File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.607: download - view: text, annotated - select for diffs
Wed Apr 7 21:08:35 2010 UTC (14 years, 1 month ago) by droeschl
Branches: MAIN
CVS tags: HEAD
Currently broken. Just saving work for Gerd.

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.607 2010/04/07 21:08:35 droeschl 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: 
   30: 
   31: package Apache::grades;
   32: use strict;
   33: use Apache::style;
   34: use Apache::lonxml;
   35: use Apache::lonnet;
   36: use Apache::loncommon;
   37: use Apache::lonhtmlcommon;
   38: use Apache::lonnavmaps;
   39: use Apache::lonhomework;
   40: use Apache::lonpickcode;
   41: use Apache::loncoursedata;
   42: use Apache::lonmsg();
   43: use Apache::Constants qw(:common);
   44: use Apache::lonlocal;
   45: use Apache::lonenc;
   46: use String::Similarity;
   47: use LONCAPA;
   48: 
   49: use POSIX qw(floor);
   50: 
   51: 
   52: 
   53: my %perm=();
   54: 
   55: #  These variables are used to recover from ssi errors
   56: 
   57: my $ssi_retries = 5;
   58: my $ssi_error;
   59: my $ssi_error_resource;
   60: my $ssi_error_message;
   61: 
   62: 
   63: sub ssi_with_retries {
   64:     my ($resource, $retries, %form) = @_;
   65:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
   66:     if ($response->is_error) {
   67: 	$ssi_error          = 1;
   68: 	$ssi_error_resource = $resource;
   69: 	$ssi_error_message  = $response->code . " " . $response->message;
   70:     }
   71: 
   72:     return $content;
   73: 
   74: }
   75: #
   76: #  Prodcuces an ssi retry failure error message to the user:
   77: #
   78: 
   79: sub ssi_print_error {
   80:     my ($r) = @_;
   81:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
   82:     $r->print('
   83: <br />
   84: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
   85: <p>
   86: '.&mt('Unable to retrieve a resource from a server:').'<br />
   87: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
   88: '.&mt('Error:').' '.$ssi_error_message.'
   89: </p>
   90: <p>'.
   91: &mt('It is recommended that you try again later, as this error may mean the server was just temporarily unavailable, or is down for maintenance.').'<br />'.
   92: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
   93: '</p>');
   94:     return;
   95: }
   96: 
   97: #
   98: # --- Retrieve the parts from the metadata file.---
   99: # Returns an array of everything that the resources stores away
  100: #
  101: 
  102: sub getpartlist {
  103:     my ($symb,$errorref) = @_;
  104: 
  105:     my $navmap   = Apache::lonnavmaps::navmap->new();
  106:     unless (ref($navmap)) {
  107:         if (ref($errorref)) { 
  108:             $$errorref = 'navmap';
  109:             return;
  110:         }
  111:     }
  112:     my $res      = $navmap->getBySymb($symb);
  113:     my $partlist = $res->parts();
  114:     my $url      = $res->src();
  115:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
  116: 
  117:     my @stores;
  118:     foreach my $part (@{ $partlist }) {
  119: 	foreach my $key (@metakeys) {
  120: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
  121: 	}
  122:     }
  123:     return @stores;
  124: }
  125: 
  126: # --- Get the symbolic name of a problem and the url
  127: # Generate an error message if symb could not be found unless silent flag is set
  128: # Takes $env{'form.symb'} by default; if not present, takes $env{'form.url'} and tries to get symb from that
  129: #
  130:  
  131: sub get_symb {
  132:     my ($request,$silent) = @_;
  133:     (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
  134:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
  135:     if ($symb eq '') { 
  136: 	if (!$silent) {
  137: 	    $request->print(&mt("Unable to handle ambiguous references: [_1].",$url));
  138: 	    return ();
  139: 	}
  140:     }
  141:     &Apache::lonenc::check_decrypt(\$symb);
  142:     return ($symb);
  143: }
  144: 
  145: #--- Format fullname, username:domain if different for display
  146: #--- Use anywhere where the student names are listed
  147: sub nameUserString {
  148:     my ($type,$fullname,$uname,$udom) = @_;
  149:     if ($type eq 'header') {
  150: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
  151:     } else {
  152: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
  153: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
  154:     }
  155: }
  156: 
  157: #--- Get the partlist and the response type for a given problem. ---
  158: #--- Indicate if a response type is coded handgraded or not. ---
  159: sub response_type {
  160:     my ($symb,$response_error) = @_;
  161: 
  162:     my $navmap = Apache::lonnavmaps::navmap->new();
  163:     unless (ref($navmap)) {
  164:         if (ref($response_error)) {
  165:             $$response_error = 1;
  166:         }
  167:         return;
  168:     }
  169:     my $res = $navmap->getBySymb($symb);
  170:     unless (ref($res)) {
  171:         $$response_error = 1;
  172:         return;
  173:     }
  174:     my $partlist = $res->parts();
  175:     my %vPart = 
  176: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
  177:     my (%response_types,%handgrade);
  178:     foreach my $part (@{ $partlist }) {
  179: 	next if (%vPart && !exists($vPart{$part}));
  180: 
  181: 	my @types = $res->responseType($part);
  182: 	my @ids = $res->responseIds($part);
  183: 	for (my $i=0; $i < scalar(@ids); $i++) {
  184: 	    $response_types{$part}{$ids[$i]} = $types[$i];
  185: 	    $handgrade{$part.'_'.$ids[$i]} = 
  186: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
  187: 				     '.handgrade',$symb);
  188: 	}
  189:     }
  190:     return ($partlist,\%handgrade,\%response_types);
  191: }
  192: 
  193: sub flatten_responseType {
  194:     my ($responseType) = @_;
  195:     my @part_response_id =
  196: 	map { 
  197: 	    my $part = $_;
  198: 	    map {
  199: 		[$part,$_]
  200: 		} sort(keys(%{ $responseType->{$part} }));
  201: 	} sort(keys(%$responseType));
  202:     return @part_response_id;
  203: }
  204: 
  205: sub get_display_part {
  206:     my ($partID,$symb)=@_;
  207:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
  208:     if (defined($display) and $display ne '') {
  209:         $display.= ' (<span class="LC_internal_info">'
  210:                   .&mt('Part ID: [_1]',$partID).'</span>)';
  211:     } else {
  212: 	$display=$partID;
  213:     }
  214:     return $display;
  215: }
  216: 
  217: sub reset_caches {
  218:     &reset_analyze_cache();
  219:     &reset_perm();
  220: }
  221: 
  222: {
  223:     my %analyze_cache;
  224:     my %analyze_cache_formkeys;
  225: 
  226:     sub reset_analyze_cache {
  227: 	undef(%analyze_cache);
  228:         undef(%analyze_cache_formkeys);
  229:     }
  230: 
  231:     sub get_analyze {
  232: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash)=@_;
  233: 	my $key = "$symb\0$uname\0$udom";
  234: 	if (exists($analyze_cache{$key})) {
  235:             my $getupdate = 0;
  236:             if (ref($add_to_hash) eq 'HASH') {
  237:                 foreach my $item (keys(%{$add_to_hash})) {
  238:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
  239:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
  240:                             $getupdate = 1;
  241:                             last;
  242:                         }
  243:                     } else {
  244:                         $getupdate = 1;
  245:                     }
  246:                 }
  247:             }
  248:             if (!$getupdate) {
  249:                 return $analyze_cache{$key};
  250:             }
  251:         }
  252: 
  253: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  254: 	$url=&Apache::lonnet::clutter($url);
  255:         my %form = ('grade_target'      => 'analyze',
  256:                     'grade_domain'      => $udom,
  257:                     'grade_symb'        => $symb,
  258:                     'grade_courseid'    =>  $env{'request.course.id'},
  259:                     'grade_username'    => $uname,
  260:                     'grade_noincrement' => $no_increment);
  261:         if (ref($add_to_hash)) {
  262:             %form = (%form,%{$add_to_hash});
  263:         } 
  264: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
  265: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  266: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  267:         if (ref($add_to_hash) eq 'HASH') {
  268:             $analyze_cache_formkeys{$key} = $add_to_hash;
  269:         } else {
  270:             $analyze_cache_formkeys{$key} = {};
  271:         }
  272: 	return $analyze_cache{$key} = \%analyze;
  273:     }
  274: 
  275:     sub get_order {
  276: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment)=@_;
  277: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment);
  278: 	return $analyze->{"$partid.$respid.shown"};
  279:     }
  280: 
  281:     sub get_radiobutton_correct_foil {
  282: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
  283: 	my $analyze = &get_analyze($symb,$uname,$udom);
  284:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom);
  285:         if (ref($foils) eq 'ARRAY') {
  286: 	    foreach my $foil (@{$foils}) {
  287: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  288: 		    return $foil;
  289: 	        }
  290: 	    }
  291: 	}
  292:     }
  293: 
  294:     sub scantron_partids_tograde {
  295:         my ($resource,$cid,$uname,$udom,$check_for_randomlist) = @_;
  296:         my (%analysis,@parts);
  297:         if (ref($resource)) {
  298:             my $symb = $resource->symb();
  299:             my $add_to_form;
  300:             if ($check_for_randomlist) {
  301:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
  302:             }
  303:             my $analyze = &get_analyze($symb,$uname,$udom,undef,$add_to_form);
  304:             if (ref($analyze) eq 'HASH') {
  305:                 %analysis = %{$analyze};
  306:             }
  307:             if (ref($analysis{'parts'}) eq 'ARRAY') {
  308:                 foreach my $part (@{$analysis{'parts'}}) {
  309:                     my ($id,$respid) = split(/\./,$part);
  310:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
  311:                         push(@parts,$part);
  312:                     }
  313:                 }
  314:             }
  315:         }
  316:         return (\%analysis,\@parts);
  317:     }
  318: 
  319: }
  320: 
  321: #--- Clean response type for display
  322: #--- Currently filters option/rank/radiobutton/match/essay/Task
  323: #        response types only.
  324: sub cleanRecord {
  325:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  326: 	$uname,$udom) = @_;
  327:     my $grayFont = '<span class="LC_internal_info">';
  328:     if ($response =~ /^(option|rank)$/) {
  329: 	my %answer=&Apache::lonnet::str2hash($answer);
  330: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  331: 	my ($toprow,$bottomrow);
  332: 	foreach my $foil (@$order) {
  333: 	    if ($grading{$foil} == 1) {
  334: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  335: 	    } else {
  336: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  337: 	    }
  338: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  339: 	}
  340: 	return '<blockquote><table border="1">'.
  341: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  342: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  343: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
  344:     } elsif ($response eq 'match') {
  345: 	my %answer=&Apache::lonnet::str2hash($answer);
  346: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  347: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  348: 	my ($toprow,$middlerow,$bottomrow);
  349: 	foreach my $foil (@$order) {
  350: 	    my $item=shift(@items);
  351: 	    if ($grading{$foil} == 1) {
  352: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  353: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  354: 	    } else {
  355: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  356: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  357: 	    }
  358: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  359: 	}
  360: 	return '<blockquote><table border="1">'.
  361: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  362: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  363: 	    $middlerow.'</tr>'.
  364: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  365: 	    $bottomrow.'</tr>'.'</table></blockquote>';
  366:     } elsif ($response eq 'radiobutton') {
  367: 	my %answer=&Apache::lonnet::str2hash($answer);
  368: 	my ($toprow,$bottomrow);
  369: 	my $correct = 
  370: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
  371: 	foreach my $foil (@$order) {
  372: 	    if (exists($answer{$foil})) {
  373: 		if ($foil eq $correct) {
  374: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  375: 		} else {
  376: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  377: 		}
  378: 	    } else {
  379: 		$toprow.='<td>'.&mt('false').'</td>';
  380: 	    }
  381: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  382: 	}
  383: 	return '<blockquote><table border="1">'.
  384: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  385: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  386: 	    $bottomrow.'</tr>'.'</table></blockquote>';
  387:     } elsif ($response eq 'essay') {
  388: 	if (! exists ($env{'form.'.$symb})) {
  389: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  390: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  391: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  392: 
  393: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  394: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  395: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  396: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  397: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  398: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  399: 	}
  400: 	$answer =~ s-\n-<br />-g;
  401: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  402:     } elsif ( $response eq 'organic') {
  403: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
  404: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  405: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  406: 	return $result;
  407:     } elsif ( $response eq 'Task') {
  408: 	if ( $answer eq 'SUBMITTED') {
  409: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  410: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  411: 	    return $result;
  412: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  413: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  414: 			       keys(%{$record}));
  415: 	    return join('<br />',($version,@matches));
  416: 			       
  417: 			       
  418: 	} else {
  419: 	    my $result =
  420: 		'<p>'
  421: 		.&mt('Overall result: [_1]',
  422: 		     $record->{$version."resource.$respid.$partid.status"})
  423: 		.'</p>';
  424: 	    
  425: 	    $result .= '<ul>';
  426: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  427: 			     keys(%{$record}));
  428: 	    foreach my $grade (sort(@grade)) {
  429: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  430: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  431: 				     $dim, $record->{$grade}).
  432: 			  '</li>';
  433: 	    }
  434: 	    $result.='</ul>';
  435: 	    return $result;
  436: 	}
  437:     } elsif ( $response =~ m/(?:numerical|formula)/) {
  438: 	$answer = 
  439: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  440: 							      $answer);
  441:     }
  442:     return $answer;
  443: }
  444: 
  445: #-- A couple of common js functions
  446: sub commonJSfunctions {
  447:     my $request = shift;
  448:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
  449:     function radioSelection(radioButton) {
  450: 	var selection=null;
  451: 	if (radioButton.length > 1) {
  452: 	    for (var i=0; i<radioButton.length; i++) {
  453: 		if (radioButton[i].checked) {
  454: 		    return radioButton[i].value;
  455: 		}
  456: 	    }
  457: 	} else {
  458: 	    if (radioButton.checked) return radioButton.value;
  459: 	}
  460: 	return selection;
  461:     }
  462: 
  463:     function pullDownSelection(selectOne) {
  464: 	var selection="";
  465: 	if (selectOne.length > 1) {
  466: 	    for (var i=0; i<selectOne.length; i++) {
  467: 		if (selectOne[i].selected) {
  468: 		    return selectOne[i].value;
  469: 		}
  470: 	    }
  471: 	} else {
  472:             // only one value it must be the selected one
  473: 	    return selectOne.value;
  474: 	}
  475:     }
  476: COMMONJSFUNCTIONS
  477: }
  478: 
  479: #--- Dumps the class list with usernames,list of sections,
  480: #--- section, ids and fullnames for each user.
  481: sub getclasslist {
  482:     my ($getsec,$filterlist,$getgroup) = @_;
  483:     my @getsec;
  484:     my @getgroup;
  485:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  486:     if (!ref($getsec)) {
  487: 	if ($getsec ne '' && $getsec ne 'all') {
  488: 	    @getsec=($getsec);
  489: 	}
  490:     } else {
  491: 	@getsec=@{$getsec};
  492:     }
  493:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  494:     if (!ref($getgroup)) {
  495: 	if ($getgroup ne '' && $getgroup ne 'all') {
  496: 	    @getgroup=($getgroup);
  497: 	}
  498:     } else {
  499: 	@getgroup=@{$getgroup};
  500:     }
  501:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  502: 
  503:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  504:     # Bail out if we were unable to get the classlist
  505:     return if (! defined($classlist));
  506:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  507:     #
  508:     my %sections;
  509:     my %fullnames;
  510:     foreach my $student (keys(%$classlist)) {
  511:         my $end      = 
  512:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  513:         my $start    = 
  514:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  515:         my $id       = 
  516:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  517:         my $section  = 
  518:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  519:         my $fullname = 
  520:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  521:         my $status   = 
  522:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  523:         my $group   = 
  524:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  525: 	# filter students according to status selected
  526: 	if ($filterlist && (!($stu_status =~ /Any/))) {
  527: 	    if (!($stu_status =~ $status)) {
  528: 		delete($classlist->{$student});
  529: 		next;
  530: 	    }
  531: 	}
  532: 	# filter students according to groups selected
  533: 	my @stu_groups = split(/,/,$group);
  534: 	if (@getgroup) {
  535: 	    my $exclude = 1;
  536: 	    foreach my $grp (@getgroup) {
  537: 	        foreach my $stu_group (@stu_groups) {
  538: 	            if ($stu_group eq $grp) {
  539: 	                $exclude = 0;
  540:     	            } 
  541: 	        }
  542:     	        if (($grp eq 'none') && !$group) {
  543:         	        $exclude = 0;
  544:         	}
  545: 	    }
  546: 	    if ($exclude) {
  547: 	        delete($classlist->{$student});
  548: 	    }
  549: 	}
  550: 	$section = ($section ne '' ? $section : 'none');
  551: 	if (&canview($section)) {
  552: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  553: 		$sections{$section}++;
  554: 		if ($classlist->{$student}) {
  555: 		    $fullnames{$student}=$fullname;
  556: 		}
  557: 	    } else {
  558: 		delete($classlist->{$student});
  559: 	    }
  560: 	} else {
  561: 	    delete($classlist->{$student});
  562: 	}
  563:     }
  564:     my %seen = ();
  565:     my @sections = sort(keys(%sections));
  566:     return ($classlist,\@sections,\%fullnames);
  567: }
  568: 
  569: sub canmodify {
  570:     my ($sec)=@_;
  571:     if ($perm{'mgr'}) {
  572: 	if (!defined($perm{'mgr_section'})) {
  573: 	    # can modify whole class
  574: 	    return 1;
  575: 	} else {
  576: 	    if ($sec eq $perm{'mgr_section'}) {
  577: 		#can modify the requested section
  578: 		return 1;
  579: 	    } else {
  580: 		# can't modify the request section
  581: 		return 0;
  582: 	    }
  583: 	}
  584:     }
  585:     #can't modify
  586:     return 0;
  587: }
  588: 
  589: sub canview {
  590:     my ($sec)=@_;
  591:     if ($perm{'vgr'}) {
  592: 	if (!defined($perm{'vgr_section'})) {
  593: 	    # can modify whole class
  594: 	    return 1;
  595: 	} else {
  596: 	    if ($sec eq $perm{'vgr_section'}) {
  597: 		#can modify the requested section
  598: 		return 1;
  599: 	    } else {
  600: 		# can't modify the request section
  601: 		return 0;
  602: 	    }
  603: 	}
  604:     }
  605:     #can't modify
  606:     return 0;
  607: }
  608: 
  609: #--- Retrieve the grade status of a student for all the parts
  610: sub student_gradeStatus {
  611:     my ($symb,$udom,$uname,$partlist) = @_;
  612:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  613:     my %partstatus = ();
  614:     foreach (@$partlist) {
  615: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  616: 	$status              = 'nothing' if ($status eq '');
  617: 	$partstatus{$_}      = $status;
  618: 	my $subkey           = "resource.$_.submitted_by";
  619: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  620:     }
  621:     return %partstatus;
  622: }
  623: 
  624: # hidden form and javascript that calls the form
  625: # Use by verifyscript and viewgrades
  626: # Shows a student's view of problem and submission
  627: sub jscriptNform {
  628:     my ($symb) = @_;
  629:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  630:     my $jscript= &Apache::lonhtmlcommon::scripttag(
  631: 	'    function viewOneStudent(user,domain) {'."\n".
  632: 	'	document.onestudent.student.value = user;'."\n".
  633: 	'	document.onestudent.userdom.value = domain;'."\n".
  634: 	'	document.onestudent.submit();'."\n".
  635: 	'    }'."\n".
  636: 	"\n");
  637:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  638: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  639: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
  640: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  641: 	'<input type="hidden" name="command" value="submission" />'."\n".
  642: 	'<input type="hidden" name="student" value="" />'."\n".
  643: 	'<input type="hidden" name="userdom" value="" />'."\n".
  644: 	'</form>'."\n";
  645:     return $jscript;
  646: }
  647: 
  648: 
  649: 
  650: # Given the score (as a number [0-1] and the weight) what is the final
  651: # point value? This function will round to the nearest tenth, third,
  652: # or quarter if one of those is within the tolerance of .00001.
  653: sub compute_points {
  654:     my ($score, $weight) = @_;
  655:     
  656:     my $tolerance = .00001;
  657:     my $points = $score * $weight;
  658: 
  659:     # Check for nearness to 1/x.
  660:     my $check_for_nearness = sub {
  661:         my ($factor) = @_;
  662:         my $num = ($points * $factor) + $tolerance;
  663:         my $floored_num = floor($num);
  664:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  665:             return $floored_num / $factor;
  666:         }
  667:         return $points;
  668:     };
  669: 
  670:     $points = $check_for_nearness->(10);
  671:     $points = $check_for_nearness->(3);
  672:     $points = $check_for_nearness->(4);
  673:     
  674:     return $points;
  675: }
  676: 
  677: #------------------ End of general use routines --------------------
  678: 
  679: #
  680: # Find most similar essay
  681: #
  682: 
  683: sub most_similar {
  684:     my ($uname,$udom,$uessay,$old_essays)=@_;
  685: 
  686: # ignore spaces and punctuation
  687: 
  688:     $uessay=~s/\W+/ /gs;
  689: 
  690: # ignore empty submissions (occuring when only files are sent)
  691: 
  692:     unless ($uessay=~/\w+/s) { return ''; }
  693: 
  694: # these will be returned. Do not care if not at least 50 percent similar
  695:     my $limit=0.6;
  696:     my $sname='';
  697:     my $sdom='';
  698:     my $scrsid='';
  699:     my $sessay='';
  700: # go through all essays ...
  701:     foreach my $tkey (keys(%$old_essays)) {
  702: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  703: # ... except the same student
  704:         next if (($tname eq $uname) && ($tdom eq $udom));
  705: 	my $tessay=$old_essays->{$tkey};
  706: 	$tessay=~s/\W+/ /gs;
  707: # String similarity gives up if not even limit
  708: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  709: # Found one
  710: 	if ($tsimilar>$limit) {
  711: 	    $limit=$tsimilar;
  712: 	    $sname=$tname;
  713: 	    $sdom=$tdom;
  714: 	    $scrsid=$tcrsid;
  715: 	    $sessay=$old_essays->{$tkey};
  716: 	}
  717:     }
  718:     if ($limit>0.6) {
  719:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  720:     } else {
  721:        return ('','','','',0);
  722:     }
  723: }
  724: 
  725: #-------------------------------------------------------------------
  726: 
  727: #------------------------------------ Receipt Verification Routines
  728: #
  729: 
  730: sub initialverifyreceipt {
  731:    my $request = shift;
  732:    &commonJSfunctions($request);
  733:    my ($symb)   = &get_symb($request);
  734:    return '<form name="gradingMenu"><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
  735:         &Apache::lonnet::recprefix($env{'request.course.id'}).
  736:         '-<input type="text" name="receipt" size="4" />'.
  737:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  738:         '<input type="hidden" name="command" value="verify" />'.
  739:         "</form>\n";
  740: }
  741: 
  742: #--- Check whether a receipt number is valid.---
  743: sub verifyreceipt {
  744:     my $request  = shift;
  745: 
  746:     my $courseid = $env{'request.course.id'};
  747:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  748: 	$env{'form.receipt'};
  749:     $receipt     =~ s/[^\-\d]//g;
  750:     my ($symb)   = &get_symb($request);
  751: 
  752:     my $title.=
  753: 	'<h3><span class="LC_info">'.
  754: 	&mt('Verifying Receipt Number [_1]',$receipt).
  755: 	'</span></h3>'."\n";
  756: 
  757:     my ($string,$contents,$matches) = ('','',0);
  758:     my (undef,undef,$fullname) = &getclasslist('all','0');
  759:     
  760:     my $receiptparts=0;
  761:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  762: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  763:     my $parts=['0'];
  764:     if ($receiptparts) {
  765:         my $res_error; 
  766:         ($parts)=&response_type($symb,\$res_error);
  767:         if ($res_error) {
  768:             return &navmap_errormsg();
  769:         } 
  770:     }
  771:     
  772:     my $header = 
  773: 	&Apache::loncommon::start_data_table().
  774: 	&Apache::loncommon::start_data_table_header_row().
  775: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  776: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  777: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  778:     if ($receiptparts) {
  779: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  780:     }
  781:     $header.=
  782: 	&Apache::loncommon::end_data_table_header_row();
  783: 
  784:     foreach (sort 
  785: 	     {
  786: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  787: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  788: 		 }
  789: 		 return $a cmp $b;
  790: 	     } (keys(%$fullname))) {
  791: 	my ($uname,$udom)=split(/\:/);
  792: 	foreach my $part (@$parts) {
  793: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  794: 		$contents.=
  795: 		    &Apache::loncommon::start_data_table_row().
  796: 		    '<td>&nbsp;'."\n".
  797: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  798: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  799: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  800: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  801: 		if ($receiptparts) {
  802: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  803: 		}
  804: 		$contents.= 
  805: 		    &Apache::loncommon::end_data_table_row()."\n";
  806: 		
  807: 		$matches++;
  808: 	    }
  809: 	}
  810:     }
  811:     if ($matches == 0) {
  812:         $string = $title
  813:                  .'<p class="LC_warning">'
  814:                  .&mt('No match found for the above receipt number.')
  815:                  .'</p>';
  816:     } else {
  817: 	$string = &jscriptNform($symb).$title.
  818: 	    '<p>'.
  819: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
  820: 	    '</p>'.
  821: 	    $header.
  822: 	    $contents.
  823: 	    &Apache::loncommon::end_data_table()."\n";
  824:     }
  825:     return $string.&show_grading_menu_form($symb);
  826: }
  827: 
  828: #--- This is called by a number of programs.
  829: #--- Called from the Grading Menu - View/Grade an individual student
  830: #--- Also called directly when one clicks on the subm button 
  831: #    on the problem page.
  832: sub listStudents {
  833:     my ($request) = shift;
  834: 
  835:     my ($symb) = &get_symb($request);
  836:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  837:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  838:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  839:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  840:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  841:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
  842: 
  843:     my $result='<h3><span class="LC_info">&nbsp;'
  844: 	.&mt("$viewgrade Submissions for a Student or a Group of Students")
  845: 	.'</span></h3>';
  846: 
  847:     my ($partlist,$handgrade,$responseType) = &response_type($symb
  848: #,$res_error
  849:     );
  850: 
  851:     my %lt = &Apache::lonlocal::texthash (
  852: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
  853: 		'single'   => 'Please select the student before clicking on the Next button.',
  854: 	     );
  855:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
  856:     function checkSelect(checkBox) {
  857: 	var ctr=0;
  858: 	var sense="";
  859: 	if (checkBox.length > 1) {
  860: 	    for (var i=0; i<checkBox.length; i++) {
  861: 		if (checkBox[i].checked) {
  862: 		    ctr++;
  863: 		}
  864: 	    }
  865: 	    sense = '$lt{'multiple'}';
  866: 	} else {
  867: 	    if (checkBox.checked) {
  868: 		ctr = 1;
  869: 	    }
  870: 	    sense = '$lt{'single'}';
  871: 	}
  872: 	if (ctr == 0) {
  873: 	    alert(sense);
  874: 	    return false;
  875: 	}
  876: 	document.gradesub.submit();
  877:     }
  878: 
  879:     function reLoadList(formname) {
  880: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  881: 	formname.command.value = 'submission';
  882: 	formname.submit();
  883:     }
  884: LISTJAVASCRIPT
  885: 
  886:     &commonJSfunctions($request);
  887:     $request->print($result);
  888: 
  889:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
  890:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
  891:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  892: 	"\n";
  893: 	
  894:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
  895:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
  896:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
  897:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
  898:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
  899:                   .&Apache::lonhtmlcommon::row_closure();
  900:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
  901:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
  902:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
  903:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
  904:                   .&Apache::lonhtmlcommon::row_closure();
  905: 
  906:     my $submission_options;
  907:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
  908: 	$submission_options.=
  909: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
  910:     }
  911:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  912:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  913:     $env{'form.Status'} = $saveStatus;
  914:     $submission_options.=
  915:         '<span class="LC_nobreak">'.
  916:         '<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.
  917:         &mt('last submission only').' </label></span>'."\n".
  918:         '<span class="LC_nobreak">'.
  919:         '<label><input type="radio" name="lastSub" value="last" /> '.
  920:         &mt('last submission &amp; parts info').' </label></span>'."\n".
  921:         '<span class="LC_nobreak">'.
  922:         '<label><input type="radio" name="lastSub" value="datesub" /> '.
  923:         &mt('by dates and submissions').'</label></span>'."\n".
  924:         '<span class="LC_nobreak">'.
  925:         '<label><input type="radio" name="lastSub" value="all" /> '.
  926:         &mt('all details').'</label></span>';
  927:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
  928:                   .$submission_options
  929:                   .&Apache::lonhtmlcommon::row_closure();
  930: 
  931:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
  932:                   .'<select name="increment">'
  933:                   .'<option value="1">'.&mt('Whole Points').'</option>'
  934:                   .'<option value=".5">'.&mt('Half Points').'</option>'
  935:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
  936:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
  937:                   .'</select>'
  938:                   .&Apache::lonhtmlcommon::row_closure();
  939: 
  940:     $gradeTable .= 
  941:         &build_section_inputs().
  942: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
  943: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
  944: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
  945: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
  946: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  947: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
  948: 
  949:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
  950: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
  951:     } else {
  952:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
  953:                       .&Apache::lonhtmlcommon::StatusOptions(
  954:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
  955:                       .&Apache::lonhtmlcommon::row_closure();
  956:     }
  957: 
  958:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
  959:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
  960:                   .&Apache::lonhtmlcommon::row_closure(1)
  961:                   .&Apache::lonhtmlcommon::end_pick_box();
  962: 
  963:     $gradeTable .= '<p>'
  964:                   .&mt('To '.lc($viewgrade)." a submission or a group of submissions, click on the check box(es) next to the student's name(s). Then click on the Next button.")."\n"
  965:                   .'<input type="hidden" name="command" value="processGroup" />'
  966:                   .'</p>';
  967: 
  968: # checkall buttons
  969:     $gradeTable.=&check_script('gradesub', 'stuinfo');
  970:     $gradeTable.='<input type="button" '."\n".
  971:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
  972:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
  973:     $gradeTable.=&check_buttons();
  974:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
  975:     $gradeTable.= &Apache::loncommon::start_data_table().
  976: 	&Apache::loncommon::start_data_table_header_row();
  977:     my $loop = 0;
  978:     while ($loop < 2) {
  979: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
  980: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
  981: 	if ($env{'form.showgrading'} eq 'yes' 
  982: 	    && $submitonly ne 'queued'
  983: 	    && $submitonly ne 'all') {
  984: 	    foreach my $part (sort(@$partlist)) {
  985: 		my $display_part=
  986: 		    &get_display_part((split(/_/,$part))[0],$symb);
  987: 		$gradeTable.=
  988: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
  989: 	    }
  990: 	} elsif ($submitonly eq 'queued') {
  991: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
  992: 	}
  993: 	$loop++;
  994: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
  995:     }
  996:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
  997: 
  998:     my $ctr = 0;
  999:     foreach my $student (sort 
 1000: 			 {
 1001: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 1002: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 1003: 			     }
 1004: 			     return $a cmp $b;
 1005: 			 }
 1006: 			 (keys(%$fullname))) {
 1007: 	my ($uname,$udom) = split(/:/,$student);
 1008: 
 1009: 	my %status = ();
 1010: 
 1011: 	if ($submitonly eq 'queued') {
 1012: 	    my %queue_status = 
 1013: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 1014: 							$udom,$uname);
 1015: 	    next if (!defined($queue_status{'gradingqueue'}));
 1016: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
 1017: 	}
 1018: 
 1019: 	if ($env{'form.showgrading'} eq 'yes' 
 1020: 	    && $submitonly ne 'queued'
 1021: 	    && $submitonly ne 'all') {
 1022: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
 1023: 	    my $submitted = 0;
 1024: 	    my $graded = 0;
 1025: 	    my $incorrect = 0;
 1026: 	    foreach (keys(%status)) {
 1027: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1028: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1029: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1030: 		
 1031: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1032: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1033: 		    $submitted = 0;
 1034: 		    my ($part)=split(/\./,$partid);
 1035: 		    $gradeTable.='<input type="hidden" name="'.
 1036: 			$student.':'.$part.':submitted_by" value="'.
 1037: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1038: 		}
 1039: 	    }
 1040: 	    
 1041: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1042: 				     $submitonly eq 'incorrect' ||
 1043: 				     $submitonly eq 'graded'));
 1044: 	    next if (!$graded && ($submitonly eq 'graded'));
 1045: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1046: 	}
 1047: 
 1048: 	$ctr++;
 1049: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1050:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1051: 	if ( $perm{'vgr'} eq 'F' ) {
 1052: 	    if ($ctr%2 ==1) {
 1053: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1054: 	    }
 1055: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1056:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1057:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1058: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1059: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1060: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1061: 
 1062: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
 1063: 		foreach (sort(keys(%status))) {
 1064: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1065: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1066: 		}
 1067: 	    }
 1068: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1069: 	    if ($ctr%2 ==0) {
 1070: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1071: 	    }
 1072: 	}
 1073:     }
 1074:     if ($ctr%2 ==1) {
 1075: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1076: 	    if ($env{'form.showgrading'} eq 'yes' 
 1077: 		&& $submitonly ne 'queued'
 1078: 		&& $submitonly ne 'all') {
 1079: 		foreach (@$partlist) {
 1080: 		    $gradeTable.='<td>&nbsp;</td>';
 1081: 		}
 1082: 	    } elsif ($submitonly eq 'queued') {
 1083: 		$gradeTable.='<td>&nbsp;</td>';
 1084: 	    }
 1085: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1086:     }
 1087: 
 1088:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1089:         '<input type="button" '.
 1090:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
 1091:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1092:     if ($ctr == 0) {
 1093: 	my $num_students=(scalar(keys(%$fullname)));
 1094: 	if ($num_students eq 0) {
 1095: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1096: 	} else {
 1097: 	    my $submissions='submissions';
 1098: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1099: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1100: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1101: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1102: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
 1103: 		    $num_students).
 1104: 		'</span><br />';
 1105: 	}
 1106:     } elsif ($ctr == 1) {
 1107: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1108:     }
 1109:     $gradeTable.=&show_grading_menu_form($symb);
 1110:     $request->print($gradeTable);
 1111:     return '';
 1112: }
 1113: 
 1114: #---- Called from the listStudents routine
 1115: 
 1116: sub check_script {
 1117:     my ($form, $type)=@_;
 1118:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
 1119:     function checkall() {
 1120:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1121:             ele = document.forms.'.$form.'.elements[i];
 1122:             if (ele.name == "'.$type.'") {
 1123:             document.forms.'.$form.'.elements[i].checked=true;
 1124:                                        }
 1125:         }
 1126:     }
 1127: 
 1128:     function checksec() {
 1129:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1130:             ele = document.forms.'.$form.'.elements[i];
 1131:            string = document.forms.'.$form.'.chksec.value;
 1132:            if
 1133:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1134:               document.forms.'.$form.'.elements[i].checked=true;
 1135:             }
 1136:         }
 1137:     }
 1138: 
 1139: 
 1140:     function uncheckall() {
 1141:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1142:             ele = document.forms.'.$form.'.elements[i];
 1143:             if (ele.name == "'.$type.'") {
 1144:             document.forms.'.$form.'.elements[i].checked=false;
 1145:                                        }
 1146:         }
 1147:     }
 1148: 
 1149: '."\n");
 1150:     return $chkallscript;
 1151: }
 1152: 
 1153: sub check_buttons {
 1154:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1155:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1156:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1157:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1158:     return $buttons;
 1159: }
 1160: 
 1161: #     Displays the submissions for one student or a group of students
 1162: sub processGroup {
 1163:     my ($request)  = shift;
 1164:     my $ctr        = 0;
 1165:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1166:     my $total      = scalar(@stuchecked)-1;
 1167: 
 1168:     foreach my $student (@stuchecked) {
 1169: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1170: 	$env{'form.student'}        = $uname;
 1171: 	$env{'form.userdom'}        = $udom;
 1172: 	$env{'form.fullname'}       = $fullname;
 1173: 	&submission($request,$ctr,$total);
 1174: 	$ctr++;
 1175:     }
 1176:     return '';
 1177: }
 1178: 
 1179: #------------------------------------------------------------------------------------
 1180: #
 1181: #-------------------------- Next few routines handles grading by student, essentially
 1182: #                           handles essay response type problem/part
 1183: #
 1184: #--- Javascript to handle the submission page functionality ---
 1185: sub sub_page_js {
 1186:     my $request = shift;
 1187: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1188:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1189:     function updateRadio(formname,id,weight) {
 1190: 	var gradeBox = formname["GD_BOX"+id];
 1191: 	var radioButton = formname["RADVAL"+id];
 1192: 	var oldpts = formname["oldpts"+id].value;
 1193: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1194: 	gradeBox.value = pts;
 1195: 	var resetbox = false;
 1196: 	if (isNaN(pts) || pts < 0) {
 1197: 	    alert("$alertmsg"+pts);
 1198: 	    for (var i=0; i<radioButton.length; i++) {
 1199: 		if (radioButton[i].checked) {
 1200: 		    gradeBox.value = i;
 1201: 		    resetbox = true;
 1202: 		}
 1203: 	    }
 1204: 	    if (!resetbox) {
 1205: 		formtextbox.value = "";
 1206: 	    }
 1207: 	    return;
 1208: 	}
 1209: 
 1210: 	if (pts > weight) {
 1211: 	    var resp = confirm("You entered a value ("+pts+
 1212: 			       ") greater than the weight for the part. Accept?");
 1213: 	    if (resp == false) {
 1214: 		gradeBox.value = oldpts;
 1215: 		return;
 1216: 	    }
 1217: 	}
 1218: 
 1219: 	for (var i=0; i<radioButton.length; i++) {
 1220: 	    radioButton[i].checked=false;
 1221: 	    if (pts == i && pts != "") {
 1222: 		radioButton[i].checked=true;
 1223: 	    }
 1224: 	}
 1225: 	updateSelect(formname,id);
 1226: 	formname["stores"+id].value = "0";
 1227:     }
 1228: 
 1229:     function writeBox(formname,id,pts) {
 1230: 	var gradeBox = formname["GD_BOX"+id];
 1231: 	if (checkSolved(formname,id) == 'update') {
 1232: 	    gradeBox.value = pts;
 1233: 	} else {
 1234: 	    var oldpts = formname["oldpts"+id].value;
 1235: 	    gradeBox.value = oldpts;
 1236: 	    var radioButton = formname["RADVAL"+id];
 1237: 	    for (var i=0; i<radioButton.length; i++) {
 1238: 		radioButton[i].checked=false;
 1239: 		if (i == oldpts) {
 1240: 		    radioButton[i].checked=true;
 1241: 		}
 1242: 	    }
 1243: 	}
 1244: 	formname["stores"+id].value = "0";
 1245: 	updateSelect(formname,id);
 1246: 	return;
 1247:     }
 1248: 
 1249:     function clearRadBox(formname,id) {
 1250: 	if (checkSolved(formname,id) == 'noupdate') {
 1251: 	    updateSelect(formname,id);
 1252: 	    return;
 1253: 	}
 1254: 	gradeSelect = formname["GD_SEL"+id];
 1255: 	for (var i=0; i<gradeSelect.length; i++) {
 1256: 	    if (gradeSelect[i].selected) {
 1257: 		var selectx=i;
 1258: 	    }
 1259: 	}
 1260: 	var stores = formname["stores"+id];
 1261: 	if (selectx == stores.value) { return };
 1262: 	var gradeBox = formname["GD_BOX"+id];
 1263: 	gradeBox.value = "";
 1264: 	var radioButton = formname["RADVAL"+id];
 1265: 	for (var i=0; i<radioButton.length; i++) {
 1266: 	    radioButton[i].checked=false;
 1267: 	}
 1268: 	stores.value = selectx;
 1269:     }
 1270: 
 1271:     function checkSolved(formname,id) {
 1272: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1273: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1274: 	    if (!reply) {return "noupdate";}
 1275: 	    formname.overRideScore.value = 'yes';
 1276: 	}
 1277: 	return "update";
 1278:     }
 1279: 
 1280:     function updateSelect(formname,id) {
 1281: 	formname["GD_SEL"+id][0].selected = true;
 1282: 	return;
 1283:     }
 1284: 
 1285: //=========== Check that a point is assigned for all the parts  ============
 1286:     function checksubmit(formname,val,total,parttot) {
 1287: 	formname.gradeOpt.value = val;
 1288: 	if (val == "Save & Next") {
 1289: 	    for (i=0;i<=total;i++) {
 1290: 		for (j=0;j<parttot;j++) {
 1291: 		    var partid = formname["partid"+i+"_"+j].value;
 1292: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1293: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1294: 			if (points == "") {
 1295: 			    var name = formname["name"+i].value;
 1296: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1297: 			    var resp = confirm("You did not assign a score for "+studentID+
 1298: 					       ", part "+partid+". Continue?");
 1299: 			    if (resp == false) {
 1300: 				formname["GD_BOX"+i+"_"+partid].focus();
 1301: 				return false;
 1302: 			    }
 1303: 			}
 1304: 		    }
 1305: 		    
 1306: 		}
 1307: 	    }
 1308: 	    
 1309: 	}
 1310: 	if (val == "Grade Student") {
 1311: 	    formname.showgrading.value = "yes";
 1312: 	    if (formname.Status.value == "") {
 1313: 		formname.Status.value = "Active";
 1314: 	    }
 1315: 	    formname.studentNo.value = total;
 1316: 	}
 1317: 	formname.submit();
 1318:     }
 1319: 
 1320: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1321:     function checkSubmitPage(formname,total) {
 1322: 	noscore = new Array(100);
 1323: 	var ptr = 0;
 1324: 	for (i=1;i<total;i++) {
 1325: 	    var partid = formname["q_"+i].value;
 1326: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1327: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1328: 		var status = formname["solved"+i+"_"+partid].value;
 1329: 		if (points == "" && status != "correct_by_student") {
 1330: 		    noscore[ptr] = i;
 1331: 		    ptr++;
 1332: 		}
 1333: 	    }
 1334: 	}
 1335: 	if (ptr != 0) {
 1336: 	    var sense = ptr == 1 ? ": " : "s: ";
 1337: 	    var prolist = "";
 1338: 	    if (ptr == 1) {
 1339: 		prolist = noscore[0];
 1340: 	    } else {
 1341: 		var i = 0;
 1342: 		while (i < ptr-1) {
 1343: 		    prolist += noscore[i]+", ";
 1344: 		    i++;
 1345: 		}
 1346: 		prolist += "and "+noscore[i];
 1347: 	    }
 1348: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1349: 	    if (resp == false) {
 1350: 		return false;
 1351: 	    }
 1352: 	}
 1353: 
 1354: 	formname.submit();
 1355:     }
 1356: SUBJAVASCRIPT
 1357: }
 1358: 
 1359: #--- javascript for essay type problem --
 1360: sub sub_page_kw_js {
 1361:     my $request = shift;
 1362:     my $iconpath = $request->dir_config('lonIconsURL');
 1363:     &commonJSfunctions($request);
 1364: 
 1365:     my $inner_js_msg_central= &Apache::lonhtmlcommon::scripttag(<<INNERJS);
 1366:     function checkInput() {
 1367:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1368:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1369:       var usrctr = document.msgcenter.usrctr.value;
 1370:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1371:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1372: 
 1373:       var msgchk = "";
 1374:       if (document.msgcenter.subchk.checked) {
 1375:          msgchk = "msgsub,";
 1376:       }
 1377:       var includemsg = 0;
 1378:       for (var i=1; i<=nmsg; i++) {
 1379:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1380:           var frmmsg = document.msgcenter["msg"+i];
 1381:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1382:           var showflg = opener.document.SCORE["shownOnce"+i];
 1383:           showflg.value = "1";
 1384:           var chkbox = document.msgcenter["msgn"+i];
 1385:           if (chkbox.checked) {
 1386:              msgchk += "savemsg"+i+",";
 1387:              includemsg = 1;
 1388:           }
 1389:       }
 1390:       if (document.msgcenter.newmsgchk.checked) {
 1391:          msgchk += "newmsg"+usrctr;
 1392:          includemsg = 1;
 1393:       }
 1394:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1395:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1396:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1397:       includemsg.value = msgchk;
 1398: 
 1399:       self.close()
 1400: 
 1401:     }
 1402: INNERJS
 1403: 
 1404:     my $inner_js_highlight_central= &Apache::lonhtmlcommon::scripttag(<<INNERJS);
 1405:     function updateChoice(flag) {
 1406:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1407:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1408:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1409:       opener.document.SCORE.refresh.value = "on";
 1410:       if (opener.document.SCORE.keywords.value!=""){
 1411:          opener.document.SCORE.submit();
 1412:       }
 1413:       self.close()
 1414:     }
 1415: INNERJS
 1416: 
 1417:     my $start_page_msg_central = 
 1418:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1419: 				       {'js_ready'  => 1,
 1420: 					'only_body' => 1,
 1421: 					'bgcolor'   =>'#FFFFFF',});
 1422:     my $end_page_msg_central = 
 1423: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1424: 
 1425: 
 1426:     my $start_page_highlight_central = 
 1427:         &Apache::loncommon::start_page('Highlight Central',
 1428: 				       $inner_js_highlight_central,
 1429: 				       {'js_ready'  => 1,
 1430: 					'only_body' => 1,
 1431: 					'bgcolor'   =>'#FFFFFF',});
 1432:     my $end_page_highlight_central = 
 1433: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1434: 
 1435:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1436:     $docopen=~s/^document\.//;
 1437:     my $alertmsg = &mt('Please select a word or group of words from document and then click this link.');
 1438:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1439: 
 1440: //===================== Show list of keywords ====================
 1441:   function keywords(formname) {
 1442:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
 1443:     if (nret==null) return;
 1444:     formname.keywords.value = nret;
 1445: 
 1446:     if (formname.keywords.value != "") {
 1447: 	formname.refresh.value = "on";
 1448: 	formname.submit();
 1449:     }
 1450:     return;
 1451:   }
 1452: 
 1453: //===================== Script to view submitted by ==================
 1454:   function viewSubmitter(submitter) {
 1455:     document.SCORE.refresh.value = "on";
 1456:     document.SCORE.NCT.value = "1";
 1457:     document.SCORE.unamedom0.value = submitter;
 1458:     document.SCORE.submit();
 1459:     return;
 1460:   }
 1461: 
 1462: //===================== Script to add keyword(s) ==================
 1463:   function getSel() {
 1464:     if (document.getSelection) txt = document.getSelection();
 1465:     else if (document.selection) txt = document.selection.createRange().text;
 1466:     else return;
 1467:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1468:     if (cleantxt=="") {
 1469: 	alert("$alertmsg");
 1470: 	return;
 1471:     }
 1472:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
 1473:     if (nret==null) return;
 1474:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1475:     if (document.SCORE.keywords.value != "") {
 1476: 	document.SCORE.refresh.value = "on";
 1477: 	document.SCORE.submit();
 1478:     }
 1479:     return;
 1480:   }
 1481: 
 1482: //====================== Script for composing message ==============
 1483:    // preload images
 1484:    img1 = new Image();
 1485:    img1.src = "$iconpath/mailbkgrd.gif";
 1486:    img2 = new Image();
 1487:    img2.src = "$iconpath/mailto.gif";
 1488: 
 1489:   function msgCenter(msgform,usrctr,fullname) {
 1490:     var Nmsg  = msgform.savemsgN.value;
 1491:     savedMsgHeader(Nmsg,usrctr,fullname);
 1492:     var subject = msgform.msgsub.value;
 1493:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1494:     re = /msgsub/;
 1495:     var shwsel = "";
 1496:     if (re.test(msgchk)) { shwsel = "checked" }
 1497:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1498:     displaySubject(checkEntities(subject),shwsel);
 1499:     for (var i=1; i<=Nmsg; i++) {
 1500: 	var testmsg = "savemsg"+i+",";
 1501: 	re = new RegExp(testmsg,"g");
 1502: 	shwsel = "";
 1503: 	if (re.test(msgchk)) { shwsel = "checked" }
 1504: 	var message = document.SCORE["savemsg"+i].value;
 1505: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1506: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1507: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1508:     }
 1509:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1510:     shwsel = "";
 1511:     re = /newmsg/;
 1512:     if (re.test(msgchk)) { shwsel = "checked" }
 1513:     newMsg(newmsg,shwsel);
 1514:     msgTail(); 
 1515:     return;
 1516:   }
 1517: 
 1518:   function checkEntities(strx) {
 1519:     if (strx.length == 0) return strx;
 1520:     var orgStr = ["&", "<", ">", '"']; 
 1521:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1522:     var counter = 0;
 1523:     while (counter < 4) {
 1524: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1525: 	counter++;
 1526:     }
 1527:     return strx;
 1528:   }
 1529: 
 1530:   function strReplace(strx, orgStr, newStr) {
 1531:     return strx.split(orgStr).join(newStr);
 1532:   }
 1533: 
 1534:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1535:     var height = 70*Nmsg+250;
 1536:     var scrollbar = "no";
 1537:     if (height > 600) {
 1538: 	height = 600;
 1539: 	scrollbar = "yes";
 1540:     }
 1541:     var xpos = (screen.width-600)/2;
 1542:     xpos = (xpos < 0) ? '0' : xpos;
 1543:     var ypos = (screen.height-height)/2-30;
 1544:     ypos = (ypos < 0) ? '0' : ypos;
 1545: 
 1546:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
 1547:     pWin.focus();
 1548:     pDoc = pWin.document;
 1549:     pDoc.$docopen;
 1550:     pDoc.write('$start_page_msg_central');
 1551: 
 1552:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1553:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1554:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
 1555: 
 1556:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1557:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1558:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
 1559: }
 1560:     function displaySubject(msg,shwsel) {
 1561:     pDoc = pWin.document;
 1562:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1563:     pDoc.write("<td>Subject<\\/td>");
 1564:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1565:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1566: }
 1567: 
 1568:   function displaySavedMsg(ctr,msg,shwsel) {
 1569:     pDoc = pWin.document;
 1570:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1571:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1572:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1573:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1574: }
 1575: 
 1576:   function newMsg(newmsg,shwsel) {
 1577:     pDoc = pWin.document;
 1578:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1579:     pDoc.write("<td align=\\"center\\">New<\\/td>");
 1580:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1581:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1582: }
 1583: 
 1584:   function msgTail() {
 1585:     pDoc = pWin.document;
 1586:     pDoc.write("<\\/table>");
 1587:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1588:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1589:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
 1590:     pDoc.write("<\\/form>");
 1591:     pDoc.write('$end_page_msg_central');
 1592:     pDoc.close();
 1593: }
 1594: 
 1595: //====================== Script for keyword highlight options ==============
 1596:   function kwhighlight() {
 1597:     var kwclr    = document.SCORE.kwclr.value;
 1598:     var kwsize   = document.SCORE.kwsize.value;
 1599:     var kwstyle  = document.SCORE.kwstyle.value;
 1600:     var redsel = "";
 1601:     var grnsel = "";
 1602:     var blusel = "";
 1603:     if (kwclr=="red")   {var redsel="checked"};
 1604:     if (kwclr=="green") {var grnsel="checked"};
 1605:     if (kwclr=="blue")  {var blusel="checked"};
 1606:     var sznsel = "";
 1607:     var sz1sel = "";
 1608:     var sz2sel = "";
 1609:     if (kwsize=="0")  {var sznsel="checked"};
 1610:     if (kwsize=="+1") {var sz1sel="checked"};
 1611:     if (kwsize=="+2") {var sz2sel="checked"};
 1612:     var synsel = "";
 1613:     var syisel = "";
 1614:     var sybsel = "";
 1615:     if (kwstyle=="")    {var synsel="checked"};
 1616:     if (kwstyle=="<i>") {var syisel="checked"};
 1617:     if (kwstyle=="<b>") {var sybsel="checked"};
 1618:     highlightCentral();
 1619:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
 1620:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
 1621:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
 1622:     highlightend();
 1623:     return;
 1624:   }
 1625: 
 1626:   function highlightCentral() {
 1627: //    if (window.hwdWin) window.hwdWin.close();
 1628:     var xpos = (screen.width-400)/2;
 1629:     xpos = (xpos < 0) ? '0' : xpos;
 1630:     var ypos = (screen.height-330)/2-30;
 1631:     ypos = (ypos < 0) ? '0' : ypos;
 1632: 
 1633:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1634:     hwdWin.focus();
 1635:     var hDoc = hwdWin.document;
 1636:     hDoc.$docopen;
 1637:     hDoc.write('$start_page_highlight_central');
 1638:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1639:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
 1640: 
 1641:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1642:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1643:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
 1644:   }
 1645: 
 1646:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1647:     var hDoc = hwdWin.document;
 1648:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1649:     hDoc.write("<td align=\\"left\\">");
 1650:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
 1651:     hDoc.write("<td align=\\"left\\">");
 1652:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
 1653:     hDoc.write("<td align=\\"left\\">");
 1654:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
 1655:     hDoc.write("<\\/tr>");
 1656:   }
 1657: 
 1658:   function highlightend() { 
 1659:     var hDoc = hwdWin.document;
 1660:     hDoc.write("<\\/table>");
 1661:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1662:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
 1663:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
 1664:     hDoc.write("<\\/form>");
 1665:     hDoc.write('$end_page_highlight_central');
 1666:     hDoc.close();
 1667:   }
 1668: 
 1669: SUBJAVASCRIPT
 1670: }
 1671: 
 1672: sub get_increment {
 1673:     my $increment = $env{'form.increment'};
 1674:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1675:         $increment != .1) {
 1676:         $increment = 1;
 1677:     }
 1678:     return $increment;
 1679: }
 1680: 
 1681: sub gradeBox_start {
 1682:     return (
 1683:         &Apache::loncommon::start_data_table()
 1684:        .&Apache::loncommon::start_data_table_header_row()
 1685:        .'<th>'.&mt('Part').'</th>'
 1686:        .'<th>'.&mt('Points').'</th>'
 1687:        .'<th>&nbsp;</th>'
 1688:        .'<th>'.&mt('Assign Grade').'</th>'
 1689:        .'<th>'.&mt('Weight').'</th>'
 1690:        .'<th>'.&mt('Grade Status').'</th>'
 1691:        .&Apache::loncommon::end_data_table_header_row()
 1692:     );
 1693: }
 1694: 
 1695: sub gradeBox_end {
 1696:     return (
 1697:         &Apache::loncommon::end_data_table()
 1698:     );
 1699: }
 1700: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1701: sub gradeBox {
 1702:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1703:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1704: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1705:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1706:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1707:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1708:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1709:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1710: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1711:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1712:     my $display_part= &get_display_part($partid,$symb);
 1713:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1714: 				       [$partid]);
 1715:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1716:     if ($last_resets{$partid}) {
 1717:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1718:     }
 1719:     $result.=&Apache::loncommon::start_data_table_row();
 1720:     my $ctr = 0;
 1721:     my $thisweight = 0;
 1722:     my $increment = &get_increment();
 1723: 
 1724:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1725:     while ($thisweight<=$wgt) {
 1726: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1727:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1728: 	    $thisweight.')" value="'.$thisweight.'" '.
 1729: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1730: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1731:         $thisweight += $increment;
 1732: 	$ctr++;
 1733:     }
 1734:     $radio.='</tr></table>';
 1735: 
 1736:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1737: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1738: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1739: 	$wgt.')" /></td>'."\n";
 1740:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1741: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1742: 	' </td>'."\n";
 1743:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1744: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1745:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1746: 	$line.='<option></option>'.
 1747: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1748:     } else {
 1749: 	$line.='<option selected="selected"></option>'.
 1750: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1751:     }
 1752:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1753: 
 1754: 
 1755:     $result .= 
 1756: 	    '<td>'.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 1757:     $result.=&Apache::loncommon::end_data_table_row();
 1758:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1759: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1760: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1761: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1762:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1763:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1764:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1765:         $aggtries.'" />'."\n";
 1766:     my $res_error;
 1767:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 1768:     if ($res_error) {
 1769:         return &navmap_errormsg();
 1770:     }
 1771:     return $result;
 1772: }
 1773: 
 1774: sub handback_box {
 1775:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error) = @_;
 1776:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
 1777:     my (@respids);
 1778:      my @part_response_id = &flatten_responseType($responseType);
 1779:     foreach my $part_response_id (@part_response_id) {
 1780:     	my ($part,$resp) = @{ $part_response_id };
 1781:         if ($part eq $partid) {
 1782:             push(@respids,$resp);
 1783:         }
 1784:     }
 1785:     my $result;
 1786:     foreach my $respid (@respids) {
 1787: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1788: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1789: 	next if (!@$files);
 1790: 	my $file_counter = 1;
 1791: 	foreach my $file (@$files) {
 1792: 	    if ($file =~ /\/portfolio\//) {
 1793:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1794:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1795:     	        $file_disp = "$name.$ext";
 1796:     	        $file = $file_path.$file_disp;
 1797:     	        $result.=&mt('Return commented version of [_1] to student.',
 1798:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1799:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1800:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
 1801:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
 1802:     	        $file_counter++;
 1803: 	    }
 1804: 	}
 1805:     }
 1806:     return $result;    
 1807: }
 1808: 
 1809: sub show_problem {
 1810:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1811:     my $rendered;
 1812:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1813:     &Apache::lonxml::remember_problem_counter();
 1814:     if ($mode eq 'both' or $mode eq 'text') {
 1815: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1816: 						       $env{'request.course.id'},
 1817: 						       undef,\%form);
 1818:     }
 1819:     if ($removeform) {
 1820: 	$rendered=~s|<form(.*?)>||g;
 1821: 	$rendered=~s|</form>||g;
 1822: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1823:     }
 1824:     my $companswer;
 1825:     if ($mode eq 'both' or $mode eq 'answer') {
 1826: 	&Apache::lonxml::restore_problem_counter();
 1827: 	$companswer=
 1828: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1829: 						    $env{'request.course.id'},
 1830: 						    %form);
 1831:     }
 1832:     if ($removeform) {
 1833: 	$companswer=~s|<form(.*?)>||g;
 1834: 	$companswer=~s|</form>||g;
 1835: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1836:     }
 1837:     $rendered=
 1838:         '<div class="LC_Box">'
 1839:        .'<h3 class="LC_hcell">'.&mt('View of the problem').'</h3>'
 1840:        .$rendered
 1841:        .'</div>';
 1842:     $companswer=
 1843:         '<div class="LC_Box">'
 1844:        .'<h3 class="LC_hcell">'.&mt('Correct answer').'</h3>'
 1845:        .$companswer
 1846:        .'</div>';
 1847:     my $result;
 1848:     if ($mode eq 'both') {
 1849:         $result=$rendered.$companswer;
 1850:     } elsif ($mode eq 'text') {
 1851:         $result=$rendered;
 1852:     } elsif ($mode eq 'answer') {
 1853:         $result=$companswer;
 1854:     }
 1855:     return $result;
 1856: }
 1857: 
 1858: sub files_exist {
 1859:     my ($r, $symb) = @_;
 1860:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1861: 
 1862:     foreach my $student (@students) {
 1863:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1864:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1865: 					      $udom,$uname);
 1866:         my ($string,$timestamp)= &get_last_submission(\%record);
 1867:         foreach my $submission (@$string) {
 1868:             my ($partid,$respid) =
 1869: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1870:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1871: 					   \%record);
 1872:             return 1 if (@$files);
 1873:         }
 1874:     }
 1875:     return 0;
 1876: }
 1877: 
 1878: sub download_all_link {
 1879:     my ($r,$symb) = @_;
 1880:     my $all_students = 
 1881: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1882: 
 1883:     my $parts =
 1884: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1885: 
 1886:     my $identifier = &Apache::loncommon::get_cgi_id();
 1887:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 1888:                              'cgi.'.$identifier.'.symb' => $symb,
 1889:                              'cgi.'.$identifier.'.parts' => $parts,});
 1890:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1891: 	      &mt('Download All Submitted Documents').'</a>');
 1892:     return
 1893: }
 1894: 
 1895: sub build_section_inputs {
 1896:     my $section_inputs;
 1897:     if ($env{'form.section'} eq '') {
 1898:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 1899:     } else {
 1900:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 1901:         foreach my $section (@sections) {
 1902:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 1903:         }
 1904:     }
 1905:     return $section_inputs;
 1906: }
 1907: 
 1908: # --------------------------- show submissions of a student, option to grade 
 1909: sub submission {
 1910:     my ($request,$counter,$total) = @_;
 1911:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 1912:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 1913:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 1914:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 1915:     my $symb = &get_symb($request);
 1916:     my $probtitle=&Apache::lonnet::gettitle($symb); 
 1917:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 1918: 
 1919:     if (!&canview($usec)) {
 1920: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
 1921: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
 1922: 			$env{'request.course.id'}.')</span>');
 1923: 	$request->print(&show_grading_menu_form($symb));
 1924: 	return;
 1925:     }
 1926: 
 1927:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 1928:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 1929:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 1930:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 1931:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1932: 	'" src="'.$request->dir_config('lonIconsURL').
 1933: 	'/check.gif" height="16" border="0" />';
 1934: 
 1935:     my %old_essays;
 1936:     # header info
 1937:     if ($counter == 0) {
 1938: 	&sub_page_js($request);
 1939: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
 1940: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
 1941: 	    &download_all_link($request, $symb);
 1942: 	}
 1943: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>');
 1944: 
 1945: 	# option to display problem, only once else it cause problems 
 1946:         # with the form later since the problem has a form.
 1947: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 1948: 	    my $mode;
 1949: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 1950: 		$mode='both';
 1951: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 1952: 		$mode='text';
 1953: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 1954: 		$mode='answer';
 1955: 	    }
 1956: 	    &Apache::lonxml::clear_problem_counter();
 1957: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 1958: 	}
 1959: 
 1960: 	# kwclr is the only variable that is guaranteed to be non blank 
 1961:         # if this subroutine has been called once.
 1962: 	my %keyhash = ();
 1963: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 1964: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 1965: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 1966: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 1967: 
 1968: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 1969: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 1970: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 1971: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 1972: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 1973: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 1974: 		$keyhash{$symb.'_subject'} : $probtitle;
 1975: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 1976: 	}
 1977: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 1978: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 1979: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 1980: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 1981: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 1982: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 1983: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 1984: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 1985: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 1986: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 1987: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1988: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
 1989: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 1990: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 1991: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 1992: 			&build_section_inputs().
 1993: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 1994: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
 1995: 			'<input type="hidden" name="NCT"'.
 1996: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 1997: 	if ($env{'form.handgrade'} eq 'yes') {
 1998: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 1999: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 2000: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 2001: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 2002: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2003: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2004: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2005: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 2006: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 2007: 	    }
 2008: 	}
 2009: 	
 2010: 	my ($cts,$prnmsg) = (1,'');
 2011: 	while ($cts <= $env{'form.savemsgN'}) {
 2012: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2013: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2014: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2015: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2016: 		'" />'."\n".
 2017: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2018: 	    $cts++;
 2019: 	}
 2020: 	$request->print($prnmsg);
 2021: 
 2022: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
 2023: #
 2024: # Print out the keyword options line
 2025: #
 2026: 	    $request->print(<<KEYWORDS);
 2027: &nbsp;<b>Keyword Options:</b>&nbsp;
 2028: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
 2029: <a href="#" onmousedown="javascript:getSel(); return false"
 2030:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
 2031: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
 2032: KEYWORDS
 2033: #
 2034: # Load the other essays for similarity check
 2035: #
 2036:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2037: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2038: 	    $apath=&escape($apath);
 2039: 	    $apath=~s/\W/\_/gs;
 2040: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 2041:         }
 2042:     }
 2043: 
 2044: # This is where output for one specific student would start
 2045:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2046:     $request->print(
 2047:         "\n\n"
 2048:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2049:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2050:        ."\n"
 2051:     );
 2052: 
 2053:     # Show additional functions if allowed
 2054:     if ($perm{'vgr'}) {
 2055:         $request->print(
 2056:             &Apache::loncommon::track_student_link(
 2057:                 &mt('View recent activity'),
 2058:                 $uname,$udom,'check')
 2059:            .' '
 2060:         );
 2061:     }
 2062:     if ($perm{'opa'}) {
 2063:         $request->print(
 2064:             &Apache::loncommon::pprmlink(
 2065:                 &mt('Set/Change parameters'),
 2066:                 $uname,$udom,$symb,'check'));
 2067:     }
 2068: 
 2069:     # Show Problem
 2070:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2071: 	my $mode;
 2072: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2073: 	    $mode='both';
 2074: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2075: 	    $mode='text';
 2076: 	} elsif ($env{'form.vAns'} eq 'all') {
 2077: 	    $mode='answer';
 2078: 	}
 2079: 	&Apache::lonxml::clear_problem_counter();
 2080: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2081:     }
 2082: 
 2083:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2084:     my $res_error;
 2085:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2086:     if ($res_error) {
 2087:         $request->print(&navmap_errormsg());
 2088:         return;
 2089:     }
 2090: 
 2091:     # Display student info
 2092:     $request->print(($counter == 0 ? '' : '<br />'));
 2093: 
 2094:     my $result='<div class="LC_Box">'
 2095:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
 2096:     $result.='<input type="hidden" name="name'.$counter.
 2097:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2098:     if ($env{'form.handgrade'} eq 'no') {
 2099:         $result.='<p class="LC_info">'
 2100:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2101:                 ."</p>\n";
 2102:     }
 2103: 
 2104:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2105:     my $fullname;
 2106:     my $col_fullnames = [];
 2107:     if ($env{'form.handgrade'} eq 'yes') {
 2108: 	(my $sub_result,$fullname,$col_fullnames)=
 2109: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2110: 				 $counter);
 2111: 	$result.=$sub_result;
 2112:     }
 2113:     $request->print($result."\n");
 2114: 
 2115:     # print student answer/submission
 2116:     # Options are (1) Handgraded submission only
 2117:     #             (2) Last submission, includes submission that is not handgraded 
 2118:     #                  (for multi-response type part)
 2119:     #             (3) Last submission plus the parts info
 2120:     #             (4) The whole record for this student
 2121:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
 2122: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2123: 	
 2124: 	my $lastsubonly;
 2125: 
 2126:         if ($$timestamp eq '') {
 2127:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2128:         } else {
 2129:             $lastsubonly =
 2130:                 '<div class="LC_grade_submissions_body">'
 2131:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
 2132: 
 2133: 	    my %seenparts;
 2134: 	    my @part_response_id = &flatten_responseType($responseType);
 2135: 	    foreach my $part (@part_response_id) {
 2136: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2137: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2138: 
 2139: 		my ($partid,$respid) = @{ $part };
 2140: 		my $display_part=&get_display_part($partid,$symb);
 2141: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2142: 		    if (exists($seenparts{$partid})) { next; }
 2143: 		    $seenparts{$partid}=1;
 2144: 		    my $submitby='<b>Part:</b> '.$display_part.
 2145: 			' <b>Collaborative submission by:</b> '.
 2146: 			'<a href="javascript:viewSubmitter(\''.
 2147: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
 2148: 			'\');" target="_self">'.
 2149: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
 2150: 		    $request->print($submitby);
 2151: 		    next;
 2152: 		}
 2153: 		my $responsetype = $responseType->{$partid}->{$respid};
 2154: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2155:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2156:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2157:                         ' <span class="LC_internal_info">'.
 2158:                         '('.&mt('Part ID: [_1]',$respid).')'.
 2159:                         '</span>&nbsp; &nbsp;'.
 2160: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2161: 		    next;
 2162: 		}
 2163: 		foreach my $submission (@$string) {
 2164: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2165: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2166: 		    my ($ressub,$hide,$subval) = split(/:/,$submission,3);
 2167: 		    # Similarity check
 2168: 		    my $similar='';
 2169: 		    if($env{'form.checkPlag'}){
 2170: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2171: 			    &most_similar($uname,$udom,$subval,\%old_essays);
 2172: 			if ($osim) {
 2173: 			    $osim=int($osim*100.0);
 2174: 			    my %old_course_desc = 
 2175: 				&Apache::lonnet::coursedescription($ocrsid,
 2176: 								   {'one_time' => 1});
 2177: 
 2178:                             if ($hide) {
 2179:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2180:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2181:                             } else {
 2182: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
 2183: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2184: 				        $osim,
 2185: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2186: 				        $old_course_desc{'description'},
 2187: 				        $old_course_desc{'num'},
 2188: 				        $old_course_desc{'domain'}).
 2189: 				    '</span></h3><blockquote><i>'.
 2190: 				    &keywords_highlight($oessay).
 2191: 				    '</i></blockquote><hr />';
 2192:                             }
 2193: 			}
 2194: 		    }
 2195: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
 2196: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
 2197: 			($env{'form.lastSub'} eq 'hdgrade' && 
 2198: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2199: 			my $display_part=&get_display_part($partid,$symb);
 2200:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
 2201:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2202:                             ' <span class="LC_internal_info">'.
 2203:                             '('.&mt('Part ID: [_1]',$respid).')'.
 2204:                             '</span>&nbsp; &nbsp;';
 2205: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2206: 			if (@$files) {
 2207:                             if ($hide) {
 2208:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2209:                             } else {
 2210:                                 $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
 2211:                                 foreach my $file (@$files) {
 2212:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2213:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
 2214:                                 }
 2215:                             }
 2216: 			    $lastsubonly.='<br />';
 2217: 			}
 2218:                         if ($hide) {
 2219:                             $lastsubonly.='<b>'.&mt('Anonymous Survey').'</b>'; 
 2220:                         } else {
 2221: 			    $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
 2222: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
 2223: 					     $respid,\%record,$order,undef,$uname,$udom);
 2224:                         }
 2225: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2226: 			$lastsubonly.='</div>';
 2227: 		    }
 2228: 		}
 2229: 	    }
 2230: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2231: 	}
 2232: 	$request->print($lastsubonly);
 2233:    } elsif ($env{'form.lastSub'} eq 'datesub') {
 2234: #	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
 2235:     my ($parts,$handgrade,$responseType) = &response_type($symb);
 2236: 
 2237: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2238:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2239: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2240: 								 $env{'request.course.id'},
 2241: 								 $last,'.submission',
 2242: 								 'Apache::grades::keywords_highlight'));
 2243:     }
 2244: 
 2245:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2246: 	.$udom.'" />'."\n");
 2247:     # return if view submission with no grading option
 2248:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
 2249: 	my $toGrade.='<input type="button" value="Grade Student" '.
 2250: 	    'onclick="javascript:checksubmit(this.form,\'Grade Student\',\''
 2251: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
 2252: 	$toGrade.='</div>'."\n";
 2253: 	if (($env{'form.command'} eq 'submission') || 
 2254: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
 2255: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
 2256: 	}
 2257: 	$request->print($toGrade);
 2258: 	return;
 2259:     } else {
 2260: 	$request->print('</div>'."\n");
 2261:     }
 2262: 
 2263:     # essay grading message center
 2264:     if ($env{'form.handgrade'} eq 'yes') {
 2265: 	my $result='<div class="LC_grade_message_center">';
 2266:     
 2267: 	$result.='<div class="LC_grade_message_center_header">'.
 2268: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2269: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2270: 	my $msgfor = $givenn.' '.$lastname;
 2271: 	if (scalar(@$col_fullnames) > 0) {
 2272: 	    my $lastone = pop(@$col_fullnames);
 2273: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2274: 	}
 2275: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2276: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2277: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2278: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2279: 	    ',\''.$msgfor.'\');" target="_self">'.
 2280: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
 2281: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2282: 	    '<img src="'.$request->dir_config('lonIconsURL').
 2283: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2284: 	    '<br />&nbsp;('.
 2285: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2286: 	$result.='</div></div>';
 2287: 	$request->print($result);
 2288:     }
 2289: 
 2290:     my %seen = ();
 2291:     my @partlist;
 2292:     my @gradePartRespid;
 2293:     my @part_response_id = &flatten_responseType($responseType);
 2294:     $request->print(
 2295:         '<div class="LC_Box">'
 2296:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2297:     );
 2298:     $request->print(&gradeBox_start());
 2299:     foreach my $part_response_id (@part_response_id) {
 2300:     	my ($partid,$respid) = @{ $part_response_id };
 2301: 	my $part_resp = join('_',@{ $part_response_id });
 2302: 	next if ($seen{$partid} > 0);
 2303: 	$seen{$partid}++;
 2304: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2305: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2306: 	push(@partlist,$partid);
 2307: 	push(@gradePartRespid,$partid.'.'.$respid);
 2308: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2309:     }
 2310:     $request->print(&gradeBox_end()); # </div>
 2311:     $request->print('</div>');
 2312: 
 2313:     $request->print('<div class="LC_grade_info_links">');
 2314:     $request->print('</div>');
 2315: 
 2316:     $result='<input type="hidden" name="partlist'.$counter.
 2317: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2318:     $result.='<input type="hidden" name="gradePartRespid'.
 2319: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2320:     my $ctr = 0;
 2321:     while ($ctr < scalar(@partlist)) {
 2322: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2323: 	    $partlist[$ctr].'" />'."\n";
 2324: 	$ctr++;
 2325:     }
 2326:     $request->print($result.''."\n");
 2327: 
 2328: # Done with printing info for one student
 2329: 
 2330:     $request->print('</div>');#LC_grade_show_user
 2331: 
 2332: 
 2333:     # print end of form
 2334:     if ($counter == $total) {
 2335:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2336: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2337: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2338: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2339: 	my $ntstu ='<select name="NTSTU">'.
 2340: 	    '<option>1</option><option>2</option>'.
 2341: 	    '<option>3</option><option>5</option>'.
 2342: 	    '<option>7</option><option>10</option></select>'."\n";
 2343: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2344: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2345:         $endform.=&mt('[_1]student(s)',$ntstu);
 2346: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2347: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2348: 	    '<input type="button" value="'.&mt('Next').'" '.
 2349: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2350:         $endform.='<span class="LC_warning">'.
 2351:                   &mt('(Next and Previous (student) do not save the scores.)').
 2352:                   '</span>'."\n" ;
 2353:         $endform.="<input type='hidden' value='".&get_increment().
 2354:             "' name='increment' />";
 2355: 	$endform.='</td></tr></table></form>';
 2356: 	$endform.=&show_grading_menu_form($symb);
 2357: 	$request->print($endform);
 2358:     }
 2359:     return '';
 2360: }
 2361: 
 2362: sub check_collaborators {
 2363:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2364:     my ($result,@col_fullnames);
 2365:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2366:     foreach my $part (keys(%$handgrade)) {
 2367: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2368: 					'.maxcollaborators',
 2369: 					$symb,$udom,$uname);
 2370: 	next if ($ncol <= 0);
 2371: 	$part =~ s/\_/\./g;
 2372: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2373: 	my (@good_collaborators, @bad_collaborators);
 2374: 	foreach my $possible_collaborator
 2375: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2376: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2377: 	    next if ($possible_collaborator eq '');
 2378: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
 2379: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2380: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2381: 	    # Doing this grep allows 'fuzzy' specification
 2382: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2383: 			       keys(%$classlist));
 2384: 	    if (! scalar(@matches)) {
 2385: 		push(@bad_collaborators, $possible_collaborator);
 2386: 	    } else {
 2387: 		push(@good_collaborators, @matches);
 2388: 	    }
 2389: 	}
 2390: 	if (scalar(@good_collaborators) != 0) {
 2391: 	    $result.='<br />'.&mt('Collaborators: ');
 2392: 	    foreach my $name (@good_collaborators) {
 2393: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2394: 		push(@col_fullnames, $givenn.' '.$lastname);
 2395: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
 2396: 	    }
 2397: 	    $result.='<br />'."\n";
 2398: 	    my ($part)=split(/\./,$part);
 2399: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2400: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2401: 		"\n";
 2402: 	}
 2403: 	if (scalar(@bad_collaborators) > 0) {
 2404: 	    $result.='<div class="LC_warning">';
 2405: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2406: 	    $result .= '</div>';
 2407: 	}         
 2408: 	if (scalar(@bad_collaborators > $ncol)) {
 2409: 	    $result .= '<div class="LC_warning">';
 2410: 	    $result .= &mt('This student has submitted too many '.
 2411: 		'collaborators.  Maximum is [_1].',$ncol);
 2412: 	    $result .= '</div>';
 2413: 	}
 2414:     }
 2415:     return ($result,$fullname,\@col_fullnames);
 2416: }
 2417: 
 2418: #--- Retrieve the last submission for all the parts
 2419: sub get_last_submission {
 2420:     my ($returnhash)=@_;
 2421:     my (@string,$timestamp,%lasthidden);
 2422:     if ($$returnhash{'version'}) {
 2423: 	my %lasthash=();
 2424: 	my ($version);
 2425: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2426: 	    foreach my $key (sort(split(/\:/,
 2427: 					$$returnhash{$version.':keys'}))) {
 2428: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2429: 		$timestamp = 
 2430: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2431: 	    }
 2432: 	}
 2433:         my %typeparts;
 2434:         my $showsurv = 
 2435:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2436:         foreach my $key (sort(keys(%lasthash))) {
 2437:             if ($key =~ /\.type$/) {
 2438:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2439:                     ($lasthash{$key} eq 'anonsurveycred')) {
 2440:                     my ($ign,@parts) = split(/\./,$key);
 2441:                     pop(@parts);
 2442:                     unless ($showsurv) {
 2443:                         my $id = join(',',@parts);
 2444:                         $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2445:                     }
 2446:                     delete($lasthash{$key});
 2447:                 }
 2448:             }
 2449:         }
 2450:         my @hidden = keys(%typeparts);
 2451: 	foreach my $key (keys(%lasthash)) {
 2452: 	    next if ($key !~ /\.submission$/);
 2453:             my $hide;
 2454:             if (@hidden) {
 2455:                 foreach my $id (@hidden) {
 2456:                     if ($key =~ /^\Q$id\E/) {
 2457:                         $hide = 1;
 2458:                         last;
 2459:                     }
 2460:                 }
 2461:             }
 2462: 	    my ($partid,$foo) = split(/submission$/,$key);
 2463: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 2464: 		'<span class="LC_warning">Draft Copy</span> ' : '';
 2465: 	    push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
 2466: 	}
 2467:     }
 2468:     if (!@string) {
 2469: 	$string[0] =
 2470: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2471:     }
 2472:     return (\@string,\$timestamp);
 2473: }
 2474: 
 2475: #--- High light keywords, with style choosen by user.
 2476: sub keywords_highlight {
 2477:     my $string    = shift;
 2478:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2479:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2480:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2481:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2482:     foreach my $keyword (@keylist) {
 2483: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2484:     }
 2485:     return $string;
 2486: }
 2487: 
 2488: #--- Called from submission routine
 2489: sub processHandGrade {
 2490:     my ($request) = shift;
 2491:     my $symb   = &get_symb($request);
 2492:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2493:     my $button = $env{'form.gradeOpt'};
 2494:     my $ngrade = $env{'form.NCT'};
 2495:     my $ntstu  = $env{'form.NTSTU'};
 2496:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2497:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2498: 
 2499:     if ($button eq 'Save & Next') {
 2500: 	my $ctr = 0;
 2501: 	while ($ctr < $ngrade) {
 2502: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2503: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2504: 	    if ($errorflag eq 'no_score') {
 2505: 		$ctr++;
 2506: 		next;
 2507: 	    }
 2508: 	    if ($errorflag eq 'not_allowed') {
 2509: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
 2510: 		$ctr++;
 2511: 		next;
 2512: 	    }
 2513: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2514: 	    my ($subject,$message,$msgstatus) = ('','','');
 2515: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2516:             my ($feedurl,$showsymb) =
 2517: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2518: 	    my $messagetail;
 2519: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2520: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2521: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2522: 		$subject.=' ['.$restitle.']';
 2523: 		my (@msgnum) = split(/,/,$includemsg);
 2524: 		foreach (@msgnum) {
 2525: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2526: 		}
 2527: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2528: 		if ($env{'form.withgrades'.$ctr}) {
 2529: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2530: 		    $messagetail = " for <a href=\"".
 2531: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
 2532: 		}
 2533: 		$msgstatus = 
 2534:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2535: 						     $message.$messagetail,
 2536:                                                      undef,$feedurl,undef,
 2537:                                                      undef,undef,$showsymb,
 2538:                                                      $restitle);
 2539: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 2540: 				$msgstatus);
 2541: 	    }
 2542: 	    if ($env{'form.collaborator'.$ctr}) {
 2543: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2544: 		foreach my $collabstr (@collabstrs) {
 2545: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2546: 		    foreach my $collaborator (@collaborators) {
 2547: 			my ($errorflag,$pts,$wgt) = 
 2548: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2549: 					   $env{'form.unamedom'.$ctr},$part);
 2550: 			if ($errorflag eq 'not_allowed') {
 2551: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2552: 			    next;
 2553: 			} elsif ($message ne '') {
 2554: 			    my ($baseurl,$showsymb) = 
 2555: 				&get_feedurl_and_symb($symb,$collaborator,
 2556: 						      $udom);
 2557: 			    if ($env{'form.withgrades'.$ctr}) {
 2558: 				$messagetail = " for <a href=\"".
 2559:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
 2560: 			    }
 2561: 			    $msgstatus = 
 2562: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2563: 			}
 2564: 		    }
 2565: 		}
 2566: 	    }
 2567: 	    $ctr++;
 2568: 	}
 2569:     }
 2570: 
 2571:     if ($env{'form.handgrade'} eq 'yes') {
 2572: 	# Keywords sorted in alphabatical order
 2573: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2574: 	my %keyhash = ();
 2575: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2576: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2577: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2578: 	$env{'form.keywords'} = join(' ',@keywords);
 2579: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2580: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2581: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2582: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2583: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2584: 
 2585: 	# message center - Order of message gets changed. Blank line is eliminated.
 2586: 	# New messages are saved in env for the next student.
 2587: 	# All messages are saved in nohist_handgrade.db
 2588: 	my ($ctr,$idx) = (1,1);
 2589: 	while ($ctr <= $env{'form.savemsgN'}) {
 2590: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2591: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2592: 		$idx++;
 2593: 	    }
 2594: 	    $ctr++;
 2595: 	}
 2596: 	$ctr = 0;
 2597: 	while ($ctr < $ngrade) {
 2598: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2599: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2600: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2601: 		$idx++;
 2602: 	    }
 2603: 	    $ctr++;
 2604: 	}
 2605: 	$env{'form.savemsgN'} = --$idx;
 2606: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2607: 	my $putresult = &Apache::lonnet::put
 2608: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2609:     }
 2610:     # Called by Save & Refresh from Highlight Attribute Window
 2611:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2612:     if ($env{'form.refresh'} eq 'on') {
 2613: 	my ($ctr,$total) = (0,0);
 2614: 	while ($ctr < $ngrade) {
 2615: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2616: 	    $ctr++;
 2617: 	}
 2618: 	$env{'form.NTSTU'}=$ngrade;
 2619: 	$ctr = 0;
 2620: 	while ($ctr < $total) {
 2621: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2622: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2623: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2624: 	    &submission($request,$ctr,$total-1);
 2625: 	    $ctr++;
 2626: 	}
 2627: 	return '';
 2628:     }
 2629: 
 2630: # Go directly to grade student - from submission or link from chart page
 2631:     if ($button eq 'Grade Student') {
 2632: #	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
 2633: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
 2634: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2635: 	$env{'form.fullname'} = $$fullname{$processUser};
 2636: 	&submission($request,0,0);
 2637: 	return '';
 2638:     }
 2639: 
 2640:     # Get the next/previous one or group of students
 2641:     my $firststu = $env{'form.unamedom0'};
 2642:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2643:     my $ctr = 2;
 2644:     while ($laststu eq '') {
 2645: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2646: 	$ctr++;
 2647: 	$laststu = $firststu if ($ctr > $ngrade);
 2648:     }
 2649: 
 2650:     my (@parsedlist,@nextlist);
 2651:     my ($nextflg) = 0;
 2652:     foreach my $item (sort 
 2653: 	     {
 2654: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2655: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2656: 		 }
 2657: 		 return $a cmp $b;
 2658: 	     } (keys(%$fullname))) {
 2659: # FIXME: this is fishy, looks like the button label
 2660: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2661: 	    push(@parsedlist,$item);
 2662: 	}
 2663: 	$nextflg = 1 if ($item eq $laststu);
 2664: 	if ($button eq 'Previous') {
 2665: 	    last if ($item eq $firststu);
 2666: 	    push(@parsedlist,$item);
 2667: 	}
 2668:     }
 2669:     $ctr = 0;
 2670: # FIXME: this is fishy, looks like the button label
 2671:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2672:     my $res_error;
 2673:     my ($partlist) = &response_type($symb,\$res_error);
 2674:     if ($res_error) {
 2675:         $request->print(&navmap_errormsg());
 2676:         return;
 2677:     }
 2678:     foreach my $student (@parsedlist) {
 2679: 	my $submitonly=$env{'form.submitonly'};
 2680: 	my ($uname,$udom) = split(/:/,$student);
 2681: 	
 2682: 	if ($submitonly eq 'queued') {
 2683: 	    my %queue_status = 
 2684: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2685: 							$udom,$uname);
 2686: 	    next if (!defined($queue_status{'gradingqueue'}));
 2687: 	}
 2688: 
 2689: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2690: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2691: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2692: 	    my $submitted = 0;
 2693: 	    my $ungraded = 0;
 2694: 	    my $incorrect = 0;
 2695: 	    foreach my $item (keys(%status)) {
 2696: 		$submitted = 1 if ($status{$item} ne 'nothing');
 2697: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 2698: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 2699: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 2700: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2701: 		    $submitted = 0;
 2702: 		}
 2703: 	    }
 2704: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2705: 				     $submitonly eq 'incorrect' ||
 2706: 				     $submitonly eq 'graded'));
 2707: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2708: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2709: 	}
 2710: 	push(@nextlist,$student) if ($ctr < $ntstu);
 2711: 	last if ($ctr == $ntstu);
 2712: 	$ctr++;
 2713:     }
 2714: 
 2715:     $ctr = 0;
 2716:     my $total = scalar(@nextlist)-1;
 2717: 
 2718:     foreach (sort(@nextlist)) {
 2719: 	my ($uname,$udom,$submitter) = split(/:/);
 2720: 	$env{'form.student'}  = $uname;
 2721: 	$env{'form.userdom'}  = $udom;
 2722: 	$env{'form.fullname'} = $$fullname{$_};
 2723: 	&submission($request,$ctr,$total);
 2724: 	$ctr++;
 2725:     }
 2726:     if ($total < 0) {
 2727: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
 2728: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
 2729: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
 2730: 	$the_end.=&show_grading_menu_form($symb);
 2731: 	$request->print($the_end);
 2732:     }
 2733:     return '';
 2734: }
 2735: 
 2736: #---- Save the score and award for each student, if changed
 2737: sub saveHandGrade {
 2738:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 2739:     my @version_parts;
 2740:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 2741: 					   $env{'request.course.id'});
 2742:     if (!&canmodify($usec)) { return('not_allowed'); }
 2743:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 2744:     my @parts_graded;
 2745:     my %newrecord  = ();
 2746:     my ($pts,$wgt) = ('','');
 2747:     my %aggregate = ();
 2748:     my $aggregateflag = 0;
 2749:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 2750:     foreach my $new_part (@parts) {
 2751: 	#collaborator ($submi may vary for different parts
 2752: 	if ($submitter && $new_part ne $part) { next; }
 2753: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 2754: 	if ($dropMenu eq 'excused') {
 2755: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 2756: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 2757: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 2758: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 2759: 		}
 2760: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 2761: 	    }
 2762: 	} elsif ($dropMenu eq 'reset status'
 2763: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 2764: 	    foreach my $key (keys(%record)) {
 2765: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 2766: 	    }
 2767: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2768: 		"$env{'user.name'}:$env{'user.domain'}";
 2769:             my $totaltries = $record{'resource.'.$part.'.tries'};
 2770: 
 2771:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2772: 					       [$new_part]);
 2773:             my $aggtries =$totaltries;
 2774:             if ($last_resets{$new_part}) {
 2775:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 2776: 					   $new_part);
 2777:             }
 2778: 
 2779:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 2780:             if ($aggtries > 0) {
 2781:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 2782:                 $aggregateflag = 1;
 2783:             }
 2784: 	} elsif ($dropMenu eq '') {
 2785: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 2786: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 2787: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 2788: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 2789: 		next;
 2790: 	    }
 2791: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 2792: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 2793: 	    my $partial= $pts/$wgt;
 2794: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 2795: 		#do not update score for part if not changed.
 2796:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 2797: 		next;
 2798: 	    } else {
 2799: 	        push(@parts_graded,$new_part);
 2800: 	    }
 2801: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 2802: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 2803: 	    }
 2804: 	    my $reckey = 'resource.'.$new_part.'.solved';
 2805: 	    if ($partial == 0) {
 2806: 		if ($record{$reckey} ne 'incorrect_by_override') {
 2807: 		    $newrecord{$reckey} = 'incorrect_by_override';
 2808: 		}
 2809: 	    } else {
 2810: 		if ($record{$reckey} ne 'correct_by_override') {
 2811: 		    $newrecord{$reckey} = 'correct_by_override';
 2812: 		}
 2813: 	    }	    
 2814: 	    if ($submitter && 
 2815: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 2816: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 2817: 	    }
 2818: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2819: 		"$env{'user.name'}:$env{'user.domain'}";
 2820: 	}
 2821: 	# unless problem has been graded, set flag to version the submitted files
 2822: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 2823: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 2824: 	        $dropMenu eq 'reset status')
 2825: 	   {
 2826: 	    push(@version_parts,$new_part);
 2827: 	}
 2828:     }
 2829:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2830:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2831: 
 2832:     if (%newrecord) {
 2833:         if (@version_parts) {
 2834:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 2835:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 2836: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 2837: 	    foreach my $new_part (@version_parts) {
 2838: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 2839: 				$new_part,\%newrecord);
 2840: 	    }
 2841:         }
 2842: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 2843: 				$env{'request.course.id'},$domain,$stuname);
 2844: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 2845: 				     $cdom,$cnum,$domain,$stuname);
 2846:     }
 2847:     if ($aggregateflag) {
 2848:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 2849: 			      $cdom,$cnum);
 2850:     }
 2851:     return ('',$pts,$wgt);
 2852: }
 2853: 
 2854: sub check_and_remove_from_queue {
 2855:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 2856:     my @ungraded_parts;
 2857:     foreach my $part (@{$parts}) {
 2858: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 2859: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 2860: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 2861: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 2862: 		) {
 2863: 	    push(@ungraded_parts, $part);
 2864: 	}
 2865:     }
 2866:     if ( !@ungraded_parts ) {
 2867: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 2868: 					       $cnum,$domain,$stuname);
 2869:     }
 2870: }
 2871: 
 2872: sub handback_files {
 2873:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 2874:     my $portfolio_root = '/userfiles/portfolio';
 2875:     my $res_error;
 2876:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2877:     if ($res_error) {
 2878:         $request->print('<br />'.&navmap_errormsg().'<br />');
 2879:         return;
 2880:     }
 2881:     my @part_response_id = &flatten_responseType($responseType);
 2882:     foreach my $part_response_id (@part_response_id) {
 2883:     	my ($part_id,$resp_id) = @{ $part_response_id };
 2884: 	my $part_resp = join('_',@{ $part_response_id });
 2885:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
 2886:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 2887:                 my $file_counter = 1;
 2888: 		my $file_msg;
 2889:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
 2890:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
 2891:                     my ($directory,$answer_file) = 
 2892:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
 2893:                     my ($answer_name,$answer_ver,$answer_ext) =
 2894: 		        &file_name_version_ext($answer_file);
 2895: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 2896:                     my $getpropath = 1;
 2897: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
 2898: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2899:                     # fix file name
 2900:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 2901:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 2902:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
 2903:             	                                $save_file_name);
 2904:                     if ($result !~ m|^/uploaded/|) {
 2905:                         $request->print('<br /><span class="LC_error">'.
 2906:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 2907:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
 2908:                                         '</span>');
 2909:                     } else {
 2910:                         # mark the file as read only
 2911:                         my @files = ($save_file_name);
 2912:                         my @what = ($symb,$env{'request.course.id'},'handback');
 2913:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
 2914: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 2915: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 2916: 			}
 2917:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 2918: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
 2919: 
 2920:                     }
 2921:                     $request->print("<br />".$fname." will be the uploaded file name");
 2922:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
 2923:                     $file_counter++;
 2924:                 }
 2925: 		my $subject = "File Handed Back by Instructor ";
 2926: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
 2927: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
 2928: 		$message .= ' The returned file(s) are named: '. $file_msg;
 2929: 		$message .= " and can be found in your portfolio space.";
 2930: 		my ($feedurl,$showsymb) = 
 2931: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
 2932:                 my $restitle = &Apache::lonnet::gettitle($symb);
 2933: 		my $msgstatus = 
 2934:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
 2935: 			 ' (File Returned) ['.$restitle.']',$message,undef,
 2936:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
 2937:             }
 2938:         }
 2939:     return;
 2940: }
 2941: 
 2942: sub get_feedurl_and_symb {
 2943:     my ($symb,$uname,$udom) = @_;
 2944:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2945:     $url = &Apache::lonnet::clutter($url);
 2946:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 2947: 					$symb,$udom,$uname);
 2948:     if ($encrypturl =~ /^yes$/i) {
 2949: 	&Apache::lonenc::encrypted(\$url,1);
 2950: 	&Apache::lonenc::encrypted(\$symb,1);
 2951:     }
 2952:     return ($url,$symb);
 2953: }
 2954: 
 2955: sub get_submitted_files {
 2956:     my ($udom,$uname,$partid,$respid,$record) = @_;
 2957:     my @files;
 2958:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 2959:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 2960:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 2961:     	    push(@files,$file_url.$file);
 2962:         }
 2963:     }
 2964:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 2965:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 2966:     }
 2967:     return (\@files);
 2968: }
 2969: 
 2970: # ----------- Provides number of tries since last reset.
 2971: sub get_num_tries {
 2972:     my ($record,$last_reset,$part) = @_;
 2973:     my $timestamp = '';
 2974:     my $num_tries = 0;
 2975:     if ($$record{'version'}) {
 2976:         for (my $version=$$record{'version'};$version>=1;$version--) {
 2977:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 2978:                 $timestamp = $$record{$version.':timestamp'};
 2979:                 if ($timestamp > $last_reset) {
 2980:                     $num_tries ++;
 2981:                 } else {
 2982:                     last;
 2983:                 }
 2984:             }
 2985:         }
 2986:     }
 2987:     return $num_tries;
 2988: }
 2989: 
 2990: # ----------- Determine decrements required in aggregate totals 
 2991: sub decrement_aggs {
 2992:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 2993:     my %decrement = (
 2994:                         attempts => 0,
 2995:                         users => 0,
 2996:                         correct => 0
 2997:                     );
 2998:     $decrement{'attempts'} = $aggtries;
 2999:     if ($solvedstatus =~ /^correct/) {
 3000:         $decrement{'correct'} = 1;
 3001:     }
 3002:     if ($aggtries == $totaltries) {
 3003:         $decrement{'users'} = 1;
 3004:     }
 3005:     foreach my $type (keys(%decrement)) {
 3006:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 3007:     }
 3008:     return;
 3009: }
 3010: 
 3011: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3012: sub get_last_resets {
 3013:     my ($symb,$courseid,$partids) =@_;
 3014:     my %last_resets;
 3015:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3016:     my $cname = $env{'course.'.$courseid.'.num'};
 3017:     my @keys;
 3018:     foreach my $part (@{$partids}) {
 3019: 	push(@keys,"$symb\0$part\0resettime");
 3020:     }
 3021:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3022: 				     $cdom,$cname);
 3023:     foreach my $part (@{$partids}) {
 3024: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3025:     }
 3026:     return %last_resets;
 3027: }
 3028: 
 3029: # ----------- Handles creating versions for portfolio files as answers
 3030: sub version_portfiles {
 3031:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3032:     my $version_parts = join('|',@$v_flag);
 3033:     my @returned_keys;
 3034:     my $parts = join('|', @$parts_graded);
 3035:     my $portfolio_root = '/userfiles/portfolio';
 3036:     foreach my $key (keys(%$record)) {
 3037:         my $new_portfiles;
 3038:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3039:             my @versioned_portfiles;
 3040:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3041:             foreach my $file (@portfiles) {
 3042:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 3043:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 3044: 		my ($answer_name,$answer_ver,$answer_ext) =
 3045: 		    &file_name_version_ext($answer_file);
 3046:                 my $getpropath = 1;    
 3047:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
 3048:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 3049:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 3050:                 if ($new_answer ne 'problem getting file') {
 3051:                     push(@versioned_portfiles, $directory.$new_answer);
 3052:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 3053:                         [$directory.$new_answer],
 3054:                         [$symb,$env{'request.course.id'},'graded']);
 3055:                 }
 3056:             }
 3057:             $$record{$key} = join(',',@versioned_portfiles);
 3058:             push(@returned_keys,$key);
 3059:         }
 3060:     } 
 3061:     return (@returned_keys);   
 3062: }
 3063: 
 3064: sub get_next_version {
 3065:     my ($answer_name, $answer_ext, $dir_list) = @_;
 3066:     my $version;
 3067:     foreach my $row (@$dir_list) {
 3068:         my ($file) = split(/\&/,$row,2);
 3069:         my ($file_name,$file_version,$file_ext) =
 3070: 	    &file_name_version_ext($file);
 3071:         if (($file_name eq $answer_name) && 
 3072: 	    ($file_ext eq $answer_ext)) {
 3073:                 # gets here if filename and extension match, regardless of version
 3074:                 if ($file_version ne '') {
 3075:                 # a versioned file is found  so save it for later
 3076:                 if ($file_version > $version) {
 3077: 		    $version = $file_version;
 3078: 	        }
 3079:             }
 3080:         }
 3081:     } 
 3082:     $version ++;
 3083:     return($version);
 3084: }
 3085: 
 3086: sub version_selected_portfile {
 3087:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3088:     my ($answer_name,$answer_ver,$answer_ext) =
 3089:         &file_name_version_ext($file_name);
 3090:     my $new_answer;
 3091:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3092:     if($env{'form.copy'} eq '-1') {
 3093:         $new_answer = 'problem getting file';
 3094:     } else {
 3095:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3096:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3097:                             $stu_name,$domain,'copy',
 3098: 		        '/portfolio'.$directory.$new_answer);
 3099:     }    
 3100:     return ($new_answer);
 3101: }
 3102: 
 3103: sub file_name_version_ext {
 3104:     my ($file)=@_;
 3105:     my @file_parts = split(/\./, $file);
 3106:     my ($name,$version,$ext);
 3107:     if (@file_parts > 1) {
 3108: 	$ext=pop(@file_parts);
 3109: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3110: 	    $version=pop(@file_parts);
 3111: 	}
 3112: 	$name=join('.',@file_parts);
 3113:     } else {
 3114: 	$name=join('.',@file_parts);
 3115:     }
 3116:     return($name,$version,$ext);
 3117: }
 3118: 
 3119: #--------------------------------------------------------------------------------------
 3120: #
 3121: #-------------------------- Next few routines handles grading by section or whole class
 3122: #
 3123: #--- Javascript to handle grading by section or whole class
 3124: sub viewgrades_js {
 3125:     my ($request) = shift;
 3126: 
 3127:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3128:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
 3129:    function writePoint(partid,weight,point) {
 3130: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3131: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3132: 	if (point == "textval") {
 3133: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3134: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3135: 		alert("$alertmsg"+parseFloat(point));
 3136: 		var resetbox = false;
 3137: 		for (var i=0; i<radioButton.length; i++) {
 3138: 		    if (radioButton[i].checked) {
 3139: 			textbox.value = i;
 3140: 			resetbox = true;
 3141: 		    }
 3142: 		}
 3143: 		if (!resetbox) {
 3144: 		    textbox.value = "";
 3145: 		}
 3146: 		return;
 3147: 	    }
 3148: 	    if (parseFloat(point) > parseFloat(weight)) {
 3149: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3150: 				   ") greater than the weight for the part. Accept?");
 3151: 		if (resp == false) {
 3152: 		    textbox.value = "";
 3153: 		    return;
 3154: 		}
 3155: 	    }
 3156: 	    for (var i=0; i<radioButton.length; i++) {
 3157: 		radioButton[i].checked=false;
 3158: 		if (parseFloat(point) == i) {
 3159: 		    radioButton[i].checked=true;
 3160: 		}
 3161: 	    }
 3162: 
 3163: 	} else {
 3164: 	    textbox.value = parseFloat(point);
 3165: 	}
 3166: 	for (i=0;i<document.classgrade.total.value;i++) {
 3167: 	    var user = document.classgrade["ctr"+i].value;
 3168: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3169: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3170: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3171: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3172: 	    if (saveval != "correct") {
 3173: 		scorename.value = point;
 3174: 		if (selname[0].selected != true) {
 3175: 		    selname[0].selected = true;
 3176: 		}
 3177: 	    }
 3178: 	}
 3179: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3180:     }
 3181: 
 3182:     function writeRadText(partid,weight) {
 3183: 	var selval   = document.classgrade["SELVAL_"+partid];
 3184: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3185:         var override = document.classgrade["FORCE_"+partid].checked;
 3186: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3187: 	if (selval[1].selected || selval[2].selected) {
 3188: 	    for (var i=0; i<radioButton.length; i++) {
 3189: 		radioButton[i].checked=false;
 3190: 
 3191: 	    }
 3192: 	    textbox.value = "";
 3193: 
 3194: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3195: 		var user = document.classgrade["ctr"+i].value;
 3196: 		user = user.replace(new RegExp(':', 'g'),"_");
 3197: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3198: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3199: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3200: 		if ((saveval != "correct") || override) {
 3201: 		    scorename.value = "";
 3202: 		    if (selval[1].selected) {
 3203: 			selname[1].selected = true;
 3204: 		    } else {
 3205: 			selname[2].selected = true;
 3206: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3207: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3208: 		    }
 3209: 		}
 3210: 	    }
 3211: 	} else {
 3212: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3213: 		var user = document.classgrade["ctr"+i].value;
 3214: 		user = user.replace(new RegExp(':', 'g'),"_");
 3215: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3216: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3217: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3218: 		if ((saveval != "correct") || override) {
 3219: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3220: 		    selname[0].selected = true;
 3221: 		}
 3222: 	    }
 3223: 	}	    
 3224:     }
 3225: 
 3226:     function changeSelect(partid,user) {
 3227: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3228: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3229: 	var point  = textbox.value;
 3230: 	var weight = document.classgrade["weight_"+partid].value;
 3231: 
 3232: 	if (isNaN(point) || parseFloat(point) < 0) {
 3233: 	    alert("$alertmsg"+parseFloat(point));
 3234: 	    textbox.value = "";
 3235: 	    return;
 3236: 	}
 3237: 	if (parseFloat(point) > parseFloat(weight)) {
 3238: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3239: 			       ") greater than the weight of the part. Accept?");
 3240: 	    if (resp == false) {
 3241: 		textbox.value = "";
 3242: 		return;
 3243: 	    }
 3244: 	}
 3245: 	selval[0].selected = true;
 3246:     }
 3247: 
 3248:     function changeOneScore(partid,user) {
 3249: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3250: 	if (selval[1].selected || selval[2].selected) {
 3251: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3252: 	    if (selval[2].selected) {
 3253: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3254: 	    }
 3255:         }
 3256:     }
 3257: 
 3258:     function resetEntry(numpart) {
 3259: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3260: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3261: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3262: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3263: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3264: 	    for (var i=0; i<radioButton.length; i++) {
 3265: 		radioButton[i].checked=false;
 3266: 
 3267: 	    }
 3268: 	    textbox.value = "";
 3269: 	    selval[0].selected = true;
 3270: 
 3271: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3272: 		var user = document.classgrade["ctr"+i].value;
 3273: 		user = user.replace(new RegExp(':', 'g'),"_");
 3274: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3275: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3276: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3277: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3278: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3279: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3280: 		if (saveselval == "excused") {
 3281: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3282: 		} else {
 3283: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3284: 		}
 3285: 	    }
 3286: 	}
 3287:     }
 3288: 
 3289: VIEWJAVASCRIPT
 3290: }
 3291: 
 3292: #--- show scores for a section or whole class w/ option to change/update a score
 3293: sub viewgrades {
 3294:     my ($request) = shift;
 3295:     &viewgrades_js($request);
 3296: 
 3297:     my ($symb) = &get_symb($request);
 3298:     #need to make sure we have the correct data for later EXT calls, 
 3299:     #thus invalidate the cache
 3300:     &Apache::lonnet::devalidatecourseresdata(
 3301:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3302:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3303:     &Apache::lonnet::clear_EXT_cache_status();
 3304: 
 3305:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3306: 
 3307:     #view individual student submission form - called using Javascript viewOneStudent
 3308:     $result.=&jscriptNform($symb);
 3309: 
 3310:     #beginning of class grading form
 3311:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3312:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3313: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3314: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3315: 	&build_section_inputs().
 3316: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 3317: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3318: 
 3319:     my ($common_header,$specific_header);
 3320:     if ($env{'form.section'} eq 'all') {
 3321: 	$common_header = &mt('Assign Common Grade to Class');
 3322:         $specific_header = &mt('Assign Grade to Specific Students in Class');
 3323:     } elsif ($env{'form.section'} eq 'none') {
 3324:         $common_header = &mt('Assign Common Grade to Students in no Section');
 3325: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
 3326:     } else {
 3327:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3328:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3329: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3330:     }
 3331:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
 3332:     #radio buttons/text box for assigning points for a section or class.
 3333:     #handles different parts of a problem
 3334:     my $res_error;
 3335:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3336:     if ($res_error) {
 3337:         return &navmap_errormsg();
 3338:     }
 3339:     my %weight = ();
 3340:     my $ctsparts = 0;
 3341:     my %seen = ();
 3342:     my @part_response_id = &flatten_responseType($responseType);
 3343:     foreach my $part_response_id (@part_response_id) {
 3344:     	my ($partid,$respid) = @{ $part_response_id };
 3345: 	my $part_resp = join('_',@{ $part_response_id });
 3346: 	next if $seen{$partid};
 3347: 	$seen{$partid}++;
 3348: 	my $handgrade=$$handgrade{$part_resp};
 3349: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3350: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3351: 
 3352: 	my $display_part=&get_display_part($partid,$symb);
 3353: 	my $radio.='<table border="0"><tr>';  
 3354: 	my $ctr = 0;
 3355: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3356: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3357: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3358: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3359: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3360: 	    $ctr++;
 3361: 	}
 3362: 	$radio.='</tr></table>';
 3363: 	my $line = '<input type="text" name="TEXTVAL_'.
 3364: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 3365: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3366: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3367: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
 3368: 	    'onchange="javascript:writeRadText(\''.$partid.'\','.
 3369: 		$weight{$partid}.')"> '.
 3370: 	    '<option selected="selected"> </option>'.
 3371: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3372: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3373: 	    '</select></td>'.
 3374:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3375: 	$line.='<input type="hidden" name="partid_'.
 3376: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3377: 	$line.='<input type="hidden" name="weight_'.
 3378: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3379: 
 3380: 	$result.=
 3381: 	    &Apache::loncommon::start_data_table_row()."\n".
 3382: 	    '<td><b>'.&mt('Part:').'</b></td><td>'.$display_part.'</td><td><b>'.&mt('Points:').'</b></td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>'.
 3383: 	    &Apache::loncommon::end_data_table_row()."\n";
 3384: 	$ctsparts++;
 3385:     }
 3386:     $result.=&Apache::loncommon::end_data_table()."\n".
 3387: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3388:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3389: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 3390: 
 3391:     #table listing all the students in a section/class
 3392:     #header of table
 3393:     $result.= '<h3>'.$specific_header.'</h3>'.
 3394:               &Apache::loncommon::start_data_table().
 3395: 	      &Apache::loncommon::start_data_table_header_row().
 3396: 	      '<th>'.&mt('No.').'</th>'.
 3397: 	      '<th>'.&nameUserString('header')."</th>\n";
 3398:     my $partserror;
 3399:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3400:     if ($partserror) {
 3401:         return &navmap_errormsg();
 3402:     }
 3403:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3404:     my @partids = ();
 3405:     foreach my $part (@parts) {
 3406: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3407:         my $narrowtext = &mt('Tries');
 3408: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3409: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3410: 	my ($partid) = &split_part_type($part);
 3411:         push(@partids,$partid);
 3412: 	my $display_part=&get_display_part($partid,$symb);
 3413: 	if ($display =~ /^Partial Credit Factor/) {
 3414: 	    $result.='<th>'.
 3415: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
 3416: 		    $display_part,$weight{$partid}).'</th>'."\n";
 3417: 	    next;
 3418: 	    
 3419: 	} else {
 3420: 	    if ($display =~ /Problem Status/) {
 3421: 		my $grade_status_mt = &mt('Grade Status');
 3422: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3423: 	    }
 3424: 	    my $part_mt = &mt('Part:');
 3425: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3426: 	}
 3427: 
 3428: 	$result.='<th>'.$display.'</th>'."\n";
 3429:     }
 3430:     $result.=&Apache::loncommon::end_data_table_header_row();
 3431: 
 3432:     my %last_resets = 
 3433: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3434: 
 3435:     #get info for each student
 3436:     #list all the students - with points and grade status
 3437:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3438:     my $ctr = 0;
 3439:     foreach (sort 
 3440: 	     {
 3441: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3442: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3443: 		 }
 3444: 		 return $a cmp $b;
 3445: 	     } (keys(%$fullname))) {
 3446: 	$ctr++;
 3447: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3448: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3449:     }
 3450:     $result.=&Apache::loncommon::end_data_table();
 3451:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3452:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3453: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 3454:     if (scalar(%$fullname) eq 0) {
 3455: 	my $colspan=3+scalar(@parts);
 3456: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3457:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3458: 	$result='<span class="LC_warning">'.
 3459: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3460: 	        $section_display, $stu_status).
 3461: 	    '</span>';
 3462:     }
 3463:     $result.=&show_grading_menu_form($symb);
 3464:     return $result;
 3465: }
 3466: 
 3467: #--- call by previous routine to display each student
 3468: sub viewstudentgrade {
 3469:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3470:     my ($uname,$udom) = split(/:/,$student);
 3471:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3472:     my %aggregates = (); 
 3473:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3474: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3475: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3476: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3477: 	'\');" target="_self">'.$fullname.'</a> '.
 3478: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3479:     $student=~s/:/_/; # colon doen't work in javascript for names
 3480:     foreach my $apart (@$parts) {
 3481: 	my ($part,$type) = &split_part_type($apart);
 3482: 	my $score=$record{"resource.$part.$type"};
 3483:         $result.='<td align="center">';
 3484:         my ($aggtries,$totaltries);
 3485:         unless (exists($aggregates{$part})) {
 3486: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3487: 
 3488: 	    $aggtries = $totaltries;
 3489:             if ($$last_resets{$part}) {  
 3490:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3491: 					   $part);
 3492:             }
 3493:             $result.='<input type="hidden" name="'.
 3494:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3495:             $result.='<input type="hidden" name="'.
 3496:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3497:             $aggregates{$part} = 1;
 3498:         }
 3499: 	if ($type eq 'awarded') {
 3500: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3501: 	    $result.='<input type="hidden" name="'.
 3502: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3503: 	    $result.='<input type="text" name="'.
 3504: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3505:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3506: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3507: 	} elsif ($type eq 'solved') {
 3508: 	    my ($status,$foo)=split(/_/,$score,2);
 3509: 	    $status = 'nothing' if ($status eq '');
 3510: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3511: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3512: 	    $result.='&nbsp;<select name="'.
 3513: 		'GD_'.$student.'_'.$part.'_solved" '.
 3514:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3515: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3516: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3517: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3518: 	    $result.="</select>&nbsp;</td>\n";
 3519: 	} else {
 3520: 	    $result.='<input type="hidden" name="'.
 3521: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3522: 		    "\n";
 3523: 	    $result.='<input type="text" name="'.
 3524: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3525: 		'value="'.$score.'" size="4" /></td>'."\n";
 3526: 	}
 3527:     }
 3528:     $result.=&Apache::loncommon::end_data_table_row();
 3529:     return $result;
 3530: }
 3531: 
 3532: #--- change scores for all the students in a section/class
 3533: #    record does not get update if unchanged
 3534: sub editgrades {
 3535:     my ($request) = @_;
 3536: 
 3537:     my $symb=&get_symb($request);
 3538:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3539:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3540:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3541: 
 3542:     my $result= &Apache::loncommon::start_data_table().
 3543: 	&Apache::loncommon::start_data_table_header_row().
 3544: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3545: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3546:     my %scoreptr = (
 3547: 		    'correct'  =>'correct_by_override',
 3548: 		    'incorrect'=>'incorrect_by_override',
 3549: 		    'excused'  =>'excused',
 3550: 		    'ungraded' =>'ungraded_attempted',
 3551:                     'credited' =>'credit_attempted',
 3552: 		    'nothing'  => '',
 3553: 		    );
 3554:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3555: 
 3556:     my (@partid);
 3557:     my %weight = ();
 3558:     my %columns = ();
 3559:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3560: 
 3561:     my $partserror;
 3562:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3563:     if ($partserror) {
 3564:         return &navmap_errormsg();
 3565:     }
 3566:     my $header;
 3567:     while ($ctr < $env{'form.totalparts'}) {
 3568: 	my $partid = $env{'form.partid_'.$ctr};
 3569: 	push(@partid,$partid);
 3570: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3571: 	$ctr++;
 3572:     }
 3573:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3574:     foreach my $partid (@partid) {
 3575: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3576: 	    '<th align="center">'.&mt('New Score').'</th>';
 3577: 	$columns{$partid}=2;
 3578: 	foreach my $stores (@parts) {
 3579: 	    my ($part,$type) = &split_part_type($stores);
 3580: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3581: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3582: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3583: 	    $display =~ s/\[Part: \Q$part\E\]//;
 3584:             my $narrowtext = &mt('Tries');
 3585: 	    $display =~ s/Number of Attempts/$narrowtext/;
 3586: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 3587: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 3588: 	    $columns{$partid}+=2;
 3589: 	}
 3590:     }
 3591:     foreach my $partid (@partid) {
 3592: 	my $display_part=&get_display_part($partid,$symb);
 3593: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3594: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3595: 	    '</th>';
 3596: 
 3597:     }
 3598:     $result .= &Apache::loncommon::end_data_table_header_row().
 3599: 	&Apache::loncommon::start_data_table_header_row().
 3600: 	$header.
 3601: 	&Apache::loncommon::end_data_table_header_row();
 3602:     my @noupdate;
 3603:     my ($updateCtr,$noupdateCtr) = (1,1);
 3604:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3605: 	my $line;
 3606: 	my $user = $env{'form.ctr'.$i};
 3607: 	my ($uname,$udom)=split(/:/,$user);
 3608: 	my %newrecord;
 3609: 	my $updateflag = 0;
 3610: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3611: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3612: 	if (!&canmodify($usec)) {
 3613: 	    my $numcols=scalar(@partid)*4+2;
 3614: 	    push(@noupdate,
 3615: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 3616: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 3617: 	    next;
 3618: 	}
 3619:         my %aggregate = ();
 3620:         my $aggregateflag = 0;
 3621: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3622: 	foreach (@partid) {
 3623: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3624: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3625: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3626: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3627: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3628: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3629: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3630: 	    my $score;
 3631: 	    if ($partial eq '') {
 3632: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3633: 	    } elsif ($partial > 0) {
 3634: 		$score = 'correct_by_override';
 3635: 	    } elsif ($partial == 0) {
 3636: 		$score = 'incorrect_by_override';
 3637: 	    }
 3638: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3639: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3640: 
 3641: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3642: 		"$env{'user.name'}:$env{'user.domain'}";
 3643: 	    if ($dropMenu eq 'reset status' &&
 3644: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3645: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3646: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3647: 		$newrecord{'resource.'.$_.'.award'} = '';
 3648: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3649: 		$updateflag = 1;
 3650:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3651:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3652:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3653:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3654:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3655:                     $aggregateflag = 1;
 3656:                 }
 3657: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3658: 		$updateflag = 1;
 3659: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3660: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3661: 		$rec_update++;
 3662: 	    }
 3663: 
 3664: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3665: 		'<td align="center">'.$awarded.
 3666: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3667: 
 3668: 
 3669: 	    my $partid=$_;
 3670: 	    foreach my $stores (@parts) {
 3671: 		my ($part,$type) = &split_part_type($stores);
 3672: 		if ($part !~ m/^\Q$partid\E/) { next;}
 3673: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 3674: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 3675: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 3676: 		if ($awarded ne '' && $awarded ne $old_aw) {
 3677: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 3678: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3679: 		    $updateflag=1;
 3680: 		}
 3681: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3682: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 3683: 	    }
 3684: 	}
 3685: 	$line.="\n";
 3686: 
 3687: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3688: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3689: 
 3690: 	if ($updateflag) {
 3691: 	    $count++;
 3692: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 3693: 				    $udom,$uname);
 3694: 
 3695: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 3696: 					      $cnum,$udom,$uname)) {
 3697: 		# need to figure out if should be in queue.
 3698: 		my %record =  
 3699: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3700: 					     $udom,$uname);
 3701: 		my $all_graded = 1;
 3702: 		my $none_graded = 1;
 3703: 		foreach my $part (@parts) {
 3704: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 3705: 			$all_graded = 0;
 3706: 		    } else {
 3707: 			$none_graded = 0;
 3708: 		    }
 3709: 		}
 3710: 
 3711: 		if ($all_graded || $none_graded) {
 3712: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 3713: 							   $symb,$cdom,$cnum,
 3714: 							   $udom,$uname);
 3715: 		}
 3716: 	    }
 3717: 
 3718: 	    $result.=&Apache::loncommon::start_data_table_row().
 3719: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 3720: 		&Apache::loncommon::end_data_table_row();
 3721: 	    $updateCtr++;
 3722: 	} else {
 3723: 	    push(@noupdate,
 3724: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 3725: 	    $noupdateCtr++;
 3726: 	}
 3727:         if ($aggregateflag) {
 3728:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3729: 				  $cdom,$cnum);
 3730:         }
 3731:     }
 3732:     if (@noupdate) {
 3733: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 3734: 	my $numcols=scalar(@partid)*4+2;
 3735: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 3736: 	    '<td align="center" colspan="'.$numcols.'">'.
 3737: 	    &mt('No Changes Occurred For the Students Below').
 3738: 	    '</td>'.
 3739: 	    &Apache::loncommon::end_data_table_row();
 3740: 	foreach my $line (@noupdate) {
 3741: 	    $result.=
 3742: 		&Apache::loncommon::start_data_table_row().
 3743: 		$line.
 3744: 		&Apache::loncommon::end_data_table_row();
 3745: 	}
 3746:     }
 3747:     $result .= &Apache::loncommon::end_data_table().
 3748: 	&show_grading_menu_form($symb);
 3749:     my $msg = '<p><b>'.
 3750: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 3751: 	    $rec_update,$count).'</b><br />'.
 3752: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 3753: 	'</b></p>';
 3754:     return $title.$msg.$result;
 3755: }
 3756: 
 3757: sub split_part_type {
 3758:     my ($partstr) = @_;
 3759:     my ($temp,@allparts)=split(/_/,$partstr);
 3760:     my $type=pop(@allparts);
 3761:     my $part=join('_',@allparts);
 3762:     return ($part,$type);
 3763: }
 3764: 
 3765: #------------- end of section for handling grading by section/class ---------
 3766: #
 3767: #----------------------------------------------------------------------------
 3768: 
 3769: 
 3770: #----------------------------------------------------------------------------
 3771: #
 3772: #-------------------------- Next few routines handles grading by csv upload
 3773: #
 3774: #--- Javascript to handle csv upload
 3775: sub csvupload_javascript_reverse_associate {
 3776:     my $error1=&mt('You need to specify the username or the student/employee ID');
 3777:     my $error2=&mt('You need to specify at least one grading field');
 3778:   return(<<ENDPICK);
 3779:   function verify(vf) {
 3780:     var foundsomething=0;
 3781:     var founduname=0;
 3782:     var foundID=0;
 3783:     for (i=0;i<=vf.nfields.value;i++) {
 3784:       tw=eval('vf.f'+i+'.selectedIndex');
 3785:       if (i==0 && tw!=0) { foundID=1; }
 3786:       if (i==1 && tw!=0) { founduname=1; }
 3787:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 3788:     }
 3789:     if (founduname==0 && foundID==0) {
 3790: 	alert('$error1');
 3791: 	return;
 3792:     }
 3793:     if (foundsomething==0) {
 3794: 	alert('$error2');
 3795: 	return;
 3796:     }
 3797:     vf.submit();
 3798:   }
 3799:   function flip(vf,tf) {
 3800:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3801:     var i;
 3802:     for (i=0;i<=vf.nfields.value;i++) {
 3803:       //can not pick the same destination field for both name and domain
 3804:       if (((i ==0)||(i ==1)) && 
 3805:           ((tf==0)||(tf==1)) && 
 3806:           (i!=tf) &&
 3807:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3808:         eval('vf.f'+i+'.selectedIndex=0;')
 3809:       }
 3810:     }
 3811:   }
 3812: ENDPICK
 3813: }
 3814: 
 3815: sub csvupload_javascript_forward_associate {
 3816:     my $error1=&mt('You need to specify the username or the student/employee ID');
 3817:     my $error2=&mt('You need to specify at least one grading field');
 3818:   return(<<ENDPICK);
 3819:   function verify(vf) {
 3820:     var foundsomething=0;
 3821:     var founduname=0;
 3822:     var foundID=0;
 3823:     for (i=0;i<=vf.nfields.value;i++) {
 3824:       tw=eval('vf.f'+i+'.selectedIndex');
 3825:       if (tw==1) { foundID=1; }
 3826:       if (tw==2) { founduname=1; }
 3827:       if (tw>3) { foundsomething=1; }
 3828:     }
 3829:     if (founduname==0 && foundID==0) {
 3830: 	alert('$error1');
 3831: 	return;
 3832:     }
 3833:     if (foundsomething==0) {
 3834: 	alert('$error2');
 3835: 	return;
 3836:     }
 3837:     vf.submit();
 3838:   }
 3839:   function flip(vf,tf) {
 3840:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3841:     var i;
 3842:     //can not pick the same destination field twice
 3843:     for (i=0;i<=vf.nfields.value;i++) {
 3844:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3845:         eval('vf.f'+i+'.selectedIndex=0;')
 3846:       }
 3847:     }
 3848:   }
 3849: ENDPICK
 3850: }
 3851: 
 3852: sub csvuploadmap_header {
 3853:     my ($request,$symb,$datatoken,$distotal)= @_;
 3854:     my $javascript;
 3855:     if ($env{'form.upfile_associate'} eq 'reverse') {
 3856: 	$javascript=&csvupload_javascript_reverse_associate();
 3857:     } else {
 3858: 	$javascript=&csvupload_javascript_forward_associate();
 3859:     }
 3860: 
 3861:     my $result='';
 3862:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 3863:     my $ignore=&mt('Ignore First Line');
 3864:     $symb = &Apache::lonenc::check_encrypt($symb);
 3865:     $request->print(<<ENDPICK);
 3866: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3867: <h3><span class="LC_info">Uploading Class Grades</span></h3>
 3868: $result
 3869: <hr />
 3870: <h3>Identify fields</h3>
 3871: Total number of records found in file: $distotal <hr />
 3872: Enter as many fields as you can. The system will inform you and bring you back
 3873: to this page if the data selected is insufficient to run your class.<hr />
 3874: <input type="button" value="Reverse Association" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 3875: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 3876: <input type="hidden" name="associate"  value="" />
 3877: <input type="hidden" name="phase"      value="three" />
 3878: <input type="hidden" name="datatoken"  value="$datatoken" />
 3879: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 3880: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 3881: <input type="hidden" name="upfile_associate" 
 3882:                                        value="$env{'form.upfile_associate'}" />
 3883: <input type="hidden" name="symb"       value="$symb" />
 3884: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3885: <input type="hidden" name="command"    value="csvuploadoptions" />
 3886: <hr />
 3887: ENDPICK
 3888:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
 3889:     return '';
 3890: 
 3891: }
 3892: 
 3893: sub csvupload_fields {
 3894:     my ($symb,$errorref) = @_;
 3895:     my (@parts) = &getpartlist($symb,$errorref);
 3896:     if (ref($errorref)) {
 3897:         if ($$errorref) {
 3898:             return;
 3899:         }
 3900:     }
 3901: 
 3902:     my @fields=(['ID','Student/Employee ID'],
 3903: 		['username','Student Username'],
 3904: 		['domain','Student Domain']);
 3905:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3906:     foreach my $part (sort(@parts)) {
 3907: 	my @datum;
 3908: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3909: 	my $name=$part;
 3910: 	if  (!$display) { $display = $name; }
 3911: 	@datum=($name,$display);
 3912: 	if ($name=~/^stores_(.*)_awarded/) {
 3913: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 3914: 	}
 3915: 	push(@fields,\@datum);
 3916:     }
 3917:     return (@fields);
 3918: }
 3919: 
 3920: sub csvuploadmap_footer {
 3921:     my ($request,$i,$keyfields) =@_;
 3922:     $request->print(<<ENDPICK);
 3923: </table>
 3924: <input type="hidden" name="nfields" value="$i" />
 3925: <input type="hidden" name="keyfields" value="$keyfields" />
 3926: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
 3927: </form>
 3928: ENDPICK
 3929: }
 3930: 
 3931: sub checkforfile_js {
 3932:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 3933:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
 3934:     function checkUpload(formname) {
 3935: 	if (formname.upfile.value == "") {
 3936: 	    alert("$alertmsg");
 3937: 	    return false;
 3938: 	}
 3939: 	formname.submit();
 3940:     }
 3941: CSVFORMJS
 3942:     return $result;
 3943: }
 3944: 
 3945: sub upcsvScores_form {
 3946:     my ($request) = shift;
 3947:     my ($symb)=&get_symb($request);
 3948:     if (!$symb) {return '';}
 3949:     my $result=&checkforfile_js();
 3950:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 3951:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 3952:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
 3953: 	'</b></td></tr>'."\n";
 3954:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 3955:     my $upload=&mt("Upload Scores");
 3956:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 3957:     my $ignore=&mt('Ignore First Line');
 3958:     $symb = &Apache::lonenc::check_encrypt($symb);
 3959:     $result.=<<ENDUPFORM;
 3960: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3961: <input type="hidden" name="symb" value="$symb" />
 3962: <input type="hidden" name="command" value="csvuploadmap" />
 3963: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3964: $upfile_select
 3965: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 3966: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 3967: </form>
 3968: ENDUPFORM
 3969:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 3970:                            &mt("How do I create a CSV file from a spreadsheet"))
 3971:     .'</td></tr></table>'."\n";
 3972:     $result.='</td></tr></table><br /><br />'."\n";
 3973:     $result.=&show_grading_menu_form($symb);
 3974:     return $result;
 3975: }
 3976: 
 3977: 
 3978: sub csvuploadmap {
 3979:     my ($request)= @_;
 3980:     my ($symb)=&get_symb($request);
 3981:     if (!$symb) {return '';}
 3982: 
 3983:     my $datatoken;
 3984:     if (!$env{'form.datatoken'}) {
 3985: 	$datatoken=&Apache::loncommon::upfile_store($request);
 3986:     } else {
 3987: 	$datatoken=$env{'form.datatoken'};
 3988: 	&Apache::loncommon::load_tmp_file($request);
 3989:     }
 3990:     my @records=&Apache::loncommon::upfile_record_sep();
 3991:     if ($env{'form.noFirstLine'}) { shift(@records); }
 3992:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 3993:     my ($i,$keyfields);
 3994:     if (@records) {
 3995:         my $fieldserror;
 3996: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 3997:         if ($fieldserror) {
 3998:             $request->print(&navmap_errormsg());
 3999:             return;
 4000:         }
 4001: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 4002: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 4003: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 4004: 							  \@fields);
 4005: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 4006: 	    chop($keyfields);
 4007: 	} else {
 4008: 	    unshift(@fields,['none','']);
 4009: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 4010: 							    \@fields);
 4011:             foreach my $rec (@records) {
 4012:                 my %temp = &Apache::loncommon::record_sep($rec);
 4013:                 if (%temp) {
 4014:                     $keyfields=join(',',sort(keys(%temp)));
 4015:                     last;
 4016:                 }
 4017:             }
 4018: 	}
 4019:     }
 4020:     &csvuploadmap_footer($request,$i,$keyfields);
 4021:     $request->print(&show_grading_menu_form($symb));
 4022: 
 4023:     return '';
 4024: }
 4025: 
 4026: sub csvuploadoptions {
 4027:     my ($request)= @_;
 4028:     my ($symb)=&get_symb($request);
 4029:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 4030:     my $ignore=&mt('Ignore First Line');
 4031:     $request->print(<<ENDPICK);
 4032: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4033: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
 4034: <input type="hidden" name="command"    value="csvuploadassign" />
 4035: <!--
 4036: <p>
 4037: <label>
 4038:    <input type="checkbox" name="show_full_results" />
 4039:    Show a table of all changes
 4040: </label>
 4041: </p>
 4042: -->
 4043: <p>
 4044: <label>
 4045:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4046:    Overwrite any existing score
 4047: </label>
 4048: </p>
 4049: ENDPICK
 4050:     my %fields=&get_fields();
 4051:     if (!defined($fields{'domain'})) {
 4052: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4053: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
 4054:     }
 4055:     foreach my $key (sort(keys(%env))) {
 4056: 	if ($key !~ /^form\.(.*)$/) { next; }
 4057: 	my $cleankey=$1;
 4058: 	if ($cleankey eq 'command') { next; }
 4059: 	$request->print('<input type="hidden" name="'.$cleankey.
 4060: 			'"  value="'.$env{$key}.'" />'."\n");
 4061:     }
 4062:     # FIXME do a check for any duplicated user ids...
 4063:     # FIXME do a check for any invalid user ids?...
 4064:     $request->print('<input type="submit" value="Assign Grades" /><br />
 4065: <hr /></form>'."\n");
 4066:     $request->print(&show_grading_menu_form($symb));
 4067:     return '';
 4068: }
 4069: 
 4070: sub get_fields {
 4071:     my %fields;
 4072:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4073:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4074: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4075: 	    if ($env{'form.f'.$i} ne 'none') {
 4076: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4077: 	    }
 4078: 	} else {
 4079: 	    if ($env{'form.f'.$i} ne 'none') {
 4080: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4081: 	    }
 4082: 	}
 4083:     }
 4084:     return %fields;
 4085: }
 4086: 
 4087: sub csvuploadassign {
 4088:     my ($request)= @_;
 4089:     my ($symb)=&get_symb($request);
 4090:     if (!$symb) {return '';}
 4091:     my $error_msg = '';
 4092:     &Apache::loncommon::load_tmp_file($request);
 4093:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4094:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 4095:     my %fields=&get_fields();
 4096:     $request->print('<h3>Assigning Grades</h3>');
 4097:     my $courseid=$env{'request.course.id'};
 4098:     my ($classlist) = &getclasslist('all',0);
 4099:     my @notallowed;
 4100:     my @skipped;
 4101:     my $countdone=0;
 4102:     foreach my $grade (@gradedata) {
 4103: 	my %entries=&Apache::loncommon::record_sep($grade);
 4104: 	my $domain;
 4105: 	if ($entries{$fields{'domain'}}) {
 4106: 	    $domain=$entries{$fields{'domain'}};
 4107: 	} else {
 4108: 	    $domain=$env{'form.default_domain'};
 4109: 	}
 4110: 	$domain=~s/\s//g;
 4111: 	my $username=$entries{$fields{'username'}};
 4112: 	$username=~s/\s//g;
 4113: 	if (!$username) {
 4114: 	    my $id=$entries{$fields{'ID'}};
 4115: 	    $id=~s/\s//g;
 4116: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4117: 	    $username=$ids{$id};
 4118: 	}
 4119: 	if (!exists($$classlist{"$username:$domain"})) {
 4120: 	    my $id=$entries{$fields{'ID'}};
 4121: 	    $id=~s/\s//g;
 4122: 	    if ($id) {
 4123: 		push(@skipped,"$id:$domain");
 4124: 	    } else {
 4125: 		push(@skipped,"$username:$domain");
 4126: 	    }
 4127: 	    next;
 4128: 	}
 4129: 	my $usec=$classlist->{"$username:$domain"}[5];
 4130: 	if (!&canmodify($usec)) {
 4131: 	    push(@notallowed,"$username:$domain");
 4132: 	    next;
 4133: 	}
 4134: 	my %points;
 4135: 	my %grades;
 4136: 	foreach my $dest (keys(%fields)) {
 4137: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4138: 		$dest eq 'domain') { next; }
 4139: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4140: 	    if ($dest=~/stores_(.*)_points/) {
 4141: 		my $part=$1;
 4142: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4143: 					      $symb,$domain,$username);
 4144:                 if ($wgt) {
 4145:                     $entries{$fields{$dest}}=~s/\s//g;
 4146:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4147:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4148:                                           : 'correct_by_override';
 4149:                     $grades{"resource.$part.awarded"}=$pcr;
 4150:                     $grades{"resource.$part.solved"}=$award;
 4151:                     $points{$part}=1;
 4152:                 } else {
 4153:                     $error_msg = "<br />" .
 4154:                         &mt("Some point values were assigned"
 4155:                             ." for problems with a weight "
 4156:                             ."of zero. These values were "
 4157:                             ."ignored.");
 4158:                 }
 4159: 	    } else {
 4160: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4161: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4162: 		my $store_key=$dest;
 4163: 		$store_key=~s/^stores/resource/;
 4164: 		$store_key=~s/_/\./g;
 4165: 		$grades{$store_key}=$entries{$fields{$dest}};
 4166: 	    }
 4167: 	}
 4168: 	if (! %grades) { 
 4169:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4170:         } else {
 4171: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4172: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4173: 					   $env{'request.course.id'},
 4174: 					   $domain,$username);
 4175: 	   if ($result eq 'ok') {
 4176: 	      $request->print('.');
 4177: 	   } else {
 4178: 	      $request->print("<p><span class=\"LC_error\">".
 4179:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4180:                                   "$username:$domain",$result)."</span></p>");
 4181: 	   }
 4182: 	   $request->rflush();
 4183: 	   $countdone++;
 4184:         }
 4185:     }
 4186:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 4187:     if (@skipped) {
 4188: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 4189:         $request->print(join(', ',@skipped));
 4190:     }
 4191:     if (@notallowed) {
 4192: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 4193: 	$request->print(join(', ',@notallowed));
 4194:     }
 4195:     $request->print("<br />\n");
 4196:     $request->print(&show_grading_menu_form($symb));
 4197:     return $error_msg;
 4198: }
 4199: #------------- end of section for handling csv file upload ---------
 4200: #
 4201: #-------------------------------------------------------------------
 4202: #
 4203: #-------------- Next few routines handle grading by page/sequence
 4204: #
 4205: #--- Select a page/sequence and a student to grade
 4206: sub pickStudentPage {
 4207:     my ($request) = shift;
 4208: 
 4209:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4210:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
 4211: 
 4212: function checkPickOne(formname) {
 4213:     if (radioSelection(formname.student) == null) {
 4214: 	alert("$alertmsg");
 4215: 	return;
 4216:     }
 4217:     ptr = pullDownSelection(formname.selectpage);
 4218:     formname.page.value = formname["page"+ptr].value;
 4219:     formname.title.value = formname["title"+ptr].value;
 4220:     formname.submit();
 4221: }
 4222: 
 4223: LISTJAVASCRIPT
 4224:     &commonJSfunctions($request);
 4225:     my ($symb) = &get_symb($request);
 4226:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4227:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4228:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4229: 
 4230:     my $result='<h3><span class="LC_info">&nbsp;'.
 4231: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4232: 
 4233:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4234:     my $map_error;
 4235:     my ($titles,$symbx) = &getSymbMap($map_error);
 4236:     if ($map_error) {
 4237:         $request->print(&navmap_errormsg());
 4238:         return; 
 4239:     }
 4240:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4241: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4242: #    my $type=($curpage =~ /\.(page|sequence)/);
 4243:     my $select = '<select name="selectpage">'."\n";
 4244:     my $ctr=0;
 4245:     foreach (@$titles) {
 4246: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4247: 	$select.='<option value="'.$ctr.'" '.
 4248: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4249: 	    '>'.$showtitle.'</option>'."\n";
 4250: 	$ctr++;
 4251:     }
 4252:     $select.= '</select>';
 4253:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
 4254: 
 4255:     $ctr=0;
 4256:     foreach (@$titles) {
 4257: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4258: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4259: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4260: 	$ctr++;
 4261:     }
 4262:     $result.='<input type="hidden" name="page" />'."\n".
 4263: 	'<input type="hidden" name="title" />'."\n";
 4264: 
 4265:     my $options =
 4266: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
 4267: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
 4268:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
 4269: 
 4270:     $options =
 4271: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
 4272: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
 4273: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
 4274:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
 4275:     
 4276:     $result.=&build_section_inputs();
 4277:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4278:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4279: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4280: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4281: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
 4282: 
 4283:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
 4284: 
 4285:     $result.='&nbsp;<input type="button" '.
 4286:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4287: 
 4288:     $request->print($result);
 4289: 
 4290:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4291: 	&Apache::loncommon::start_data_table().
 4292: 	&Apache::loncommon::start_data_table_header_row().
 4293: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4294: 	'<th>'.&nameUserString('header').'</th>'.
 4295: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4296: 	'<th>'.&nameUserString('header').'</th>'.
 4297: 	&Apache::loncommon::end_data_table_header_row();
 4298:  
 4299:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4300:     my $ptr = 1;
 4301:     foreach my $student (sort 
 4302: 			 {
 4303: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4304: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4305: 			     }
 4306: 			     return $a cmp $b;
 4307: 			 } (keys(%$fullname))) {
 4308: 	my ($uname,$udom) = split(/:/,$student);
 4309: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4310:                                   : '</td>');
 4311: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4312: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4313: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4314: 	$studentTable.=
 4315: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4316:                          : '');
 4317: 	$ptr++;
 4318:     }
 4319:     if ($ptr%2 == 0) {
 4320: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4321: 	    &Apache::loncommon::end_data_table_row();
 4322:     }
 4323:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4324:     $studentTable.='<input type="button" '.
 4325:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4326: 
 4327:     $studentTable.=&show_grading_menu_form($symb);
 4328:     $request->print($studentTable);
 4329: 
 4330:     return '';
 4331: }
 4332: 
 4333: sub getSymbMap {
 4334:     my ($map_error) = @_;
 4335:     my $navmap = Apache::lonnavmaps::navmap->new();
 4336:     unless (ref($navmap)) {
 4337:         if (ref($map_error)) {
 4338:             $$map_error = 'navmap';
 4339:         }
 4340:         return;
 4341:     }
 4342:     my %symbx = ();
 4343:     my @titles = ();
 4344:     my $minder = 0;
 4345: 
 4346:     # Gather every sequence that has problems.
 4347:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4348: 					       1,0,1);
 4349:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4350: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4351: 	    my $title = $minder.'.'.
 4352: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4353: 	    push(@titles, $title); # minder in case two titles are identical
 4354: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4355: 	    $minder++;
 4356: 	}
 4357:     }
 4358:     return \@titles,\%symbx;
 4359: }
 4360: 
 4361: #
 4362: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4363: sub displayPage {
 4364:     my ($request) = shift;
 4365: 
 4366:     my ($symb) = &get_symb($request);
 4367:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4368:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4369:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4370:     my $pageTitle = $env{'form.page'};
 4371:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4372:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4373:     my $usec=$classlist->{$env{'form.student'}}[5];
 4374: 
 4375:     #need to make sure we have the correct data for later EXT calls, 
 4376:     #thus invalidate the cache
 4377:     &Apache::lonnet::devalidatecourseresdata(
 4378:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4379:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4380:     &Apache::lonnet::clear_EXT_cache_status();
 4381: 
 4382:     if (!&canview($usec)) {
 4383: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
 4384: 	$request->print(&show_grading_menu_form($symb));
 4385: 	return;
 4386:     }
 4387:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4388:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4389: 	'</h3>'."\n";
 4390:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4391:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4392: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4393:     } else {
 4394: 	delete($env{'form.CODE'});
 4395:     }
 4396:     &sub_page_js($request);
 4397:     $request->print($result);
 4398: 
 4399:     my $navmap = Apache::lonnavmaps::navmap->new();
 4400:     unless (ref($navmap)) {
 4401:         $request->print(&navmap_errormsg());
 4402:         $request->print(&show_grading_menu_form($symb));
 4403:         return;
 4404:     }
 4405:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4406:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4407:     if (!$map) {
 4408: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4409: 	$request->print(&show_grading_menu_form($symb));
 4410: 	return; 
 4411:     }
 4412:     my $iterator = $navmap->getIterator($map->map_start(),
 4413: 					$map->map_finish());
 4414: 
 4415:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4416: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4417: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4418: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4419: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4420: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4421: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4422: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
 4423: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
 4424: 
 4425:     if (defined($env{'form.CODE'})) {
 4426: 	$studentTable.=
 4427: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4428:     }
 4429:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4430: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4431: 
 4432:     $studentTable.='&nbsp;<span class="LC_info">'.
 4433:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 4434:         '</span>'."\n".
 4435: 	&Apache::loncommon::start_data_table().
 4436: 	&Apache::loncommon::start_data_table_header_row().
 4437: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
 4438: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4439: 	&Apache::loncommon::end_data_table_header_row();
 4440: 
 4441:     &Apache::lonxml::clear_problem_counter();
 4442:     my ($depth,$question,$prob) = (1,1,1);
 4443:     $iterator->next(); # skip the first BEGIN_MAP
 4444:     my $curRes = $iterator->next(); # for "current resource"
 4445:     while ($depth > 0) {
 4446:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4447:         if($curRes == $iterator->END_MAP) { $depth--; }
 4448: 
 4449:         if (ref($curRes) && $curRes->is_problem()) {
 4450: 	    my $parts = $curRes->parts();
 4451:             my $title = $curRes->compTitle();
 4452: 	    my $symbx = $curRes->symb();
 4453: 	    $studentTable.=
 4454: 		&Apache::loncommon::start_data_table_row().
 4455: 		'<td align="center" valign="top" >'.$prob.
 4456: 		(scalar(@{$parts}) == 1 ? '' 
 4457: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
 4458: 							scalar(@{$parts}))
 4459: 		 ).
 4460: 		 '</td>';
 4461: 	    $studentTable.='<td valign="top">';
 4462: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4463: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4464: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4465: 					     undef,'both',\%form);
 4466: 	    } else {
 4467: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4468: 		$companswer =~ s|<form(.*?)>||g;
 4469: 		$companswer =~ s|</form>||g;
 4470: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4471: #		    $companswer =~ s/$1/ /ms;
 4472: #		    $request->print('match='.$1."<br />\n");
 4473: #		}
 4474: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4475: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 4476: 	    }
 4477: 
 4478: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4479: 
 4480: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4481: 		if ($record{'version'} eq '') {
 4482: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4483: 		} else {
 4484: 		    my %responseType = ();
 4485: 		    foreach my $partid (@{$parts}) {
 4486: 			my @responseIds =$curRes->responseIds($partid);
 4487: 			my @responseType =$curRes->responseType($partid);
 4488: 			my %responseIds;
 4489: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4490: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4491: 			}
 4492: 			$responseType{$partid} = \%responseIds;
 4493: 		    }
 4494: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4495: 
 4496: 		}
 4497: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4498: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4499: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4500: 									$env{'request.course.id'},
 4501: 									'','.submission');
 4502:  
 4503: 	    }
 4504: 	    if (&canmodify($usec)) {
 4505:             $studentTable.=&gradeBox_start();
 4506: 		foreach my $partid (@{$parts}) {
 4507: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4508: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4509: 		    $question++;
 4510: 		}
 4511:             $studentTable.=&gradeBox_end();
 4512: 		$prob++;
 4513: 	    }
 4514: 	    $studentTable.='</td></tr>';
 4515: 
 4516: 	}
 4517:         $curRes = $iterator->next();
 4518:     }
 4519: 
 4520:     $studentTable.=
 4521:         '</table>'."\n".
 4522:         '<input type="button" value="'.&mt('Save').'" '.
 4523:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4524:         '</form>'."\n";
 4525:     $studentTable.=&show_grading_menu_form($symb);
 4526:     $request->print($studentTable);
 4527: 
 4528:     return '';
 4529: }
 4530: 
 4531: sub displaySubByDates {
 4532:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4533:     my $isCODE=0;
 4534:     my $isTask = ($symb =~/\.task$/);
 4535:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4536:     my $studentTable=&Apache::loncommon::start_data_table().
 4537: 	&Apache::loncommon::start_data_table_header_row().
 4538: 	'<th>'.&mt('Date/Time').'</th>'.
 4539: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4540: 	'<th>'.&mt('Submission').'</th>'.
 4541: 	'<th>'.&mt('Status').'</th>'.
 4542: 	&Apache::loncommon::end_data_table_header_row();
 4543:     my ($version);
 4544:     my %mark;
 4545:     my %orders;
 4546:     $mark{'correct_by_student'} = $checkIcon;
 4547:     if (!exists($$record{'1:timestamp'})) {
 4548: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 4549:     }
 4550: 
 4551:     my $interaction;
 4552:     my $no_increment = 1;
 4553:     for ($version=1;$version<=$$record{'version'};$version++) {
 4554: 	my $timestamp = 
 4555: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4556: 	if (exists($$record{$version.':resource.0.version'})) {
 4557: 	    $interaction = $$record{$version.':resource.0.version'};
 4558: 	}
 4559: 
 4560: 	my $where = ($isTask ? "$version:resource.$interaction"
 4561: 		             : "$version:resource");
 4562: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4563: 	    '<td>'.$timestamp.'</td>';
 4564: 	if ($isCODE) {
 4565: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4566: 	}
 4567: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4568: 	my @displaySub = ();
 4569: 	foreach my $partid (@{$parts}) {
 4570:             my $hidden;
 4571:             if (($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurvey') ||
 4572:                 ($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurveycred')) {
 4573:                 $hidden = 1;
 4574:             }
 4575: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4576: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4577: 	    
 4578: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4579: 	    my $display_part=&get_display_part($partid,$symb);
 4580: 	    foreach my $matchKey (@matchKey) {
 4581: 		if (exists($$record{$version.':'.$matchKey}) &&
 4582: 		    $$record{$version.':'.$matchKey} ne '') {
 4583:                     
 4584: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4585: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4586:                     $displaySub[0].='<span class="LC_nobreak"';
 4587:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 4588:                                    .' <span class="LC_internal_info">'
 4589:                                    .'('.&mt('Part ID: [_1]',$responseId).')'
 4590:                                    .'</span>'
 4591:                                    .' <b>';
 4592:                     if ($hidden) {
 4593:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
 4594:                     } else {
 4595: 		        if ($$record{"$where.$partid.tries"} eq '') {
 4596: 			    $displaySub[0].=&mt('Trial not counted');
 4597: 		        } else {
 4598: 			    $displaySub[0].=&mt('Trial: [_1]',
 4599: 					    $$record{"$where.$partid.tries"});
 4600: 		        }
 4601: 		        my $responseType=($isTask ? 'Task'
 4602:                                               : $responseType->{$partid}->{$responseId});
 4603: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4604: 		        if (!exists($orders{$partid}->{$responseId})) {
 4605: 			    $orders{$partid}->{$responseId}=
 4606: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
 4607:                                            $no_increment);
 4608: 		        }
 4609: 		        $displaySub[0].='</b></span>'; # /nobreak
 4610: 		        $displaySub[0].='&nbsp; '.
 4611: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
 4612:                     }
 4613: 		}
 4614: 	    }
 4615: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4616: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 4617: 				    $$record{"$where.$partid.checkedin"},
 4618: 				    $$record{"$where.$partid.checkedin.slot"}).
 4619: 					'<br />';
 4620: 	    }
 4621: 	    if (exists $$record{"$where.$partid.award"}) {
 4622: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 4623: 		    lc($$record{"$where.$partid.award"}).' '.
 4624: 		    $mark{$$record{"$where.$partid.solved"}}.
 4625: 		    '<br />';
 4626: 	    }
 4627: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4628: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4629: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4630: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4631: 		$displaySub[2].=
 4632: 		    $$record{"$version:resource.$partid.regrader"}.
 4633: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4634: 	    }
 4635: 	}
 4636: 	# needed because old essay regrader has not parts info
 4637: 	if (exists $$record{"$version:resource.regrader"}) {
 4638: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 4639: 	}
 4640: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 4641: 	if ($displaySub[2]) {
 4642: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 4643: 	}
 4644: 	$studentTable.='&nbsp;</td>'.
 4645: 	    &Apache::loncommon::end_data_table_row();
 4646:     }
 4647:     $studentTable.=&Apache::loncommon::end_data_table();
 4648:     return $studentTable;
 4649: }
 4650: 
 4651: sub updateGradeByPage {
 4652:     my ($request) = shift;
 4653: 
 4654:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4655:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4656:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4657:     my $pageTitle = $env{'form.page'};
 4658:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4659:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4660:     my $usec=$classlist->{$env{'form.student'}}[5];
 4661:     if (!&canmodify($usec)) {
 4662: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 4663: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
 4664: 	return;
 4665:     }
 4666:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4667:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 4668: 	'</h3>'."\n";
 4669: 
 4670:     $request->print($result);
 4671: 
 4672: 
 4673:     my $navmap = Apache::lonnavmaps::navmap->new();
 4674:     unless (ref($navmap)) {
 4675:         $request->print(&navmap_errormsg());
 4676:         return;
 4677:     }
 4678:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 4679:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4680:     if (!$map) {
 4681: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 4682: 	my ($symb)=&get_symb($request);
 4683: 	$request->print(&show_grading_menu_form($symb));
 4684: 	return; 
 4685:     }
 4686:     my $iterator = $navmap->getIterator($map->map_start(),
 4687: 					$map->map_finish());
 4688: 
 4689:     my $studentTable=
 4690: 	&Apache::loncommon::start_data_table().
 4691: 	&Apache::loncommon::start_data_table_header_row().
 4692: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 4693: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 4694: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 4695: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 4696: 	&Apache::loncommon::end_data_table_header_row();
 4697: 
 4698:     $iterator->next(); # skip the first BEGIN_MAP
 4699:     my $curRes = $iterator->next(); # for "current resource"
 4700:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 4701:     while ($depth > 0) {
 4702:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4703:         if($curRes == $iterator->END_MAP) { $depth--; }
 4704: 
 4705:         if (ref($curRes) && $curRes->is_problem()) {
 4706: 	    my $parts = $curRes->parts();
 4707:             my $title = $curRes->compTitle();
 4708: 	    my $symbx = $curRes->symb();
 4709: 	    $studentTable.=
 4710: 		&Apache::loncommon::start_data_table_row().
 4711: 		'<td align="center" valign="top" >'.$prob.
 4712: 		(scalar(@{$parts}) == 1 ? '' 
 4713:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
 4714: 		.')').'</td>';
 4715: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 4716: 
 4717: 	    my %newrecord=();
 4718: 	    my @displayPts=();
 4719:             my %aggregate = ();
 4720:             my $aggregateflag = 0;
 4721: 	    foreach my $partid (@{$parts}) {
 4722: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 4723: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 4724: 
 4725: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 4726: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 4727: 		my $partial = $newpts/$wgt;
 4728: 		my $score;
 4729: 		if ($partial > 0) {
 4730: 		    $score = 'correct_by_override';
 4731: 		} elsif ($newpts ne '') { #empty is taken as 0
 4732: 		    $score = 'incorrect_by_override';
 4733: 		}
 4734: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 4735: 		if ($dropMenu eq 'excused') {
 4736: 		    $partial = '';
 4737: 		    $score = 'excused';
 4738: 		} elsif ($dropMenu eq 'reset status'
 4739: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 4740: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 4741: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 4742: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 4743: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 4744: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 4745: 		    $changeflag++;
 4746: 		    $newpts = '';
 4747:                     
 4748:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 4749:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 4750:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 4751:                     if ($aggtries > 0) {
 4752:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4753:                         $aggregateflag = 1;
 4754:                     }
 4755: 		}
 4756: 		my $display_part=&get_display_part($partid,$curRes->symb());
 4757: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 4758: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4759: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 4760: 		    '&nbsp;<br />';
 4761: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4762: 		     (($score eq 'excused') ? 'excused' : $newpts).
 4763: 		    '&nbsp;<br />';
 4764: 		$question++;
 4765: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 4766: 
 4767: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 4768: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 4769: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 4770: 		    if (scalar(keys(%newrecord)) > 0);
 4771: 
 4772: 		$changeflag++;
 4773: 	    }
 4774: 	    if (scalar(keys(%newrecord)) > 0) {
 4775: 		my %record = 
 4776: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 4777: 					     $udom,$uname);
 4778: 
 4779: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 4780: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 4781: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 4782: 		    $newrecord{'resource.CODE'} = '';
 4783: 		}
 4784: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 4785: 					$udom,$uname);
 4786: 		%record = &Apache::lonnet::restore($symbx,
 4787: 						   $env{'request.course.id'},
 4788: 						   $udom,$uname);
 4789: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 4790: 					     $cdom,$cnum,$udom,$uname);
 4791: 	    }
 4792: 	    
 4793:             if ($aggregateflag) {
 4794:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4795:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 4796:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 4797:             }
 4798: 
 4799: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 4800: 		'<td valign="top">'.$displayPts[1].'</td>'.
 4801: 		&Apache::loncommon::end_data_table_row();
 4802: 
 4803: 	    $prob++;
 4804: 	}
 4805:         $curRes = $iterator->next();
 4806:     }
 4807: 
 4808:     $studentTable.=&Apache::loncommon::end_data_table();
 4809:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
 4810:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 4811: 		  &mt('The scores were changed for [quant,_1,problem].',
 4812: 		  $changeflag));
 4813:     $request->print($grademsg.$studentTable);
 4814: 
 4815:     return '';
 4816: }
 4817: 
 4818: #-------- end of section for handling grading by page/sequence ---------
 4819: #
 4820: #-------------------------------------------------------------------
 4821: 
 4822: #-------------------- Bubblesheet (Scantron) Grading -------------------
 4823: #
 4824: #------ start of section for handling grading by page/sequence ---------
 4825: 
 4826: =pod
 4827: 
 4828: =head1 Bubble sheet grading routines
 4829: 
 4830:   For this documentation:
 4831: 
 4832:    'scanline' refers to the full line of characters
 4833:    from the file that we are parsing that represents one entire sheet
 4834: 
 4835:    'bubble line' refers to the data
 4836:    representing the line of bubbles that are on the physical bubble sheet
 4837: 
 4838: 
 4839: The overall process is that a scanned in bubble sheet data is uploaded
 4840: into a course. When a user wants to grade, they select a
 4841: sequence/folder of resources, a file of bubble sheet info, and pick
 4842: one of the predefined configurations for what each scanline looks
 4843: like.
 4844: 
 4845: Next each scanline is checked for any errors of either 'missing
 4846: bubbles' (it's an error because it may have been mis-scanned
 4847: because too light bubbling), 'double bubble' (each bubble line should
 4848: have no more that one letter picked), invalid or duplicated CODE,
 4849: invalid student/employee ID
 4850: 
 4851: If the CODE option is used that determines the randomization of the
 4852: homework problems, either way the student/employee ID is looked up into a
 4853: username:domain.
 4854: 
 4855: During the validation phase the instructor can choose to skip scanlines. 
 4856: 
 4857: After the validation phase, there are now 3 bubble sheet files
 4858: 
 4859:   scantron_original_filename (unmodified original file)
 4860:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 4861:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 4862: 
 4863: Also there is a separate hash nohist_scantrondata that contains extra
 4864: correction information that isn't representable in the bubble sheet
 4865: file (see &scantron_getfile() for more information)
 4866: 
 4867: After all scanlines are either valid, marked as valid or skipped, then
 4868: foreach line foreach problem in the picked sequence, an ssi request is
 4869: made that simulates a user submitting their selected letter(s) against
 4870: the homework problem.
 4871: 
 4872: =over 4
 4873: 
 4874: 
 4875: 
 4876: =item defaultFormData
 4877: 
 4878:   Returns html hidden inputs used to hold context/default values.
 4879: 
 4880:  Arguments:
 4881:   $symb - $symb of the current resource 
 4882: 
 4883: =cut
 4884: 
 4885: sub defaultFormData {
 4886:     my ($symb)=@_;
 4887:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4888:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />';
 4889: }
 4890: 
 4891: 
 4892: =pod 
 4893: 
 4894: =item getSequenceDropDown
 4895: 
 4896:    Return html dropdown of possible sequences to grade
 4897:  
 4898:  Arguments:
 4899:    $symb - $symb of the current resource
 4900:    $map_error - ref to scalar which will container error if
 4901:                 $navmap object is unavailable in &getSymbMap().
 4902: 
 4903: =cut
 4904: 
 4905: sub getSequenceDropDown {
 4906:     my ($symb,$map_error)=@_;
 4907:     my $result='<select name="selectpage">'."\n";
 4908:     my ($titles,$symbx) = &getSymbMap($map_error);
 4909:     if (ref($map_error)) {
 4910:         return if ($$map_error);
 4911:     }
 4912:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 4913:     my $ctr=0;
 4914:     foreach (@$titles) {
 4915: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4916: 	$result.='<option value="'.$$symbx{$_}.'" '.
 4917: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4918: 	    '>'.$showtitle.'</option>'."\n";
 4919: 	$ctr++;
 4920:     }
 4921:     $result.= '</select>';
 4922:     return $result;
 4923: }
 4924: 
 4925: my %bubble_lines_per_response;     # no. bubble lines for each response.
 4926:                                    # key is zero-based index - 0, 1, 2 ...
 4927: 
 4928: my %first_bubble_line;             # First bubble line no. for each bubble.
 4929: 
 4930: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 4931:                                    # matchresponse or rankresponse, where 
 4932:                                    # an individual response can have multiple 
 4933:                                    # lines
 4934: 
 4935: my %responsetype_per_response;     # responsetype for each response
 4936: 
 4937: # Save and restore the bubble lines array to the form env.
 4938: 
 4939: 
 4940: sub save_bubble_lines {
 4941:     foreach my $line (keys(%bubble_lines_per_response)) {
 4942: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 4943: 	$env{"form.scantron.first_bubble_line.$line"} =
 4944: 	    $first_bubble_line{$line};
 4945:         $env{"form.scantron.sub_bubblelines.$line"} = 
 4946:             $subdivided_bubble_lines{$line};
 4947:         $env{"form.scantron.responsetype.$line"} =
 4948:             $responsetype_per_response{$line};
 4949:     }
 4950: }
 4951: 
 4952: 
 4953: sub restore_bubble_lines {
 4954:     my $line = 0;
 4955:     %bubble_lines_per_response = ();
 4956:     while ($env{"form.scantron.bubblelines.$line"}) {
 4957: 	my $value = $env{"form.scantron.bubblelines.$line"};
 4958: 	$bubble_lines_per_response{$line} = $value;
 4959: 	$first_bubble_line{$line}  =
 4960: 	    $env{"form.scantron.first_bubble_line.$line"};
 4961:         $subdivided_bubble_lines{$line} =
 4962:             $env{"form.scantron.sub_bubblelines.$line"};
 4963:         $responsetype_per_response{$line} =
 4964:             $env{"form.scantron.responsetype.$line"};
 4965: 	$line++;
 4966:     }
 4967: }
 4968: 
 4969: #  Given the parsed scanline, get the response for 
 4970: #  'answer' number n:
 4971: 
 4972: sub get_response_bubbles {
 4973:     my ($parsed_line, $response)  = @_;
 4974: 
 4975:     my $bubble_line = $first_bubble_line{$response-1} +1;
 4976:     my $bubble_lines= $bubble_lines_per_response{$response-1};
 4977:     
 4978:     my $selected = "";
 4979: 
 4980:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
 4981: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
 4982: 	$bubble_line++;
 4983:     }
 4984:     return $selected;
 4985: }
 4986: 
 4987: =pod 
 4988: 
 4989: =item scantron_filenames
 4990: 
 4991:    Returns a list of the scantron files in the current course 
 4992: 
 4993: =cut
 4994: 
 4995: sub scantron_filenames {
 4996:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4997:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4998:     my $getpropath = 1;
 4999:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
 5000:                                        $getpropath);
 5001:     my @possiblenames;
 5002:     foreach my $filename (sort(@files)) {
 5003: 	($filename)=split(/&/,$filename);
 5004: 	if ($filename!~/^scantron_orig_/) { next ; }
 5005: 	$filename=~s/^scantron_orig_//;
 5006: 	push(@possiblenames,$filename);
 5007:     }
 5008:     return @possiblenames;
 5009: }
 5010: 
 5011: =pod 
 5012: 
 5013: =item scantron_uploads
 5014: 
 5015:    Returns  html drop-down list of scantron files in current course.
 5016: 
 5017:  Arguments:
 5018:    $file2grade - filename to set as selected in the dropdown
 5019: 
 5020: =cut
 5021: 
 5022: sub scantron_uploads {
 5023:     my ($file2grade) = @_;
 5024:     my $result=	'<select name="scantron_selectfile">';
 5025:     $result.="<option></option>";
 5026:     foreach my $filename (sort(&scantron_filenames())) {
 5027: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 5028:     }
 5029:     $result.="</select>";
 5030:     return $result;
 5031: }
 5032: 
 5033: =pod 
 5034: 
 5035: =item scantron_scantab
 5036: 
 5037:   Returns html drop down of the scantron formats in the scantronformat.tab
 5038:   file.
 5039: 
 5040: =cut
 5041: 
 5042: sub scantron_scantab {
 5043:     my $result='<select name="scantron_format">'."\n";
 5044:     $result.='<option></option>'."\n";
 5045:     my @lines = &get_scantronformat_file();
 5046:     if (@lines > 0) {
 5047:         foreach my $line (@lines) {
 5048:             next if (($line =~ /^\#/) || ($line eq ''));
 5049: 	    my ($name,$descrip)=split(/:/,$line);
 5050: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 5051:         }
 5052:     }
 5053:     $result.='</select>'."\n";
 5054:     return $result;
 5055: }
 5056: 
 5057: =pod
 5058: 
 5059: =item get_scantronformat_file
 5060: 
 5061:   Returns an array containing lines from the scantron format file for
 5062:   the domain of the course.
 5063: 
 5064:   If a url for a custom.tab file is listed in domain's configuration.db, 
 5065:   lines are from this file.
 5066: 
 5067:   Otherwise, if a default.tab has been published in RES space by the 
 5068:   domainconfig user, lines are from this file.
 5069: 
 5070:   Otherwise, fall back to getting lines from the legacy file on the
 5071:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 5072: 
 5073: =cut
 5074: 
 5075: sub get_scantronformat_file {
 5076:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5077:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 5078:     my $gottab = 0;
 5079:     my @lines;
 5080:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5081:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5082:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5083:             if ($formatfile ne '-1') {
 5084:                 @lines = split("\n",$formatfile,-1);
 5085:                 $gottab = 1;
 5086:             }
 5087:         }
 5088:     }
 5089:     if (!$gottab) {
 5090:         my $confname = $cdom.'-domainconfig';
 5091:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5092:         my $formatfile =  &Apache::lonnet::getfile($default);
 5093:         if ($formatfile ne '-1') {
 5094:             @lines = split("\n",$formatfile,-1);
 5095:             $gottab = 1;
 5096:         }
 5097:     }
 5098:     if (!$gottab) {
 5099:         my @domains = &Apache::lonnet::current_machine_domains();
 5100:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5101:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5102:             @lines = <$fh>;
 5103:             close($fh);
 5104:         } else {
 5105:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 5106:             @lines = <$fh>;
 5107:             close($fh);
 5108:         }
 5109:     }
 5110:     return @lines;
 5111: }
 5112: 
 5113: =pod 
 5114: 
 5115: =item scantron_CODElist
 5116: 
 5117:   Returns html drop down of the saved CODE lists from current course,
 5118:   generated from earlier printings.
 5119: 
 5120: =cut
 5121: 
 5122: sub scantron_CODElist {
 5123:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5124:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5125:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5126:     my $namechoice='<option></option>';
 5127:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5128: 	if ($name =~ /^error: 2 /) { next; }
 5129: 	if ($name =~ /^type\0/) { next; }
 5130: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5131:     }
 5132:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5133:     return $namechoice;
 5134: }
 5135: 
 5136: =pod 
 5137: 
 5138: =item scantron_CODEunique
 5139: 
 5140:   Returns the html for "Each CODE to be used once" radio.
 5141: 
 5142: =cut
 5143: 
 5144: sub scantron_CODEunique {
 5145:     my $result='<span class="LC_nobreak">
 5146:                  <label><input type="radio" name="scantron_CODEunique"
 5147:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5148:                 </span>
 5149:                 <span class="LC_nobreak">
 5150:                  <label><input type="radio" name="scantron_CODEunique"
 5151:                         value="no" />'.&mt('No').' </label>
 5152:                 </span>';
 5153:     return $result;
 5154: }
 5155: 
 5156: =pod 
 5157: 
 5158: =item scantron_selectphase
 5159: 
 5160:   Generates the initial screen to start the bubble sheet process.
 5161:   Allows for - starting a grading run.
 5162:              - downloading existing scan data (original, corrected
 5163:                                                 or skipped info)
 5164: 
 5165:              - uploading new scan data
 5166: 
 5167:  Arguments:
 5168:   $r          - The Apache request object
 5169:   $file2grade - name of the file that contain the scanned data to score
 5170: 
 5171: =cut
 5172: 
 5173: sub scantron_selectphase {
 5174:     my ($r,$file2grade) = @_;
 5175:     my ($symb)=&get_symb($r);
 5176:     if (!$symb) {return '';}
 5177:     my $map_error;
 5178:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 5179:     if ($map_error) {
 5180:         $r->print('<br />'.&navmap_errormsg().'<br />');
 5181:         return;
 5182:     }
 5183:     my $default_form_data=&defaultFormData($symb);
 5184:     my $grading_menu_button=&show_grading_menu_form($symb);
 5185:     my $file_selector=&scantron_uploads($file2grade);
 5186:     my $format_selector=&scantron_scantab();
 5187:     my $CODE_selector=&scantron_CODElist();
 5188:     my $CODE_unique=&scantron_CODEunique();
 5189:     my $result;
 5190: 
 5191:     $ssi_error = 0;
 5192: 
 5193:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5194:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5195: 
 5196: 	# Chunk of form to prompt for a scantron file upload.
 5197: 
 5198:         $r->print('
 5199:     <br />
 5200:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5201:        '.&Apache::loncommon::start_data_table_header_row().'
 5202:             <th>
 5203:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 5204:             </th>
 5205:        '.&Apache::loncommon::end_data_table_header_row().'
 5206:        '.&Apache::loncommon::start_data_table_row().'
 5207:             <td>
 5208: ');
 5209:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 5210:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5211:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5212:     $r->print(&Apache::lonhtmlcommon::scripttag('
 5213:     function checkUpload(formname) {
 5214: 	if (formname.upfile.value == "") {
 5215: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 5216: 	    return false;
 5217: 	}
 5218: 	formname.submit();
 5219:     }'));
 5220:     $r->print('
 5221:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5222:                 '.$default_form_data.'
 5223:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5224:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5225:                 <input name="command" value="scantronupload_save" type="hidden" />
 5226:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5227:                 <br />
 5228:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 5229:               </form>
 5230: ');
 5231: 
 5232:         $r->print('
 5233:             </td>
 5234:        '.&Apache::loncommon::end_data_table_row().'
 5235:        '.&Apache::loncommon::end_data_table().'
 5236: ');
 5237:     }
 5238: 
 5239:     # Chunk of form to prompt for a file to grade and how:
 5240: 
 5241:     $result.= '
 5242:     <br />
 5243:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5244:     <input type="hidden" name="command" value="scantron_warning" />
 5245:     '.$default_form_data.'
 5246:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5247:        '.&Apache::loncommon::start_data_table_header_row().'
 5248:             <th colspan="2">
 5249:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5250:             </th>
 5251:        '.&Apache::loncommon::end_data_table_header_row().'
 5252:        '.&Apache::loncommon::start_data_table_row().'
 5253:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5254:        '.&Apache::loncommon::end_data_table_row().'
 5255:        '.&Apache::loncommon::start_data_table_row().'
 5256:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 5257:        '.&Apache::loncommon::end_data_table_row().'
 5258:        '.&Apache::loncommon::start_data_table_row().'
 5259:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 5260:        '.&Apache::loncommon::end_data_table_row().'
 5261:        '.&Apache::loncommon::start_data_table_row().'
 5262:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5263:        '.&Apache::loncommon::end_data_table_row().'
 5264:        '.&Apache::loncommon::start_data_table_row().'
 5265:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5266:        '.&Apache::loncommon::end_data_table_row().'
 5267:        '.&Apache::loncommon::start_data_table_row().'
 5268: 	    <td> '.&mt('Options:').' </td>
 5269:             <td>
 5270: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5271:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5272:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5273: 	    </td>
 5274:        '.&Apache::loncommon::end_data_table_row().'
 5275:        '.&Apache::loncommon::start_data_table_row().'
 5276:             <td colspan="2">
 5277:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 5278:             </td>
 5279:        '.&Apache::loncommon::end_data_table_row().'
 5280:     '.&Apache::loncommon::end_data_table().'
 5281:     </form>
 5282: ';
 5283:    
 5284:     $r->print($result);
 5285: 
 5286: 
 5287: 
 5288:     # Chunk of the form that prompts to view a scoring office file,
 5289:     # corrected file, skipped records in a file.
 5290: 
 5291:     $r->print('
 5292:    <br />
 5293:    <form action="/adm/grades" name="scantron_download">
 5294:      '.$default_form_data.'
 5295:      <input type="hidden" name="command" value="scantron_download" />
 5296:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5297:        '.&Apache::loncommon::start_data_table_header_row().'
 5298:               <th>
 5299:                 &nbsp;'.&mt('Download a scoring office file').'
 5300:               </th>
 5301:        '.&Apache::loncommon::end_data_table_header_row().'
 5302:        '.&Apache::loncommon::start_data_table_row().'
 5303:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5304:                 <br />
 5305:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5306:        '.&Apache::loncommon::end_data_table_row().'
 5307:      '.&Apache::loncommon::end_data_table().'
 5308:    </form>
 5309:    <br />
 5310: ');
 5311: 
 5312:     &Apache::lonpickcode::code_list($r,2);
 5313: 
 5314:     $r->print('<br /><form method="post" name="checkscantron">'.
 5315:              $default_form_data."\n".
 5316:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5317:              &Apache::loncommon::start_data_table_header_row()."\n".
 5318:              '<th colspan="2">
 5319:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 5320:              '</th>'."\n".
 5321:               &Apache::loncommon::end_data_table_header_row()."\n".
 5322:               &Apache::loncommon::start_data_table_row()."\n".
 5323:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5324:               '<td> '.$sequence_selector.' </td>'.
 5325:               &Apache::loncommon::end_data_table_row()."\n".
 5326:               &Apache::loncommon::start_data_table_row()."\n".
 5327:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5328:               '<td> '.$file_selector.' </td>'."\n".
 5329:               &Apache::loncommon::end_data_table_row()."\n".
 5330:               &Apache::loncommon::start_data_table_row()."\n".
 5331:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5332:               '<td> '.$format_selector.' </td>'."\n".
 5333:               &Apache::loncommon::end_data_table_row()."\n".
 5334:               &Apache::loncommon::start_data_table_row()."\n".
 5335:               '<td> '.&mt('Options').' </td>'."\n".
 5336:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 5337:               &Apache::loncommon::end_data_table_row()."\n".
 5338:               &Apache::loncommon::start_data_table_row()."\n".
 5339:               '<td colspan="2">'."\n".
 5340:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5341:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 5342:               '</td>'."\n".
 5343:               &Apache::loncommon::end_data_table_row()."\n".
 5344:               &Apache::loncommon::end_data_table()."\n".
 5345:               '</form><br />');
 5346:     $r->print($grading_menu_button);
 5347:     return;
 5348: }
 5349: 
 5350: =pod
 5351: 
 5352: =item get_scantron_config
 5353: 
 5354:    Parse and return the scantron configuration line selected as a
 5355:    hash of configuration file fields.
 5356: 
 5357:  Arguments:
 5358:     which - the name of the configuration to parse from the file.
 5359: 
 5360: 
 5361:  Returns:
 5362:             If the named configuration is not in the file, an empty
 5363:             hash is returned.
 5364:     a hash with the fields
 5365:       name         - internal name for the this configuration setup
 5366:       description  - text to display to operator that describes this config
 5367:       CODElocation - if 0 or the string 'none'
 5368:                           - no CODE exists for this config
 5369:                      if -1 || the string 'letter'
 5370:                           - a CODE exists for this config and is
 5371:                             a string of letters
 5372:                      Unsupported value (but planned for future support)
 5373:                           if a positive integer
 5374:                                - The CODE exists as the first n items from
 5375:                                  the question section of the form
 5376:                           if the string 'number'
 5377:                                - The CODE exists for this config and is
 5378:                                  a string of numbers
 5379:       CODEstart   - (only matter if a CODE exists) column in the line where
 5380:                      the CODE starts
 5381:       CODElength  - length of the CODE
 5382:       IDstart     - column where the student/employee ID starts
 5383:       IDlength    - length of the student/employee ID info
 5384:       Qstart      - column where the information from the bubbled
 5385:                     'questions' start
 5386:       Qlength     - number of columns comprising a single bubble line from
 5387:                     the sheet. (usually either 1 or 10)
 5388:       Qon         - either a single character representing the character used
 5389:                     to signal a bubble was chosen in the positional setup, or
 5390:                     the string 'letter' if the letter of the chosen bubble is
 5391:                     in the final, or 'number' if a number representing the
 5392:                     chosen bubble is in the file (1->A 0->J)
 5393:       Qoff        - the character used to represent that a bubble was
 5394:                     left blank
 5395:       PaperID     - if the scanning process generates a unique number for each
 5396:                     sheet scanned the column that this ID number starts in
 5397:       PaperIDlength - number of columns that comprise the unique ID number
 5398:                       for the sheet of paper
 5399:       FirstName   - column that the first name starts in
 5400:       FirstNameLength - number of columns that the first name spans
 5401:  
 5402:       LastName    - column that the last name starts in
 5403:       LastNameLength - number of columns that the last name spans
 5404: 
 5405: =cut
 5406: 
 5407: sub get_scantron_config {
 5408:     my ($which) = @_;
 5409:     my @lines = &get_scantronformat_file();
 5410:     my %config;
 5411:     #FIXME probably should move to XML it has already gotten a bit much now
 5412:     foreach my $line (@lines) {
 5413: 	my ($name,$descrip)=split(/:/,$line);
 5414: 	if ($name ne $which ) { next; }
 5415: 	chomp($line);
 5416: 	my @config=split(/:/,$line);
 5417: 	$config{'name'}=$config[0];
 5418: 	$config{'description'}=$config[1];
 5419: 	$config{'CODElocation'}=$config[2];
 5420: 	$config{'CODEstart'}=$config[3];
 5421: 	$config{'CODElength'}=$config[4];
 5422: 	$config{'IDstart'}=$config[5];
 5423: 	$config{'IDlength'}=$config[6];
 5424: 	$config{'Qstart'}=$config[7];
 5425:  	$config{'Qlength'}=$config[8];
 5426: 	$config{'Qoff'}=$config[9];
 5427: 	$config{'Qon'}=$config[10];
 5428: 	$config{'PaperID'}=$config[11];
 5429: 	$config{'PaperIDlength'}=$config[12];
 5430: 	$config{'FirstName'}=$config[13];
 5431: 	$config{'FirstNamelength'}=$config[14];
 5432: 	$config{'LastName'}=$config[15];
 5433: 	$config{'LastNamelength'}=$config[16];
 5434: 	last;
 5435:     }
 5436:     return %config;
 5437: }
 5438: 
 5439: =pod 
 5440: 
 5441: =item username_to_idmap
 5442: 
 5443:     creates a hash keyed by student/employee ID with values of the corresponding
 5444:     student username:domain.
 5445: 
 5446:   Arguments:
 5447: 
 5448:     $classlist - reference to the class list hash. This is a hash
 5449:                  keyed by student name:domain  whose elements are references
 5450:                  to arrays containing various chunks of information
 5451:                  about the student. (See loncoursedata for more info).
 5452: 
 5453:   Returns
 5454:     %idmap - the constructed hash
 5455: 
 5456: =cut
 5457: 
 5458: sub username_to_idmap {
 5459:     my ($classlist)= @_;
 5460:     my %idmap;
 5461:     foreach my $student (keys(%$classlist)) {
 5462: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5463: 	    $student;
 5464:     }
 5465:     return %idmap;
 5466: }
 5467: 
 5468: =pod
 5469: 
 5470: =item scantron_fixup_scanline
 5471: 
 5472:    Process a requested correction to a scanline.
 5473: 
 5474:   Arguments:
 5475:     $scantron_config   - hash from &get_scantron_config()
 5476:     $scan_data         - hash of correction information 
 5477:                           (see &scantron_getfile())
 5478:     $line              - existing scanline
 5479:     $whichline         - line number of the passed in scanline
 5480:     $field             - type of change to process 
 5481:                          (either 
 5482:                           'ID'     -> correct the student/employee ID
 5483:                           'CODE'   -> correct the CODE
 5484:                           'answer' -> fixup the submitted answers)
 5485:     
 5486:    $args               - hash of additional info,
 5487:                           - 'ID' 
 5488:                                'newid' -> studentID to use in replacement
 5489:                                           of existing one
 5490:                           - 'CODE' 
 5491:                                'CODE_ignore_dup' - set to true if duplicates
 5492:                                                    should be ignored.
 5493: 	                       'CODE' - is new code or 'use_unfound'
 5494:                                         if the existing unfound code should
 5495:                                         be used as is
 5496:                           - 'answer'
 5497:                                'response' - new answer or 'none' if blank
 5498:                                'question' - the bubble line to change
 5499:                                'questionnum' - the question identifier,
 5500:                                                may include subquestion. 
 5501: 
 5502:   Returns:
 5503:     $line - the modified scanline
 5504: 
 5505:   Side effects: 
 5506:     $scan_data - may be updated
 5507: 
 5508: =cut
 5509: 
 5510: 
 5511: sub scantron_fixup_scanline {
 5512:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5513:     if ($field eq 'ID') {
 5514: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5515: 	    return ($line,1,'New value too large');
 5516: 	}
 5517: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5518: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5519: 				     $args->{'newid'});
 5520: 	}
 5521: 	substr($line,$$scantron_config{'IDstart'}-1,
 5522: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5523: 	if ($args->{'newid'}=~/^\s*$/) {
 5524: 	    &scan_data($scan_data,"$whichline.user",
 5525: 		       $args->{'username'}.':'.$args->{'domain'});
 5526: 	}
 5527:     } elsif ($field eq 'CODE') {
 5528: 	if ($args->{'CODE_ignore_dup'}) {
 5529: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5530: 	}
 5531: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5532: 	if ($args->{'CODE'} ne 'use_unfound') {
 5533: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5534: 		return ($line,1,'New CODE value too large');
 5535: 	    }
 5536: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5537: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5538: 	    }
 5539: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5540: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5541: 	}
 5542:     } elsif ($field eq 'answer') {
 5543: 	my $length=$scantron_config->{'Qlength'};
 5544: 	my $off=$scantron_config->{'Qoff'};
 5545: 	my $on=$scantron_config->{'Qon'};
 5546: 	my $answer=${off}x$length;
 5547: 	if ($args->{'response'} eq 'none') {
 5548: 	    &scan_data($scan_data,
 5549: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5550: 	} else {
 5551: 	    if ($on eq 'letter') {
 5552: 		my @alphabet=('A'..'Z');
 5553: 		$answer=$alphabet[$args->{'response'}];
 5554: 	    } elsif ($on eq 'number') {
 5555: 		$answer=$args->{'response'}+1;
 5556: 		if ($answer == 10) { $answer = '0'; }
 5557: 	    } else {
 5558: 		substr($answer,$args->{'response'},1)=$on;
 5559: 	    }
 5560: 	    &scan_data($scan_data,
 5561: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5562: 	}
 5563: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5564: 	substr($line,$where-1,$length)=$answer;
 5565:     }
 5566:     return $line;
 5567: }
 5568: 
 5569: =pod
 5570: 
 5571: =item scan_data
 5572: 
 5573:     Edit or look up  an item in the scan_data hash.
 5574: 
 5575:   Arguments:
 5576:     $scan_data  - The hash (see scantron_getfile)
 5577:     $key        - shorthand of the key to edit (actual key is
 5578:                   scantronfilename_key).
 5579:     $data        - New value of the hash entry.
 5580:     $delete      - If true, the entry is removed from the hash.
 5581: 
 5582:   Returns:
 5583:     The new value of the hash table field (undefined if deleted).
 5584: 
 5585: =cut
 5586: 
 5587: 
 5588: sub scan_data {
 5589:     my ($scan_data,$key,$value,$delete)=@_;
 5590:     my $filename=$env{'form.scantron_selectfile'};
 5591:     if (defined($value)) {
 5592: 	$scan_data->{$filename.'_'.$key} = $value;
 5593:     }
 5594:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5595:     return $scan_data->{$filename.'_'.$key};
 5596: }
 5597: 
 5598: # ----- These first few routines are general use routines.----
 5599: 
 5600: # Return the number of occurences of a pattern in a string.
 5601: 
 5602: sub occurence_count {
 5603:     my ($string, $pattern) = @_;
 5604: 
 5605:     my @matches = ($string =~ /$pattern/g);
 5606: 
 5607:     return scalar(@matches);
 5608: }
 5609: 
 5610: 
 5611: # Take a string known to have digits and convert all the
 5612: # digits into letters in the range J,A..I.
 5613: 
 5614: sub digits_to_letters {
 5615:     my ($input) = @_;
 5616: 
 5617:     my @alphabet = ('J', 'A'..'I');
 5618: 
 5619:     my @input    = split(//, $input);
 5620:     my $output ='';
 5621:     for (my $i = 0; $i < scalar(@input); $i++) {
 5622: 	if ($input[$i] =~ /\d/) {
 5623: 	    $output .= $alphabet[$input[$i]];
 5624: 	} else {
 5625: 	    $output .= $input[$i];
 5626: 	}
 5627:     }
 5628:     return $output;
 5629: }
 5630: 
 5631: =pod 
 5632: 
 5633: =item scantron_parse_scanline
 5634: 
 5635:   Decodes a scanline from the selected scantron file
 5636: 
 5637:  Arguments:
 5638:     line             - The text of the scantron file line to process
 5639:     whichline        - Line number
 5640:     scantron_config  - Hash describing the format of the scantron lines.
 5641:     scan_data        - Hash of extra information about the scanline
 5642:                        (see scantron_getfile for more information)
 5643:     just_header      - True if should not process question answers but only
 5644:                        the stuff to the left of the answers.
 5645:  Returns:
 5646:    Hash containing the result of parsing the scanline
 5647: 
 5648:    Keys are all proceeded by the string 'scantron.'
 5649: 
 5650:        CODE    - the CODE in use for this scanline
 5651:        useCODE - 1 if the CODE is invalid but it usage has been forced
 5652:                  by the operator
 5653:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 5654:                             CODEs were selected, but the usage has been
 5655:                             forced by the operator
 5656:        ID  - student/employee ID
 5657:        PaperID - if used, the ID number printed on the sheet when the 
 5658:                  paper was scanned
 5659:        FirstName - first name from the sheet
 5660:        LastName  - last name from the sheet
 5661: 
 5662:      if just_header was not true these key may also exist
 5663: 
 5664:        missingerror - a list of bubble ranges that are considered to be answers
 5665:                       to a single question that don't have any bubbles filled in.
 5666:                       Of the form questionnumber:firstbubblenumber:count.
 5667:        doubleerror  - a list of bubble ranges that are considered to be answers
 5668:                       to a single question that have more than one bubble filled in.
 5669:                       Of the form questionnumber::firstbubblenumber:count
 5670:    
 5671:                 In the above, count is the number of bubble responses in the
 5672:                 input line needed to represent the possible answers to the question.
 5673:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 5674:                 per line would have count = 2.
 5675: 
 5676:        maxquest     - the number of the last bubble line that was parsed
 5677: 
 5678:        (<number> starts at 1)
 5679:        <number>.answer - zero or more letters representing the selected
 5680:                          letters from the scanline for the bubble line 
 5681:                          <number>.
 5682:                          if blank there was either no bubble or there where
 5683:                          multiple bubbles, (consult the keys missingerror and
 5684:                          doubleerror if this is an error condition)
 5685: 
 5686: =cut
 5687: 
 5688: sub scantron_parse_scanline {
 5689:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
 5690: 
 5691:     my %record;
 5692:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 5693:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 5694:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
 5695:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 5696: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 5697: 	if ($$scantron_config{'CODElocation'} < 0 ||
 5698: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 5699: 	    $$scantron_config{'CODElocation'} eq 'number') {
 5700: 	    $record{'scantron.CODE'}=substr($data,
 5701: 					    $$scantron_config{'CODEstart'}-1,
 5702: 					    $$scantron_config{'CODElength'});
 5703: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 5704: 		$record{'scantron.useCODE'}=1;
 5705: 	    }
 5706: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 5707: 		$record{'scantron.CODE_ignore_dup'}=1;
 5708: 	    }
 5709: 	} else {
 5710: 	    #FIXME interpret first N questions
 5711: 	}
 5712:     }
 5713:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 5714: 				  $$scantron_config{'IDlength'});
 5715:     $record{'scantron.PaperID'}=
 5716: 	substr($data,$$scantron_config{'PaperID'}-1,
 5717: 	       $$scantron_config{'PaperIDlength'});
 5718:     $record{'scantron.FirstName'}=
 5719: 	substr($data,$$scantron_config{'FirstName'}-1,
 5720: 	       $$scantron_config{'FirstNamelength'});
 5721:     $record{'scantron.LastName'}=
 5722: 	substr($data,$$scantron_config{'LastName'}-1,
 5723: 	       $$scantron_config{'LastNamelength'});
 5724:     if ($just_header) { return \%record; }
 5725: 
 5726:     my @alphabet=('A'..'Z');
 5727:     my $questnum=0;
 5728:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 5729: 
 5730:     chomp($questions);		# Get rid of any trailing \n.
 5731:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 5732:     while (length($questions)) {
 5733: 	my $answers_needed = $bubble_lines_per_response{$questnum};
 5734:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 5735:                              || 1;
 5736:         $questnum++;
 5737:         my $quest_id = $questnum;
 5738:         my $currentquest = substr($questions,0,$answer_length);
 5739:         $questions       = substr($questions,$answer_length);
 5740:         if (length($currentquest) < $answer_length) { next; }
 5741: 
 5742:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
 5743:             my $subquestnum = 1;
 5744:             my $subquestions = $currentquest;
 5745:             my @subanswers_needed = 
 5746:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
 5747:             foreach my $subans (@subanswers_needed) {
 5748:                 my $subans_length =
 5749:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 5750:                 my $currsubquest = substr($subquestions,0,$subans_length);
 5751:                 $subquestions   = substr($subquestions,$subans_length);
 5752:                 $quest_id = "$questnum.$subquestnum";
 5753:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 5754:                     ($$scantron_config{'Qon'} eq 'number')) {
 5755:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 5756:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 5757:                         \@alphabet,\%record,$scantron_config,$scan_data);
 5758:                 } else {
 5759:                     $ansnum = &scantron_validator_positional($ansnum,
 5760:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
 5761:                 }
 5762:                 $subquestnum ++;
 5763:             }
 5764:         } else {
 5765:             if (($$scantron_config{'Qon'} eq 'letter') ||
 5766:                 ($$scantron_config{'Qon'} eq 'number')) {
 5767:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 5768:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5769:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5770:             } else {
 5771:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 5772:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5773:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5774:             }
 5775:         }
 5776:     }
 5777:     $record{'scantron.maxquest'}=$questnum;
 5778:     return \%record;
 5779: }
 5780: 
 5781: sub scantron_validator_lettnum {
 5782:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 5783:         $alphabet,$record,$scantron_config,$scan_data) = @_;
 5784: 
 5785:     # Qon 'letter' implies for each slot in currquest we have:
 5786:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 5787:     #    about anything else (esp. a value of Qoff) for missing
 5788:     #    bubbles.
 5789:     #
 5790:     # Qon 'number' implies each slot gives a digit that indexes the
 5791:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 5792:     #    and * or ? for double bubbles on a single line.
 5793:     #
 5794: 
 5795:     my $matchon;
 5796:     if ($$scantron_config{'Qon'} eq 'letter') {
 5797:         $matchon = '[A-Z]';
 5798:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 5799:         $matchon = '\d';
 5800:     }
 5801:     my $occurrences = 0;
 5802:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5803:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5804:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5805:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5806:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5807:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5808:         my @singlelines = split('',$currquest);
 5809:         foreach my $entry (@singlelines) {
 5810:             $occurrences = &occurence_count($entry,$matchon);
 5811:             if ($occurrences > 1) {
 5812:                 last;
 5813:             }
 5814:         } 
 5815:     } else {
 5816:         $occurrences = &occurence_count($currquest,$matchon); 
 5817:     }
 5818:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 5819:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5820:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5821:             my $bubble = substr($currquest,$ans,1);
 5822:             if ($bubble =~ /$matchon/ ) {
 5823:                 if ($$scantron_config{'Qon'} eq 'number') {
 5824:                     if ($bubble == 0) {
 5825:                         $bubble = 10; 
 5826:                     }
 5827:                     $record->{"scantron.$ansnum.answer"} = 
 5828:                         $alphabet->[$bubble-1];
 5829:                 } else {
 5830:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 5831:                 }
 5832:             } else {
 5833:                 $record->{"scantron.$ansnum.answer"}='';
 5834:             }
 5835:             $ansnum++;
 5836:         }
 5837:     } elsif (!defined($currquest)
 5838:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 5839:             || (&occurence_count($currquest,$matchon) == 0)) {
 5840:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5841:             $record->{"scantron.$ansnum.answer"}='';
 5842:             $ansnum++;
 5843:         }
 5844:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5845:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 5846:         }
 5847:     } else {
 5848:         if ($$scantron_config{'Qon'} eq 'number') {
 5849:             $currquest = &digits_to_letters($currquest);            
 5850:         }
 5851:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5852:             my $bubble = substr($currquest,$ans,1);
 5853:             $record->{"scantron.$ansnum.answer"} = $bubble;
 5854:             $ansnum++;
 5855:         }
 5856:     }
 5857:     return $ansnum;
 5858: }
 5859: 
 5860: sub scantron_validator_positional {
 5861:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 5862:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
 5863: 
 5864:     # Otherwise there's a positional notation;
 5865:     # each bubble line requires Qlength items, and there are filled in
 5866:     # bubbles for each case where there 'Qon' characters.
 5867:     #
 5868: 
 5869:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 5870: 
 5871:     # If the split only gives us one element.. the full length of the
 5872:     # answer string, no bubbles are filled in:
 5873: 
 5874:     if ($answers_needed eq '') {
 5875:         return;
 5876:     }
 5877: 
 5878:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 5879:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5880:             $record->{"scantron.$ansnum.answer"}='';
 5881:             $ansnum++;
 5882:         }
 5883:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5884:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 5885:         }
 5886:     } elsif (scalar(@array) == 2) {
 5887:         my $location = length($array[0]);
 5888:         my $line_num = int($location / $$scantron_config{'Qlength'});
 5889:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 5890:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5891:             if ($ans eq $line_num) {
 5892:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 5893:             } else {
 5894:                 $record->{"scantron.$ansnum.answer"} = ' ';
 5895:             }
 5896:             $ansnum++;
 5897:          }
 5898:     } else {
 5899:         #  If there's more than one instance of a bubble character
 5900:         #  That's a double bubble; with positional notation we can
 5901:         #  record all the bubbles filled in as well as the
 5902:         #  fact this response consists of multiple bubbles.
 5903:         #
 5904:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5905:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5906:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5907:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5908:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5909:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5910:             my $doubleerror = 0;
 5911:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 5912:                    (!$doubleerror)) {
 5913:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 5914:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 5915:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 5916:                if (length(@currarray) > 2) {
 5917:                    $doubleerror = 1;
 5918:                } 
 5919:             }
 5920:             if ($doubleerror) {
 5921:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5922:             }
 5923:         } else {
 5924:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5925:         }
 5926:         my $item = $ansnum;
 5927:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5928:             $record->{"scantron.$item.answer"} = '';
 5929:             $item ++;
 5930:         }
 5931: 
 5932:         my @ans=@array;
 5933:         my $i=0;
 5934:         my $increment = 0;
 5935:         while ($#ans) {
 5936:             $i+=length($ans[0]) + $increment;
 5937:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 5938:             my $bubble = $i%$$scantron_config{'Qlength'};
 5939:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 5940:             shift(@ans);
 5941:             $increment = 1;
 5942:         }
 5943:         $ansnum += $answers_needed;
 5944:     }
 5945:     return $ansnum;
 5946: }
 5947: 
 5948: =pod
 5949: 
 5950: =item scantron_add_delay
 5951: 
 5952:    Adds an error message that occurred during the grading phase to a
 5953:    queue of messages to be shown after grading pass is complete
 5954: 
 5955:  Arguments:
 5956:    $delayqueue  - arrary ref of hash ref of error messages
 5957:    $scanline    - the scanline that caused the error
 5958:    $errormesage - the error message
 5959:    $errorcode   - a numeric code for the error
 5960: 
 5961:  Side Effects:
 5962:    updates the $delayqueue to have a new hash ref of the error
 5963: 
 5964: =cut
 5965: 
 5966: sub scantron_add_delay {
 5967:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 5968:     push(@$delayqueue,
 5969: 	 {'line' => $scanline, 'emsg' => $errormessage,
 5970: 	  'ecode' => $errorcode }
 5971: 	 );
 5972: }
 5973: 
 5974: =pod
 5975: 
 5976: =item scantron_find_student
 5977: 
 5978:    Finds the username for the current scanline
 5979: 
 5980:   Arguments:
 5981:    $scantron_record - hash result from scantron_parse_scanline
 5982:    $scan_data       - hash of correction information 
 5983:                       (see &scantron_getfile() form more information)
 5984:    $idmap           - hash from &username_to_idmap()
 5985:    $line            - number of current scanline
 5986:  
 5987:   Returns:
 5988:    Either 'username:domain' or undef if unknown
 5989: 
 5990: =cut
 5991: 
 5992: sub scantron_find_student {
 5993:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 5994:     my $scanID=$$scantron_record{'scantron.ID'};
 5995:     if ($scanID =~ /^\s*$/) {
 5996:  	return &scan_data($scan_data,"$line.user");
 5997:     }
 5998:     foreach my $id (keys(%$idmap)) {
 5999:  	if (lc($id) eq lc($scanID)) {
 6000:  	    return $$idmap{$id};
 6001:  	}
 6002:     }
 6003:     return undef;
 6004: }
 6005: 
 6006: =pod
 6007: 
 6008: =item scantron_filter
 6009: 
 6010:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 6011:    hidden resources was selected
 6012: 
 6013: =cut
 6014: 
 6015: sub scantron_filter {
 6016:     my ($curres)=@_;
 6017: 
 6018:     if (ref($curres) && $curres->is_problem()) {
 6019: 	# if the user has asked to not have either hidden
 6020: 	# or 'randomout' controlled resources to be graded
 6021: 	# don't include them
 6022: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6023: 	    && $curres->randomout) {
 6024: 	    return 0;
 6025: 	}
 6026: 	return 1;
 6027:     }
 6028:     return 0;
 6029: }
 6030: 
 6031: =pod
 6032: 
 6033: =item scantron_process_corrections
 6034: 
 6035:    Gets correction information out of submitted form data and corrects
 6036:    the scanline
 6037: 
 6038: =cut
 6039: 
 6040: sub scantron_process_corrections {
 6041:     my ($r) = @_;
 6042:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6043:     my ($scanlines,$scan_data)=&scantron_getfile();
 6044:     my $classlist=&Apache::loncoursedata::get_classlist();
 6045:     my $which=$env{'form.scantron_line'};
 6046:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 6047:     my ($skip,$err,$errmsg);
 6048:     if ($env{'form.scantron_skip_record'}) {
 6049: 	$skip=1;
 6050:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 6051: 	my $newstudent=$env{'form.scantron_username'}.':'.
 6052: 	    $env{'form.scantron_domain'};
 6053: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 6054: 	($line,$err,$errmsg)=
 6055: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6056: 				     'ID',{'newid'=>$newid,
 6057: 				    'username'=>$env{'form.scantron_username'},
 6058: 				    'domain'=>$env{'form.scantron_domain'}});
 6059:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 6060: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 6061: 	my $newCODE;
 6062: 	my %args;
 6063: 	if      ($resolution eq 'use_unfound') {
 6064: 	    $newCODE='use_unfound';
 6065: 	} elsif ($resolution eq 'use_found') {
 6066: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6067: 	} elsif ($resolution eq 'use_typed') {
 6068: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6069: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6070: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6071: 	}
 6072: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6073: 	    $args{'CODE_ignore_dup'}=1;
 6074: 	}
 6075: 	$args{'CODE'}=$newCODE;
 6076: 	($line,$err,$errmsg)=
 6077: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6078: 				     'CODE',\%args);
 6079:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6080: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6081: 	    ($line,$err,$errmsg)=
 6082: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6083: 					 $which,'answer',
 6084: 					 { 'question'=>$question,
 6085: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6086:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6087: 	    if ($err) { last; }
 6088: 	}
 6089:     }
 6090:     if ($err) {
 6091: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
 6092:     } else {
 6093: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 6094: 	&scantron_putfile($scanlines,$scan_data);
 6095:     }
 6096: }
 6097: 
 6098: =pod
 6099: 
 6100: =item reset_skipping_status
 6101: 
 6102:    Forgets the current set of remember skipped scanlines (and thus
 6103:    reverts back to considering all lines in the
 6104:    scantron_skipped_<filename> file)
 6105: 
 6106: =cut
 6107: 
 6108: sub reset_skipping_status {
 6109:     my ($scanlines,$scan_data)=&scantron_getfile();
 6110:     &scan_data($scan_data,'remember_skipping',undef,1);
 6111:     &scantron_putfile(undef,$scan_data);
 6112: }
 6113: 
 6114: =pod
 6115: 
 6116: =item start_skipping
 6117: 
 6118:    Marks a scanline to be skipped. 
 6119: 
 6120: =cut
 6121: 
 6122: sub start_skipping {
 6123:     my ($scan_data,$i)=@_;
 6124:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6125:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6126: 	$remembered{$i}=2;
 6127:     } else {
 6128: 	$remembered{$i}=1;
 6129:     }
 6130:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6131: }
 6132: 
 6133: =pod
 6134: 
 6135: =item should_be_skipped
 6136: 
 6137:    Checks whether a scanline should be skipped.
 6138: 
 6139: =cut
 6140: 
 6141: sub should_be_skipped {
 6142:     my ($scanlines,$scan_data,$i)=@_;
 6143:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6144: 	# not redoing old skips
 6145: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6146: 	return 0;
 6147:     }
 6148:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6149: 
 6150:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6151: 	return 0;
 6152:     }
 6153:     return 1;
 6154: }
 6155: 
 6156: =pod
 6157: 
 6158: =item remember_current_skipped
 6159: 
 6160:    Discovers what scanlines are in the scantron_skipped_<filename>
 6161:    file and remembers them into scan_data for later use.
 6162: 
 6163: =cut
 6164: 
 6165: sub remember_current_skipped {
 6166:     my ($scanlines,$scan_data)=&scantron_getfile();
 6167:     my %to_remember;
 6168:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6169: 	if ($scanlines->{'skipped'}[$i]) {
 6170: 	    $to_remember{$i}=1;
 6171: 	}
 6172:     }
 6173: 
 6174:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6175:     &scantron_putfile(undef,$scan_data);
 6176: }
 6177: 
 6178: =pod
 6179: 
 6180: =item check_for_error
 6181: 
 6182:     Checks if there was an error when attempting to remove a specific
 6183:     scantron_.. bubble sheet data file. Prints out an error if
 6184:     something went wrong.
 6185: 
 6186: =cut
 6187: 
 6188: sub check_for_error {
 6189:     my ($r,$result)=@_;
 6190:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6191: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6192:     }
 6193: }
 6194: 
 6195: =pod
 6196: 
 6197: =item scantron_warning_screen
 6198: 
 6199:    Interstitial screen to make sure the operator has selected the
 6200:    correct options before we start the validation phase.
 6201: 
 6202: =cut
 6203: 
 6204: sub scantron_warning_screen {
 6205:     my ($button_text)=@_;
 6206:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6207:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6208:     my $CODElist;
 6209:     if ($scantron_config{'CODElocation'} &&
 6210: 	$scantron_config{'CODEstart'} &&
 6211: 	$scantron_config{'CODElength'}) {
 6212: 	$CODElist=$env{'form.scantron_CODElist'};
 6213: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
 6214: 	$CODElist=
 6215: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6216: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6217:     }
 6218:     return ('
 6219: <p>
 6220: <span class="LC_warning">
 6221: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
 6222: </p>
 6223: <table>
 6224: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6225: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6226: '.$CODElist.'
 6227: </table>
 6228: <br />
 6229: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
 6230: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
 6231: 
 6232: <br />
 6233: ');
 6234: }
 6235: 
 6236: =pod
 6237: 
 6238: =item scantron_do_warning
 6239: 
 6240:    Check if the operator has picked something for all required
 6241:    fields. Error out if something is missing.
 6242: 
 6243: =cut
 6244: 
 6245: sub scantron_do_warning {
 6246:     my ($r)=@_;
 6247:     my ($symb)=&get_symb($r);
 6248:     if (!$symb) {return '';}
 6249:     my $default_form_data=&defaultFormData($symb);
 6250:     $r->print(&scantron_form_start().$default_form_data);
 6251:     if ( $env{'form.selectpage'} eq '' ||
 6252: 	 $env{'form.scantron_selectfile'} eq '' ||
 6253: 	 $env{'form.scantron_format'} eq '' ) {
 6254: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
 6255: 	if ( $env{'form.selectpage'} eq '') {
 6256: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6257: 	} 
 6258: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6259: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a file that contains the student\'s response data.').'</span></p>');
 6260: 	} 
 6261: 	if ( $env{'form.scantron_format'} eq '') {
 6262: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a the format of the student\'s response data.').'</span></p>');
 6263: 	} 
 6264:     } else {
 6265: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
 6266: 	$r->print('
 6267: '.$warning.'
 6268: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6269: <input type="hidden" name="command" value="scantron_validate" />
 6270: ');
 6271:     }
 6272:     $r->print("</form><br />".&show_grading_menu_form($symb));
 6273:     return '';
 6274: }
 6275: 
 6276: =pod
 6277: 
 6278: =item scantron_form_start
 6279: 
 6280:     html hidden input for remembering all selected grading options
 6281: 
 6282: =cut
 6283: 
 6284: sub scantron_form_start {
 6285:     my ($max_bubble)=@_;
 6286:     my $result= <<SCANTRONFORM;
 6287: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6288:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6289:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6290:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6291:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6292:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6293:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6294:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6295:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6296:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6297: SCANTRONFORM
 6298: 
 6299:   my $line = 0;
 6300:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6301:        my $chunk =
 6302: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6303:        $chunk .=
 6304: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6305:        $chunk .= 
 6306:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6307:        $chunk .=
 6308:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6309:        $result .= $chunk;
 6310:        $line++;
 6311:    }
 6312:     return $result;
 6313: }
 6314: 
 6315: =pod
 6316: 
 6317: =item scantron_validate_file
 6318: 
 6319:     Dispatch routine for doing validation of a bubble sheet data file.
 6320: 
 6321:     Also processes any necessary information resets that need to
 6322:     occur before validation begins (ignore previous corrections,
 6323:     restarting the skipped records processing)
 6324: 
 6325: =cut
 6326: 
 6327: sub scantron_validate_file {
 6328:     my ($r) = @_;
 6329:     my ($symb)=&get_symb($r);
 6330:     if (!$symb) {return '';}
 6331:     my $default_form_data=&defaultFormData($symb);
 6332:     
 6333:     # do the detection of only doing skipped records first befroe we delete
 6334:     # them when doing the corrections reset
 6335:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6336: 	&reset_skipping_status();
 6337:     }
 6338:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6339: 	&remember_current_skipped();
 6340: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6341:     }
 6342: 
 6343:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6344: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6345: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6346: 	&check_for_error($r,&scantron_remove_scan_data());
 6347: 	$env{'form.scantron_options_ignore'}='done';
 6348:     }
 6349: 
 6350:     if ($env{'form.scantron_corrections'}) {
 6351: 	&scantron_process_corrections($r);
 6352:     }
 6353:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6354:     #get the student pick code ready
 6355:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6356:     my $nav_error;
 6357:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
 6358:     if ($nav_error) {
 6359:         $r->print(&navmap_errormsg());
 6360:         return '';
 6361:     }
 6362:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6363:     $r->print($result);
 6364:     
 6365:     my @validate_phases=( 'sequence',
 6366: 			  'ID',
 6367: 			  'CODE',
 6368: 			  'doublebubble',
 6369: 			  'missingbubbles');
 6370:     if (!$env{'form.validatepass'}) {
 6371: 	$env{'form.validatepass'} = 0;
 6372:     }
 6373:     my $currentphase=$env{'form.validatepass'};
 6374: 
 6375: 
 6376:     my $stop=0;
 6377:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6378: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6379: 	$r->rflush();
 6380: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6381: 	{
 6382: 	    no strict 'refs';
 6383: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6384: 	}
 6385:     }
 6386:     if (!$stop) {
 6387: 	my $warning=&scantron_warning_screen('Start Grading');
 6388: 	$r->print(&mt('Validation process complete.').'<br />'.
 6389:                   $warning.
 6390:                   &mt('Perform verification for each student after storage of submissions?').
 6391:                   '&nbsp;<span class="LC_nobreak"><label>'.
 6392:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 6393:                   ('&nbsp;'x3).'<label>'.
 6394:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 6395:                   '</label></span><br />'.
 6396:                   &mt('Grading will take longer if you use verification.').'<br />'.
 6397:                   &mt("Alternatively, the 'Review bubblesheet data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
 6398:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 6399:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 6400:     } else {
 6401: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6402: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6403:     }
 6404:     if ($stop) {
 6405: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6406: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 6407: 	    $r->print(' '.&mt('this error').' <br />');
 6408: 
 6409: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
 6410: 	} else {
 6411:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6412: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 6413:             } else {
 6414:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 6415:             }
 6416: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6417: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6418: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6419: 	}
 6420:     }
 6421:     $r->print(" </form><br />".&show_grading_menu_form($symb));
 6422:     return '';
 6423: }
 6424: 
 6425: 
 6426: =pod
 6427: 
 6428: =item scantron_remove_file
 6429: 
 6430:    Removes the requested bubble sheet data file, makes sure that
 6431:    scantron_original_<filename> is never removed
 6432: 
 6433: 
 6434: =cut
 6435: 
 6436: sub scantron_remove_file {
 6437:     my ($which)=@_;
 6438:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6439:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6440:     my $file='scantron_';
 6441:     if ($which eq 'corrected' || $which eq 'skipped') {
 6442: 	$file.=$which.'_';
 6443:     } else {
 6444: 	return 'refused';
 6445:     }
 6446:     $file.=$env{'form.scantron_selectfile'};
 6447:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6448: }
 6449: 
 6450: 
 6451: =pod
 6452: 
 6453: =item scantron_remove_scan_data
 6454: 
 6455:    Removes all scan_data correction for the requested bubble sheet
 6456:    data file.  (In the case that both the are doing skipped records we need
 6457:    to remember the old skipped lines for the time being so that element
 6458:    persists for a while.)
 6459: 
 6460: =cut
 6461: 
 6462: sub scantron_remove_scan_data {
 6463:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6464:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6465:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6466:     my @todelete;
 6467:     my $filename=$env{'form.scantron_selectfile'};
 6468:     foreach my $key (@keys) {
 6469: 	if ($key=~/^\Q$filename\E_/) {
 6470: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6471: 		$key=~/remember_skipping/) {
 6472: 		next;
 6473: 	    }
 6474: 	    push(@todelete,$key);
 6475: 	}
 6476:     }
 6477:     my $result;
 6478:     if (@todelete) {
 6479: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6480: 				       \@todelete,$cdom,$cname);
 6481:     } else {
 6482: 	$result = 'ok';
 6483:     }
 6484:     return $result;
 6485: }
 6486: 
 6487: 
 6488: =pod
 6489: 
 6490: =item scantron_getfile
 6491: 
 6492:     Fetches the requested bubble sheet data file (all 3 versions), and
 6493:     the scan_data hash
 6494:   
 6495:   Arguments:
 6496:     None
 6497: 
 6498:   Returns:
 6499:     2 hash references
 6500: 
 6501:      - first one has 
 6502:          orig      -
 6503:          corrected -
 6504:          skipped   -  each of which points to an array ref of the specified
 6505:                       file broken up into individual lines
 6506:          count     - number of scanlines
 6507:  
 6508:      - second is the scan_data hash possible keys are
 6509:        ($number refers to scanline numbered $number and thus the key affects
 6510:         only that scanline
 6511:         $bubline refers to the specific bubble line element and the aspects
 6512:         refers to that specific bubble line element)
 6513: 
 6514:        $number.user - username:domain to use
 6515:        $number.CODE_ignore_dup 
 6516:                     - ignore the duplicate CODE error 
 6517:        $number.useCODE
 6518:                     - use the CODE in the scanline as is
 6519:        $number.no_bubble.$bubline
 6520:                     - it is valid that there is no bubbled in bubble
 6521:                       at $number $bubline
 6522:        remember_skipping
 6523:                     - a frozen hash containing keys of $number and values
 6524:                       of either 
 6525:                         1 - we are on a 'do skipped records pass' and plan
 6526:                             on processing this line
 6527:                         2 - we are on a 'do skipped records pass' and this
 6528:                             scanline has been marked to skip yet again
 6529: 
 6530: =cut
 6531: 
 6532: sub scantron_getfile {
 6533:     #FIXME really would prefer a scantron directory
 6534:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6535:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6536:     my $lines;
 6537:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6538: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 6539:     my %scanlines;
 6540:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 6541:     my $temp=$scanlines{'orig'};
 6542:     $scanlines{'count'}=$#$temp;
 6543: 
 6544:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6545: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 6546:     if ($lines eq '-1') {
 6547: 	$scanlines{'corrected'}=[];
 6548:     } else {
 6549: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 6550:     }
 6551:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6552: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 6553:     if ($lines eq '-1') {
 6554: 	$scanlines{'skipped'}=[];
 6555:     } else {
 6556: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 6557:     }
 6558:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 6559:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 6560:     my %scan_data = @tmp;
 6561:     return (\%scanlines,\%scan_data);
 6562: }
 6563: 
 6564: =pod
 6565: 
 6566: =item lonnet_putfile
 6567: 
 6568:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 6569: 
 6570:  Arguments:
 6571:    $contents - data to store
 6572:    $filename - filename to store $contents into
 6573: 
 6574:  Returns:
 6575:    result value from &Apache::lonnet::finishuserfileupload
 6576: 
 6577: =cut
 6578: 
 6579: sub lonnet_putfile {
 6580:     my ($contents,$filename)=@_;
 6581:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6582:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6583:     $env{'form.sillywaytopassafilearound'}=$contents;
 6584:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 6585: 
 6586: }
 6587: 
 6588: =pod
 6589: 
 6590: =item scantron_putfile
 6591: 
 6592:     Stores the current version of the bubble sheet data files, and the
 6593:     scan_data hash. (Does not modify the original version only the
 6594:     corrected and skipped versions.
 6595: 
 6596:  Arguments:
 6597:     $scanlines - hash ref that looks like the first return value from
 6598:                  &scantron_getfile()
 6599:     $scan_data - hash ref that looks like the second return value from
 6600:                  &scantron_getfile()
 6601: 
 6602: =cut
 6603: 
 6604: sub scantron_putfile {
 6605:     my ($scanlines,$scan_data) = @_;
 6606:     #FIXME really would prefer a scantron directory
 6607:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6608:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6609:     if ($scanlines) {
 6610: 	my $prefix='scantron_';
 6611: # no need to update orig, shouldn't change
 6612: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 6613: #		    $env{'form.scantron_selectfile'});
 6614: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 6615: 			$prefix.'corrected_'.
 6616: 			$env{'form.scantron_selectfile'});
 6617: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 6618: 			$prefix.'skipped_'.
 6619: 			$env{'form.scantron_selectfile'});
 6620:     }
 6621:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 6622: }
 6623: 
 6624: =pod
 6625: 
 6626: =item scantron_get_line
 6627: 
 6628:    Returns the correct version of the scanline
 6629: 
 6630:  Arguments:
 6631:     $scanlines - hash ref that looks like the first return value from
 6632:                  &scantron_getfile()
 6633:     $scan_data - hash ref that looks like the second return value from
 6634:                  &scantron_getfile()
 6635:     $i         - number of the requested line (starts at 0)
 6636: 
 6637:  Returns:
 6638:    A scanline, (either the original or the corrected one if it
 6639:    exists), or undef if the requested scanline should be
 6640:    skipped. (Either because it's an skipped scanline, or it's an
 6641:    unskipped scanline and we are not doing a 'do skipped scanlines'
 6642:    pass.
 6643: 
 6644: =cut
 6645: 
 6646: sub scantron_get_line {
 6647:     my ($scanlines,$scan_data,$i)=@_;
 6648:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 6649:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 6650:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 6651:     return $scanlines->{'orig'}[$i]; 
 6652: }
 6653: 
 6654: =pod
 6655: 
 6656: =item scantron_todo_count
 6657: 
 6658:     Counts the number of scanlines that need processing.
 6659: 
 6660:  Arguments:
 6661:     $scanlines - hash ref that looks like the first return value from
 6662:                  &scantron_getfile()
 6663:     $scan_data - hash ref that looks like the second return value from
 6664:                  &scantron_getfile()
 6665: 
 6666:  Returns:
 6667:     $count - number of scanlines to process
 6668: 
 6669: =cut
 6670: 
 6671: sub get_todo_count {
 6672:     my ($scanlines,$scan_data)=@_;
 6673:     my $count=0;
 6674:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6675: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6676: 	if ($line=~/^[\s\cz]*$/) { next; }
 6677: 	$count++;
 6678:     }
 6679:     return $count;
 6680: }
 6681: 
 6682: =pod
 6683: 
 6684: =item scantron_put_line
 6685: 
 6686:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
 6687:     data file.
 6688: 
 6689:  Arguments:
 6690:     $scanlines - hash ref that looks like the first return value from
 6691:                  &scantron_getfile()
 6692:     $scan_data - hash ref that looks like the second return value from
 6693:                  &scantron_getfile()
 6694:     $i         - line number to update
 6695:     $newline   - contents of the updated scanline
 6696:     $skip      - if true make the line for skipping and update the
 6697:                  'skipped' file
 6698: 
 6699: =cut
 6700: 
 6701: sub scantron_put_line {
 6702:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 6703:     if ($skip) {
 6704: 	$scanlines->{'skipped'}[$i]=$newline;
 6705: 	&start_skipping($scan_data,$i);
 6706: 	return;
 6707:     }
 6708:     $scanlines->{'corrected'}[$i]=$newline;
 6709: }
 6710: 
 6711: =pod
 6712: 
 6713: =item scantron_clear_skip
 6714: 
 6715:    Remove a line from the 'skipped' file
 6716: 
 6717:  Arguments:
 6718:     $scanlines - hash ref that looks like the first return value from
 6719:                  &scantron_getfile()
 6720:     $scan_data - hash ref that looks like the second return value from
 6721:                  &scantron_getfile()
 6722:     $i         - line number to update
 6723: 
 6724: =cut
 6725: 
 6726: sub scantron_clear_skip {
 6727:     my ($scanlines,$scan_data,$i)=@_;
 6728:     if (exists($scanlines->{'skipped'}[$i])) {
 6729: 	undef($scanlines->{'skipped'}[$i]);
 6730: 	return 1;
 6731:     }
 6732:     return 0;
 6733: }
 6734: 
 6735: =pod
 6736: 
 6737: =item scantron_filter_not_exam
 6738: 
 6739:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 6740:    filter out resources that are not marked as 'exam' mode
 6741: 
 6742: =cut
 6743: 
 6744: sub scantron_filter_not_exam {
 6745:     my ($curres)=@_;
 6746:     
 6747:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 6748: 	# if the user has asked to not have either hidden
 6749: 	# or 'randomout' controlled resources to be graded
 6750: 	# don't include them
 6751: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6752: 	    && $curres->randomout) {
 6753: 	    return 0;
 6754: 	}
 6755: 	return 1;
 6756:     }
 6757:     return 0;
 6758: }
 6759: 
 6760: =pod
 6761: 
 6762: =item scantron_validate_sequence
 6763: 
 6764:     Validates the selected sequence, checking for resource that are
 6765:     not set to exam mode.
 6766: 
 6767: =cut
 6768: 
 6769: sub scantron_validate_sequence {
 6770:     my ($r,$currentphase) = @_;
 6771: 
 6772:     my $navmap=Apache::lonnavmaps::navmap->new();
 6773:     unless (ref($navmap)) {
 6774:         $r->print(&navmap_errormsg());
 6775:         return (1,$currentphase);
 6776:     }
 6777:     my (undef,undef,$sequence)=
 6778: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6779: 
 6780:     my $map=$navmap->getResourceByUrl($sequence);
 6781: 
 6782:     $r->print('<input type="hidden" name="validate_sequence_exam"
 6783:                                     value="ignore" />');
 6784:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 6785: 	my @resources=
 6786: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 6787: 	if (@resources) {
 6788: 	    $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>");
 6789: 	    return (1,$currentphase);
 6790: 	}
 6791:     }
 6792: 
 6793:     return (0,$currentphase+1);
 6794: }
 6795: 
 6796: 
 6797: 
 6798: sub scantron_validate_ID {
 6799:     my ($r,$currentphase) = @_;
 6800:     
 6801:     #get student info
 6802:     my $classlist=&Apache::loncoursedata::get_classlist();
 6803:     my %idmap=&username_to_idmap($classlist);
 6804: 
 6805:     #get scantron line setup
 6806:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6807:     my ($scanlines,$scan_data)=&scantron_getfile();
 6808: 
 6809:     my $nav_error;
 6810:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble_lines.. array.
 6811:     if ($nav_error) {
 6812:         $r->print(&navmap_errormsg());
 6813:         return(1,$currentphase);
 6814:     }
 6815: 
 6816:     my %found=('ids'=>{},'usernames'=>{});
 6817:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6818: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6819: 	if ($line=~/^[\s\cz]*$/) { next; }
 6820: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6821: 						 $scan_data);
 6822: 	my $id=$$scan_record{'scantron.ID'};
 6823: 	my $found;
 6824: 	foreach my $checkid (keys(%idmap)) {
 6825: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 6826: 	}
 6827: 	if ($found) {
 6828: 	    my $username=$idmap{$found};
 6829: 	    if ($found{'ids'}{$found}) {
 6830: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6831: 					 $line,'duplicateID',$found);
 6832: 		return(1,$currentphase);
 6833: 	    } elsif ($found{'usernames'}{$username}) {
 6834: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6835: 					 $line,'duplicateID',$username);
 6836: 		return(1,$currentphase);
 6837: 	    }
 6838: 	    #FIXME store away line we previously saw the ID on to use above
 6839: 	    $found{'ids'}{$found}++;
 6840: 	    $found{'usernames'}{$username}++;
 6841: 	} else {
 6842: 	    if ($id =~ /^\s*$/) {
 6843: 		my $username=&scan_data($scan_data,"$i.user");
 6844: 		if (defined($username) && $found{'usernames'}{$username}) {
 6845: 		    &scantron_get_correction($r,$i,$scan_record,
 6846: 					     \%scantron_config,
 6847: 					     $line,'duplicateID',$username);
 6848: 		    return(1,$currentphase);
 6849: 		} elsif (!defined($username)) {
 6850: 		    &scantron_get_correction($r,$i,$scan_record,
 6851: 					     \%scantron_config,
 6852: 					     $line,'incorrectID');
 6853: 		    return(1,$currentphase);
 6854: 		}
 6855: 		$found{'usernames'}{$username}++;
 6856: 	    } else {
 6857: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6858: 					 $line,'incorrectID');
 6859: 		return(1,$currentphase);
 6860: 	    }
 6861: 	}
 6862:     }
 6863: 
 6864:     return (0,$currentphase+1);
 6865: }
 6866: 
 6867: 
 6868: sub scantron_get_correction {
 6869:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
 6870: #FIXME in the case of a duplicated ID the previous line, probably need
 6871: #to show both the current line and the previous one and allow skipping
 6872: #the previous one or the current one
 6873: 
 6874:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 6875: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6876: 			    " for PaperID <tt>[_1]</tt>",
 6877: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
 6878:     } else {
 6879: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6880: 			    " in scanline [_1] <pre>[_2]</pre>",
 6881: 			    $i,$line)."</p> \n");
 6882:     }
 6883:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
 6884: 			  "The name on the paper is [_2],[_3]",
 6885: 			  $$scan_record{'scantron.ID'},
 6886: 			  $$scan_record{'scantron.LastName'},
 6887: 			  $$scan_record{'scantron.FirstName'})."</p>";
 6888: 
 6889:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 6890:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 6891:                            # Array populated for doublebubble or
 6892:     my @lines_to_correct;  # missingbubble errors to build javascript
 6893:                            # to validate radio button checking   
 6894: 
 6895:     if ($error =~ /ID$/) {
 6896: 	if ($error eq 'incorrectID') {
 6897: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
 6898: 		      "</p>\n");
 6899: 	} elsif ($error eq 'duplicateID') {
 6900: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 6901: 	}
 6902: 	$r->print($message);
 6903: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6904: 	$r->print("\n<ul><li> ");
 6905: 	#FIXME it would be nice if this sent back the user ID and
 6906: 	#could do partial userID matches
 6907: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 6908: 				       'scantron_username','scantron_domain'));
 6909: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 6910: 	$r->print("\n@".
 6911: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 6912: 
 6913: 	$r->print('</li>');
 6914:     } elsif ($error =~ /CODE$/) {
 6915: 	if ($error eq 'incorrectCODE') {
 6916: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 6917: 	} elsif ($error eq 'duplicateCODE') {
 6918: 	    $r->print("<p>".&mt("The encoded CODE has also been used by a previous paper [_1], and CODEs are supposed to be unique.",join(', ',@{$arg}))."</p>\n");
 6919: 	}
 6920: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
 6921: 			    $$scan_record{'scantron.CODE'})."<br />\n");
 6922: 	$r->print($message);
 6923: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6924: 	$r->print("\n<br /> ");
 6925: 	my $i=0;
 6926: 	if ($error eq 'incorrectCODE' 
 6927: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 6928: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 6929: 	    if ($closest > 0) {
 6930: 		foreach my $testcode (@{$closest}) {
 6931: 		    my $checked='';
 6932: 		    if (!$i) { $checked=' checked="checked"'; }
 6933: 		    $r->print("
 6934:    <label>
 6935:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 6936:        ".&mt("Use the similar CODE [_1] instead.",
 6937: 	    "<b><tt>".$testcode."</tt></b>")."
 6938:     </label>
 6939:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 6940: 		    $r->print("\n<br />");
 6941: 		    $i++;
 6942: 		}
 6943: 	    }
 6944: 	}
 6945: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 6946: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 6947: 	    $r->print("
 6948:     <label>
 6949:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 6950:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
 6951: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 6952:     </label>");
 6953: 	    $r->print("\n<br />");
 6954: 	}
 6955: 
 6956: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
 6957: function change_radio(field) {
 6958:     var slct=document.scantronupload.scantron_CODE_resolution;
 6959:     var i;
 6960:     for (i=0;i<slct.length;i++) {
 6961:         if (slct[i].value==field) { slct[i].checked=true; }
 6962:     }
 6963: }
 6964: ENDSCRIPT
 6965: 	my $href="/adm/pickcode?".
 6966: 	   "form=".&escape("scantronupload").
 6967: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 6968: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 6969: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 6970: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 6971: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 6972: 	    $r->print("
 6973:     <label>
 6974:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 6975:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 6976: 	     "<a target='_blank' href='$href'>","</a>")."
 6977:     </label> 
 6978:     ".&mt("Selected CODE is [_1]",'<input readonly="readonly" type="text" size="8" name="scantron_CODE_selectedvalue" onfocus="javascript:change_radio(\'use_found\')" onchange="javascript:change_radio(\'use_found\')" />'));
 6979: 	    $r->print("\n<br />");
 6980: 	}
 6981: 	$r->print("
 6982:     <label>
 6983:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 6984:        ".&mt("Use [_1] as the CODE.",
 6985: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 6986: 	$r->print("\n<br /><br />");
 6987:     } elsif ($error eq 'doublebubble') {
 6988: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 6989: 
 6990: 	# The form field scantron_questions is acutally a list of line numbers.
 6991: 	# represented by this form so:
 6992: 
 6993: 	my $line_list = &questions_to_line_list($arg);
 6994: 
 6995: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6996: 		  $line_list.'" />');
 6997: 	$r->print($message);
 6998: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 6999: 	foreach my $question (@{$arg}) {
 7000: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7001:                                                    $scan_record, $error);
 7002:             push(@lines_to_correct,@linenums);
 7003: 	}
 7004:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7005:     } elsif ($error eq 'missingbubble') {
 7006: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
 7007: 	$r->print($message);
 7008: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 7009: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 7010: 
 7011: 	# The form field scantron_questions is actually a list of line numbers not
 7012: 	# a list of question numbers. Therefore:
 7013: 	#
 7014: 	
 7015: 	my $line_list = &questions_to_line_list($arg);
 7016: 
 7017: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7018: 		  $line_list.'" />');
 7019: 	foreach my $question (@{$arg}) {
 7020: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7021:                                                    $scan_record, $error);
 7022:             push(@lines_to_correct,@linenums);
 7023: 	}
 7024:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7025:     } else {
 7026: 	$r->print("\n<ul>");
 7027:     }
 7028:     $r->print("\n</li></ul>");
 7029: }
 7030: 
 7031: sub verify_bubbles_checked {
 7032:     my (@ansnums) = @_;
 7033:     my $ansnumstr = join('","',@ansnums);
 7034:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 7035:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
 7036: function verify_bubble_radio(form) {
 7037:     var ansnumArray = new Array ("$ansnumstr");
 7038:     var need_bubble_count = 0;
 7039:     for (var i=0; i<ansnumArray.length; i++) {
 7040:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 7041:             var bubble_picked = 0; 
 7042:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 7043:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 7044:                     bubble_picked = 1;
 7045:                 }
 7046:             }
 7047:             if (bubble_picked == 0) {
 7048:                 need_bubble_count ++;
 7049:             }
 7050:         }
 7051:     }
 7052:     if (need_bubble_count) {
 7053:         alert("$warning");
 7054:         return;
 7055:     }
 7056:     form.submit(); 
 7057: }
 7058: ENDSCRIPT
 7059:     return $output;
 7060: }
 7061: 
 7062: =pod
 7063: 
 7064: =item  questions_to_line_list
 7065: 
 7066: Converts a list of questions into a string of comma separated
 7067: line numbers in the answer sheet used by the questions.  This is
 7068: used to fill in the scantron_questions form field.
 7069: 
 7070:   Arguments:
 7071:      questions    - Reference to an array of questions.
 7072: 
 7073: =cut
 7074: 
 7075: 
 7076: sub questions_to_line_list {
 7077:     my ($questions) = @_;
 7078:     my @lines;
 7079: 
 7080:     foreach my $item (@{$questions}) {
 7081:         my $question = $item;
 7082:         my ($first,$count,$last);
 7083:         if ($item =~ /^(\d+)\.(\d+)$/) {
 7084:             $question = $1;
 7085:             my $subquestion = $2;
 7086:             $first = $first_bubble_line{$question-1} + 1;
 7087:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7088:             my $subcount = 1;
 7089:             while ($subcount<$subquestion) {
 7090:                 $first += $subans[$subcount-1];
 7091:                 $subcount ++;
 7092:             }
 7093:             $count = $subans[$subquestion-1];
 7094:         } else {
 7095: 	    $first   = $first_bubble_line{$question-1} + 1;
 7096: 	    $count   = $bubble_lines_per_response{$question-1};
 7097:         }
 7098:         $last = $first+$count-1;
 7099:         push(@lines, ($first..$last));
 7100:     }
 7101:     return join(',', @lines);
 7102: }
 7103: 
 7104: =pod 
 7105: 
 7106: =item prompt_for_corrections
 7107: 
 7108: Prompts for a potentially multiline correction to the
 7109: user's bubbling (factors out common code from scantron_get_correction
 7110: for multi and missing bubble cases).
 7111: 
 7112:  Arguments:
 7113:    $r           - Apache request object.
 7114:    $question    - The question number to prompt for.
 7115:    $scan_config - The scantron file configuration hash.
 7116:    $scan_record - Reference to the hash that has the the parsed scanlines.
 7117:    $error       - Type of error
 7118: 
 7119:  Implicit inputs:
 7120:    %bubble_lines_per_response   - Starting line numbers for each question.
 7121:                                   Numbered from 0 (but question numbers are from
 7122:                                   1.
 7123:    %first_bubble_line           - Starting bubble line for each question.
 7124:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 7125:                                   type problems render as separate sub-questions, 
 7126:                                   in exam mode. This hash contains a 
 7127:                                   comma-separated list of the lines per 
 7128:                                   sub-question.
 7129:    %responsetype_per_response   - essayresponse, formularesponse,
 7130:                                   stringresponse, imageresponse, reactionresponse,
 7131:                                   and organicresponse type problem parts can have
 7132:                                   multiple lines per response if the weight
 7133:                                   assigned exceeds 10.  In this case, only
 7134:                                   one bubble per line is permitted, but more 
 7135:                                   than one line might contain bubbles, e.g.
 7136:                                   bubbling of: line 1 - J, line 2 - J, 
 7137:                                   line 3 - B would assign 22 points.  
 7138: 
 7139: =cut
 7140: 
 7141: sub prompt_for_corrections {
 7142:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
 7143:     my ($current_line,$lines);
 7144:     my @linenums;
 7145:     my $questionnum = $question;
 7146:     if ($question =~ /^(\d+)\.(\d+)$/) {
 7147:         $question = $1;
 7148:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7149:         my $subquestion = $2;
 7150:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7151:         my $subcount = 1;
 7152:         while ($subcount<$subquestion) {
 7153:             $current_line += $subans[$subcount-1];
 7154:             $subcount ++;
 7155:         }
 7156:         $lines = $subans[$subquestion-1];
 7157:     } else {
 7158:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7159:         $lines        = $bubble_lines_per_response{$question-1};
 7160:     }
 7161:     if ($lines > 1) {
 7162:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7163:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
 7164:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
 7165:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
 7166:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
 7167:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
 7168:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
 7169:             $r->print(&mt("Although this particular question type requires handgrading, the instructions for this question in the exam directed students to leave [quant,_1,line] blank on their bubblesheets.",$lines).'<br /><br />'.&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.').'<br />'.&mt('The score for this question will be a sum of the numeric values for the selected bubbles from each line, where A=1 point, B=2 points etc.').'<br />'.&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.").'<br /><br />');
 7170:         } else {
 7171:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7172:         }
 7173:     }
 7174:     for (my $i =0; $i < $lines; $i++) {
 7175:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7176: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
 7177: 	        		  $questionnum,$error,split('', $selected));
 7178:         push(@linenums,$current_line);
 7179: 	$current_line++;
 7180:     }
 7181:     if ($lines > 1) {
 7182: 	$r->print("<hr /><br />");
 7183:     }
 7184:     return @linenums;
 7185: }
 7186: 
 7187: =pod
 7188: 
 7189: =item scantron_bubble_selector
 7190:   
 7191:    Generates the html radiobuttons to correct a single bubble line
 7192:    possibly showing the existing the selected bubbles if known
 7193: 
 7194:  Arguments:
 7195:     $r           - Apache request object
 7196:     $scan_config - hash from &get_scantron_config()
 7197:     $line        - Number of the line being displayed.
 7198:     $questionnum - Question number (may include subquestion)
 7199:     $error       - Type of error.
 7200:     @selected    - Array of bubbles picked on this line.
 7201: 
 7202: =cut
 7203: 
 7204: sub scantron_bubble_selector {
 7205:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7206:     my $max=$$scan_config{'Qlength'};
 7207: 
 7208:     my $scmode=$$scan_config{'Qon'};
 7209:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
 7210: 
 7211:     my @alphabet=('A'..'Z');
 7212:     $r->print(&Apache::loncommon::start_data_table().
 7213:               &Apache::loncommon::start_data_table_row());
 7214:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7215:     for (my $i=0;$i<$max+1;$i++) {
 7216: 	$r->print("\n".'<td align="center">');
 7217: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7218: 	else { $r->print('&nbsp;'); }
 7219: 	$r->print('</td>');
 7220:     }
 7221:     $r->print(&Apache::loncommon::end_data_table_row().
 7222:               &Apache::loncommon::start_data_table_row());
 7223:     for (my $i=0;$i<$max;$i++) {
 7224: 	$r->print("\n".
 7225: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7226: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7227:     }
 7228:     my $nobub_checked = ' ';
 7229:     if ($error eq 'missingbubble') {
 7230:         $nobub_checked = ' checked = "checked" ';
 7231:     }
 7232:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7233: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7234:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7235:               $line.'" value="'.$questionnum.'" /></td>');
 7236:     $r->print(&Apache::loncommon::end_data_table_row().
 7237:               &Apache::loncommon::end_data_table());
 7238: }
 7239: 
 7240: =pod
 7241: 
 7242: =item num_matches
 7243: 
 7244:    Counts the number of characters that are the same between the two arguments.
 7245: 
 7246:  Arguments:
 7247:    $orig - CODE from the scanline
 7248:    $code - CODE to match against
 7249: 
 7250:  Returns:
 7251:    $count - integer count of the number of same characters between the
 7252:             two arguments
 7253: 
 7254: =cut
 7255: 
 7256: sub num_matches {
 7257:     my ($orig,$code) = @_;
 7258:     my @code=split(//,$code);
 7259:     my @orig=split(//,$orig);
 7260:     my $same=0;
 7261:     for (my $i=0;$i<scalar(@code);$i++) {
 7262: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7263:     }
 7264:     return $same;
 7265: }
 7266: 
 7267: =pod
 7268: 
 7269: =item scantron_get_closely_matching_CODEs
 7270: 
 7271:    Cycles through all CODEs and finds the set that has the greatest
 7272:    number of same characters as the provided CODE
 7273: 
 7274:  Arguments:
 7275:    $allcodes - hash ref returned by &get_codes()
 7276:    $CODE     - CODE from the current scanline
 7277: 
 7278:  Returns:
 7279:    2 element list
 7280:     - first elements is number of how closely matching the best fit is 
 7281:       (5 means best set has 5 matching characters)
 7282:     - second element is an arrary ref containing the set of valid CODEs
 7283:       that best fit the passed in CODE
 7284: 
 7285: =cut
 7286: 
 7287: sub scantron_get_closely_matching_CODEs {
 7288:     my ($allcodes,$CODE)=@_;
 7289:     my @CODEs;
 7290:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7291: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7292:     }
 7293: 
 7294:     return ($#CODEs,$CODEs[-1]);
 7295: }
 7296: 
 7297: =pod
 7298: 
 7299: =item get_codes
 7300: 
 7301:    Builds a hash which has keys of all of the valid CODEs from the selected
 7302:    set of remembered CODEs.
 7303: 
 7304:  Arguments:
 7305:   $old_name - name of the set of remembered CODEs
 7306:   $cdom     - domain of the course
 7307:   $cnum     - internal course name
 7308: 
 7309:  Returns:
 7310:   %allcodes - keys are the valid CODEs, values are all 1
 7311: 
 7312: =cut
 7313: 
 7314: sub get_codes {
 7315:     my ($old_name, $cdom, $cnum) = @_;
 7316:     if (!$old_name) {
 7317: 	$old_name=$env{'form.scantron_CODElist'};
 7318:     }
 7319:     if (!$cdom) {
 7320: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7321:     }
 7322:     if (!$cnum) {
 7323: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7324:     }
 7325:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7326: 				    $cdom,$cnum);
 7327:     my %allcodes;
 7328:     if ($result{"type\0$old_name"} eq 'number') {
 7329: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7330:     } else {
 7331: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7332:     }
 7333:     return %allcodes;
 7334: }
 7335: 
 7336: =pod
 7337: 
 7338: =item scantron_validate_CODE
 7339: 
 7340:    Validates all scanlines in the selected file to not have any
 7341:    invalid or underspecified CODEs and that none of the codes are
 7342:    duplicated if this was requested.
 7343: 
 7344: =cut
 7345: 
 7346: sub scantron_validate_CODE {
 7347:     my ($r,$currentphase) = @_;
 7348:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7349:     if ($scantron_config{'CODElocation'} &&
 7350: 	$scantron_config{'CODEstart'} &&
 7351: 	$scantron_config{'CODElength'}) {
 7352: 	if (!defined($env{'form.scantron_CODElist'})) {
 7353: 	    &FIXME_blow_up()
 7354: 	}
 7355:     } else {
 7356: 	return (0,$currentphase+1);
 7357:     }
 7358:     
 7359:     my %usedCODEs;
 7360: 
 7361:     my %allcodes=&get_codes();
 7362: 
 7363:     my $nav_error;
 7364:     &scantron_get_maxbubble(\$nav_error); # parse needs the lines per response array.
 7365:     if ($nav_error) {
 7366:         $r->print(&navmap_errormsg());
 7367:         return(1,$currentphase);
 7368:     }
 7369: 
 7370:     my ($scanlines,$scan_data)=&scantron_getfile();
 7371:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7372: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7373: 	if ($line=~/^[\s\cz]*$/) { next; }
 7374: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7375: 						 $scan_data);
 7376: 	my $CODE=$$scan_record{'scantron.CODE'};
 7377: 	my $error=0;
 7378: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7379: 	    &scantron_get_correction($r,$i,$scan_record,
 7380: 				     \%scantron_config,
 7381: 				     $line,'incorrectCODE',\%allcodes);
 7382: 	    return(1,$currentphase);
 7383: 	}
 7384: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7385: 	    && !$$scan_record{'scantron.useCODE'}) {
 7386: 	    &scantron_get_correction($r,$i,$scan_record,
 7387: 				     \%scantron_config,
 7388: 				     $line,'incorrectCODE',\%allcodes);
 7389: 	    return(1,$currentphase);
 7390: 	}
 7391: 	if (exists($usedCODEs{$CODE}) 
 7392: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 7393: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 7394: 	    &scantron_get_correction($r,$i,$scan_record,
 7395: 				     \%scantron_config,
 7396: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 7397: 	    return(1,$currentphase);
 7398: 	}
 7399: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 7400:     }
 7401:     return (0,$currentphase+1);
 7402: }
 7403: 
 7404: =pod
 7405: 
 7406: =item scantron_validate_doublebubble
 7407: 
 7408:    Validates all scanlines in the selected file to not have any
 7409:    bubble lines with multiple bubbles marked.
 7410: 
 7411: =cut
 7412: 
 7413: sub scantron_validate_doublebubble {
 7414:     my ($r,$currentphase) = @_;
 7415:     #get student info
 7416:     my $classlist=&Apache::loncoursedata::get_classlist();
 7417:     my %idmap=&username_to_idmap($classlist);
 7418: 
 7419:     #get scantron line setup
 7420:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7421:     my ($scanlines,$scan_data)=&scantron_getfile();
 7422:     my $nav_error;
 7423:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble line array.
 7424:     if ($nav_error) {
 7425:         $r->print(&navmap_errormsg());
 7426:         return(1,$currentphase);
 7427:     }
 7428: 
 7429:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7430: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7431: 	if ($line=~/^[\s\cz]*$/) { next; }
 7432: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7433: 						 $scan_data);
 7434: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 7435: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 7436: 				 'doublebubble',
 7437: 				 $$scan_record{'scantron.doubleerror'});
 7438:     	return (1,$currentphase);
 7439:     }
 7440:     return (0,$currentphase+1);
 7441: }
 7442: 
 7443: 
 7444: sub scantron_get_maxbubble {
 7445:     my ($nav_error) = @_;
 7446:     if (defined($env{'form.scantron_maxbubble'}) &&
 7447: 	$env{'form.scantron_maxbubble'}) {
 7448: 	&restore_bubble_lines();
 7449: 	return $env{'form.scantron_maxbubble'};
 7450:     }
 7451: 
 7452:     my (undef, undef, $sequence) =
 7453: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7454: 
 7455:     my $navmap=Apache::lonnavmaps::navmap->new();
 7456:     unless (ref($navmap)) {
 7457:         if (ref($nav_error)) {
 7458:             $$nav_error = 1;
 7459:         }
 7460:         return;
 7461:     }
 7462:     my $map=$navmap->getResourceByUrl($sequence);
 7463:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7464: 
 7465:     &Apache::lonxml::clear_problem_counter();
 7466: 
 7467:     my $uname       = $env{'user.name'};
 7468:     my $udom        = $env{'user.domain'};
 7469:     my $cid         = $env{'request.course.id'};
 7470:     my $total_lines = 0;
 7471:     %bubble_lines_per_response = ();
 7472:     %first_bubble_line         = ();
 7473:     %subdivided_bubble_lines   = ();
 7474:     %responsetype_per_response = ();
 7475: 
 7476:     my $response_number = 0;
 7477:     my $bubble_line     = 0;
 7478:     foreach my $resource (@resources) {
 7479:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
 7480:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 7481: 	    foreach my $part_id (@{$parts}) {
 7482:                 my $lines;
 7483: 
 7484: 	        # TODO - make this a persistent hash not an array.
 7485: 
 7486:                 # optionresponse, matchresponse and rankresponse type items 
 7487:                 # render as separate sub-questions in exam mode.
 7488:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 7489:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 7490:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 7491:                     my ($numbub,$numshown);
 7492:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 7493:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 7494:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 7495:                         }
 7496:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 7497:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 7498:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 7499:                         }
 7500:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 7501:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 7502:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 7503:                         }
 7504:                     }
 7505:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 7506:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 7507:                     }
 7508:                     my $bubbles_per_line = 10;
 7509:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
 7510:                     if (($numbub % $bubbles_per_line) != 0) {
 7511:                         $inner_bubble_lines++;
 7512:                     }
 7513:                     for (my $i=0; $i<$numshown; $i++) {
 7514:                         $subdivided_bubble_lines{$response_number} .= 
 7515:                             $inner_bubble_lines.',';
 7516:                     }
 7517:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 7518:                     $lines = $numshown * $inner_bubble_lines;
 7519:                 } else {
 7520:                     $lines = $analysis->{"$part_id.bubble_lines"};
 7521:                 } 
 7522: 
 7523:                 $first_bubble_line{$response_number} = $bubble_line;
 7524: 	        $bubble_lines_per_response{$response_number} = $lines;
 7525:                 $responsetype_per_response{$response_number} = 
 7526:                     $analysis->{$part_id.'.type'};
 7527: 	        $response_number++;
 7528: 
 7529: 	        $bubble_line +=  $lines;
 7530: 	        $total_lines +=  $lines;
 7531: 	    }
 7532:         }
 7533:     }
 7534:     &Apache::lonnet::delenv('scantron.');
 7535: 
 7536:     &save_bubble_lines();
 7537:     $env{'form.scantron_maxbubble'} =
 7538: 	$total_lines;
 7539:     return $env{'form.scantron_maxbubble'};
 7540: }
 7541: 
 7542: sub scantron_validate_missingbubbles {
 7543:     my ($r,$currentphase) = @_;
 7544:     #get student info
 7545:     my $classlist=&Apache::loncoursedata::get_classlist();
 7546:     my %idmap=&username_to_idmap($classlist);
 7547: 
 7548:     #get scantron line setup
 7549:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7550:     my ($scanlines,$scan_data)=&scantron_getfile();
 7551:     my $nav_error;
 7552:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
 7553:     if ($nav_error) {
 7554:         return(1,$currentphase);
 7555:     }
 7556:     if (!$max_bubble) { $max_bubble=2**31; }
 7557:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7558: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7559: 	if ($line=~/^[\s\cz]*$/) { next; }
 7560: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7561: 						 $scan_data);
 7562: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 7563: 	my @to_correct;
 7564: 	
 7565: 	# Probably here's where the error is...
 7566: 
 7567: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 7568:             my $lastbubble;
 7569:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 7570:                my $question = $1;
 7571:                my $subquestion = $2;
 7572:                if (!defined($first_bubble_line{$question -1})) { next; }
 7573:                my $first = $first_bubble_line{$question-1};
 7574:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7575:                my $subcount = 1;
 7576:                while ($subcount<$subquestion) {
 7577:                    $first += $subans[$subcount-1];
 7578:                    $subcount ++;
 7579:                }
 7580:                my $count = $subans[$subquestion-1];
 7581:                $lastbubble = $first + $count;
 7582:             } else {
 7583:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
 7584:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
 7585:             }
 7586:             if ($lastbubble > $max_bubble) { next; }
 7587: 	    push(@to_correct,$missing);
 7588: 	}
 7589: 	if (@to_correct) {
 7590: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7591: 				     $line,'missingbubble',\@to_correct);
 7592: 	    return (1,$currentphase);
 7593: 	}
 7594: 
 7595:     }
 7596:     return (0,$currentphase+1);
 7597: }
 7598: 
 7599: 
 7600: sub scantron_process_students {
 7601:     my ($r) = @_;
 7602: 
 7603:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7604:     my ($symb)=&get_symb($r);
 7605:     if (!$symb) {
 7606: 	return '';
 7607:     }
 7608:     my $default_form_data=&defaultFormData($symb);
 7609: 
 7610:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7611:     my ($scanlines,$scan_data)=&scantron_getfile();
 7612:     my $classlist=&Apache::loncoursedata::get_classlist();
 7613:     my %idmap=&username_to_idmap($classlist);
 7614:     my $navmap=Apache::lonnavmaps::navmap->new();
 7615:     unless (ref($navmap)) {
 7616:         $r->print(&navmap_errormsg());
 7617:         return '';
 7618:     }  
 7619:     my $map=$navmap->getResourceByUrl($sequence);
 7620:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7621:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 7622:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 7623:                             \%grader_randomlists_by_symb);
 7624:     my $resource_error;
 7625:     foreach my $resource (@resources) {
 7626:         my $ressymb;
 7627:         if (ref($resource)) {
 7628:             $ressymb = $resource->symb();
 7629:         } else {
 7630:             $resource_error = 1;
 7631:             last;
 7632:         }
 7633:         my ($analysis,$parts) =
 7634:             &scantron_partids_tograde($resource,$env{'request.course.id'},
 7635:                                       $env{'user.name'},$env{'user.domain'},1);
 7636:         $grader_partids_by_symb{$ressymb} = $parts;
 7637:         if (ref($analysis) eq 'HASH') {
 7638:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7639:                 $grader_randomlists_by_symb{$ressymb} = 
 7640:                     $analysis->{'parts_withrandomlist'};
 7641:             }
 7642:         }
 7643:     }
 7644:     if ($resource_error) {
 7645:         $r->print(&navmap_errormsg());
 7646:         return '';
 7647:     }
 7648: 
 7649:     my ($uname,$udom);
 7650:     my $result= <<SCANTRONFORM;
 7651: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7652:   <input type="hidden" name="command" value="scantron_configphase" />
 7653:   $default_form_data
 7654: SCANTRONFORM
 7655:     $r->print($result);
 7656: 
 7657:     my @delayqueue;
 7658:     my (%completedstudents,%scandata);
 7659:     
 7660:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 7661:     my $count=&get_todo_count($scanlines,$scan_data);
 7662:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
 7663:  				    'Bubblesheet Progress',$count,
 7664: 				    'inline',undef,'scantronupload');
 7665:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 7666: 					  'Processing first student');
 7667:     $r->print('<br />');
 7668:     my $start=&Time::HiRes::time();
 7669:     my $i=-1;
 7670:     my $started;
 7671: 
 7672:     my $nav_error;
 7673:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
 7674:     if ($nav_error) {
 7675:         $r->print(&navmap_errormsg());
 7676:         return '';
 7677:     }
 7678: 
 7679:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 7680:     # the user and return.
 7681: 
 7682:     if ($ssi_error) {
 7683: 	$r->print("</form>");
 7684: 	&ssi_print_error($r);
 7685: 	$r->print(&show_grading_menu_form($symb));
 7686:         &Apache::lonnet::remove_lock($lock);
 7687: 	return '';		# Dunno why the other returns return '' rather than just returning.
 7688:     }
 7689: 
 7690:     my %lettdig = &letter_to_digits();
 7691:     my $numletts = scalar(keys(%lettdig));
 7692: 
 7693:     while ($i<$scanlines->{'count'}) {
 7694:  	($uname,$udom)=('','');
 7695:  	$i++;
 7696:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7697:  	if ($line=~/^[\s\cz]*$/) { next; }
 7698: 	if ($started) {
 7699: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 7700: 						     'last student');
 7701: 	}
 7702: 	$started=1;
 7703:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7704:  						 $scan_data);
 7705:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 7706:  					      \%idmap,$i)) {
 7707:   	    &scantron_add_delay(\@delayqueue,$line,
 7708:  				'Unable to find a student that matches',1);
 7709:  	    next;
 7710:   	}
 7711:  	if (exists $completedstudents{$uname}) {
 7712:  	    &scantron_add_delay(\@delayqueue,$line,
 7713:  				'Student '.$uname.' has multiple sheets',2);
 7714:  	    next;
 7715:  	}
 7716:   	($uname,$udom)=split(/:/,$uname);
 7717: 
 7718:         my (%partids_by_symb,$res_error);
 7719:         foreach my $resource (@resources) {
 7720:             my $ressymb;
 7721:             if (ref($resource)) {
 7722:                 $ressymb = $resource->symb();
 7723:             } else {
 7724:                 $res_error = 1;
 7725:                 last;
 7726:             }
 7727:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 7728:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 7729:                 my ($analysis,$parts) =
 7730:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
 7731:                 $partids_by_symb{$ressymb} = $parts;
 7732:             } else {
 7733:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 7734:             }
 7735:         }
 7736: 
 7737:         if ($res_error) {
 7738:             &scantron_add_delay(\@delayqueue,$line,
 7739:                                 'An error occurred while grading student '.$uname,2);
 7740:             next;
 7741:         }
 7742: 
 7743: 	&Apache::lonxml::clear_problem_counter();
 7744:   	&Apache::lonnet::appenv($scan_record);
 7745: 
 7746: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 7747: 	    &scantron_putfile($scanlines,$scan_data);
 7748: 	}
 7749: 	
 7750:         my $scancode;
 7751:         if ((exists($scan_record->{'scantron.CODE'})) &&
 7752:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 7753:             $scancode = $scan_record->{'scantron.CODE'};
 7754:         } else {
 7755:             $scancode = '';
 7756:         }
 7757: 
 7758:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7759:                                    \@resources,\%partids_by_symb) eq 'ssi_error') {
 7760:             $ssi_error = 0; # So end of handler error message does not trigger.
 7761:             $r->print("</form>");
 7762:             &ssi_print_error($r);
 7763:             $r->print(&show_grading_menu_form($symb));
 7764:             &Apache::lonnet::remove_lock($lock);
 7765:             return '';      # Why return ''?  Beats me.
 7766:         }
 7767: 
 7768: 	$completedstudents{$uname}={'line'=>$line};
 7769:         if ($env{'form.verifyrecord'}) {
 7770:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 7771:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 7772:             chomp($studentdata);
 7773:             $studentdata =~ s/\r$//;
 7774:             my $studentrecord = '';
 7775:             my $counter = -1;
 7776:             foreach my $resource (@resources) {
 7777:                 my $ressymb = $resource->symb();
 7778:                 ($counter,my $recording) =
 7779:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7780:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 7781:                                              \%scantron_config,\%lettdig,$numletts);
 7782:                 $studentrecord .= $recording;
 7783:             }
 7784:             if ($studentrecord ne $studentdata) {
 7785:                 &Apache::lonxml::clear_problem_counter();
 7786:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7787:                                            \@resources,\%partids_by_symb) eq 'ssi_error') {
 7788:                     $ssi_error = 0; # So end of handler error message does not trigger.
 7789:                     $r->print("</form>");
 7790:                     &ssi_print_error($r);
 7791:                     $r->print(&show_grading_menu_form($symb));
 7792:                     &Apache::lonnet::remove_lock($lock);
 7793:                     delete($completedstudents{$uname});
 7794:                     return '';
 7795:                 }
 7796:                 $counter = -1;
 7797:                 $studentrecord = '';
 7798:                 foreach my $resource (@resources) {
 7799:                     my $ressymb = $resource->symb();
 7800:                     ($counter,my $recording) =
 7801:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7802:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 7803:                                                  \%scantron_config,\%lettdig,$numletts);
 7804:                     $studentrecord .= $recording;
 7805:                 }
 7806:                 if ($studentrecord ne $studentdata) {
 7807:                     $r->print('<p><span class="LC_error">');
 7808:                     if ($scancode eq '') {
 7809:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
 7810:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 7811:                     } else {
 7812:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
 7813:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 7814:                     }
 7815:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 7816:                               &Apache::loncommon::start_data_table_header_row()."\n".
 7817:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 7818:                               &Apache::loncommon::end_data_table_header_row()."\n".
 7819:                               &Apache::loncommon::start_data_table_row().
 7820:                               '<td>'.&mt('Bubble Sheet').'</td>'.
 7821:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
 7822:                               &Apache::loncommon::end_data_table_row().
 7823:                               &Apache::loncommon::start_data_table_row().
 7824:                               '<td>Stored submissions</td>'.
 7825:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
 7826:                               &Apache::loncommon::end_data_table_row().
 7827:                               &Apache::loncommon::end_data_table().'</p>');
 7828:                 } else {
 7829:                     $r->print('<br /><span class="LC_warning">'.
 7830:                              &mt('A second grading pass was needed for user: [_1] with ID: [_2], because a mismatch was seen on the first pass.',$uname.':'.$udom,$scan_record->{'scantron.ID'}).'<br />'.
 7831:                              &mt("As a consequence, this user's submission history records two tries.").
 7832:                                  '</span><br />');
 7833:                 }
 7834:             }
 7835:         }
 7836:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 7837:     } continue {
 7838: 	&Apache::lonxml::clear_problem_counter();
 7839: 	&Apache::lonnet::delenv('scantron.');
 7840:     }
 7841:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 7842:     &Apache::lonnet::remove_lock($lock);
 7843: #    my $lasttime = &Time::HiRes::time()-$start;
 7844: #    $r->print("<p>took $lasttime</p>");
 7845: 
 7846:     $r->print("</form>");
 7847:     $r->print(&show_grading_menu_form($symb));
 7848:     return '';
 7849: }
 7850: 
 7851: sub graders_resources_pass {
 7852:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
 7853:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 7854:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 7855:         foreach my $resource (@{$resources}) {
 7856:             my $ressymb = $resource->symb();
 7857:             my ($analysis,$parts) =
 7858:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 7859:                                           $env{'user.name'},$env{'user.domain'},1);
 7860:             $grader_partids_by_symb->{$ressymb} = $parts;
 7861:             if (ref($analysis) eq 'HASH') {
 7862:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7863:                     $grader_randomlists_by_symb->{$ressymb} =
 7864:                         $analysis->{'parts_withrandomlist'};
 7865:                 }
 7866:             }
 7867:         }
 7868:     }
 7869:     return;
 7870: }
 7871: 
 7872: sub grade_student_bubbles {
 7873:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
 7874:     if (ref($resources) eq 'ARRAY') {
 7875:         my $count = 0;
 7876:         foreach my $resource (@{$resources}) {
 7877:             my $ressymb = $resource->symb();
 7878:             my %form = ('submitted'      => 'scantron',
 7879:                         'grade_target'   => 'grade',
 7880:                         'grade_username' => $uname,
 7881:                         'grade_domain'   => $udom,
 7882:                         'grade_courseid' => $env{'request.course.id'},
 7883:                         'grade_symb'     => $ressymb,
 7884:                         'CODE'           => $scancode
 7885:                        );
 7886:             if (ref($parts) eq 'HASH') {
 7887:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 7888:                     foreach my $part (@{$parts->{$ressymb}}) {
 7889:                         $form{'scantron_questnum_start.'.$part} =
 7890:                             1+$env{'form.scantron.first_bubble_line.'.$count};
 7891:                         $count++;
 7892:                     }
 7893:                 }
 7894:             }
 7895:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 7896:             return 'ssi_error' if ($ssi_error);
 7897:             last if (&Apache::loncommon::connection_aborted($r));
 7898:         }
 7899:     }
 7900:     return;
 7901: }
 7902: 
 7903: sub scantron_upload_scantron_data {
 7904:     my ($r)=@_;
 7905:     my $dom = $env{'request.role.domain'};
 7906:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 7907:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 7908:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 7909: 							  'domainid',
 7910: 							  'coursename',$dom);
 7911:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 7912:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
 7913:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 7914:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 7915:     my $nocourseid_alert = &mt("Please use the 'Select Course' link to open a separate window where you can search for a course to which a file can be uploaded.");
 7916:     $r->print(&Apache::lonhtmlcommon::scripttag('
 7917:     function checkUpload(formname) {
 7918: 	if (formname.upfile.value == "") {
 7919: 	    alert("'.$nofile_alert.'");
 7920: 	    return false;
 7921: 	}
 7922:         if (formname.courseid.value == "") {
 7923:             alert("'.$nocourseid_alert.'");
 7924:             return false;
 7925:         }
 7926: 	formname.submit();
 7927:     }
 7928: 
 7929:     function ToSyllabus() {
 7930:         var cdom = '."'$dom'".';
 7931:         var cnum = document.rules.courseid.value;
 7932:         if (cdom == "" || cdom == null) {
 7933:             return;
 7934:         }
 7935:         if (cnum == "" || cnum == null) {
 7936:            return;
 7937:         }
 7938:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 7939:                             "height=350,width=350,scrollbars=yes,menubar=no");
 7940:         return;
 7941:     }
 7942: 
 7943: '));
 7944:     $r->print('
 7945: <h3>'.&mt('Send scanned bubblesheet data to a course').'</h3>
 7946: 
 7947: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 7948: '.$default_form_data.
 7949:   &Apache::lonhtmlcommon::start_pick_box().
 7950:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 7951:   '<input name="courseid" type="text" size="30" />'.$select_link.
 7952:   &Apache::lonhtmlcommon::row_closure().
 7953:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 7954:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 7955:   &Apache::lonhtmlcommon::row_closure().
 7956:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 7957:   '<input name="domainid" type="hidden" />'.$domdesc.
 7958:   &Apache::lonhtmlcommon::row_closure().
 7959:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 7960:   '<input type="file" name="upfile" size="50" />'.
 7961:   &Apache::lonhtmlcommon::row_closure(1).
 7962:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 7963: 
 7964: <input name="command" value="scantronupload_save" type="hidden" />
 7965: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 7966: </form>
 7967: ');
 7968:     return '';
 7969: }
 7970: 
 7971: 
 7972: sub scantron_upload_scantron_data_save {
 7973:     my($r)=@_;
 7974:     my ($symb)=&get_symb($r,1);
 7975:     my $doanotherupload=
 7976: 	'<br /><form action="/adm/grades" method="post">'."\n".
 7977: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 7978: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 7979: 	'</form>'."\n";
 7980:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 7981: 	!&Apache::lonnet::allowed('usc',
 7982: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 7983: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 7984: 	if ($symb) {
 7985: 	    $r->print(&show_grading_menu_form($symb));
 7986: 	} else {
 7987: 	    $r->print($doanotherupload);
 7988: 	}
 7989: 	return '';
 7990:     }
 7991:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 7992:     my $uploadedfile;
 7993:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
 7994:     if (length($env{'form.upfile'}) < 2) {
 7995:         $r->print(&mt('[_1]Error:[_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.','<span class="LC_error">','</span>','<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 7996:     } else {
 7997:         my $result = 
 7998:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
 7999:                                             $env{'form.courseid'},$env{'form.domainid'});
 8000: 	if ($result =~ m{^/uploaded/}) {
 8001: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
 8002:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
 8003: 			  '<span class="LC_filename">'.$result.'</span>'));
 8004:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 8005:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 8006:                                                        $env{'form.courseid'},$uploadedfile));
 8007: 	} else {
 8008: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
 8009:                           '<span class="LC_error">','</span>',$result,
 8010: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 8011: 	}
 8012:     }
 8013:     if ($symb) {
 8014: 	$r->print(&scantron_selectphase($r,$uploadedfile));
 8015:     } else {
 8016: 	$r->print($doanotherupload);
 8017:     }
 8018:     return '';
 8019: }
 8020: 
 8021: sub validate_uploaded_scantron_file {
 8022:     my ($cdom,$cname,$fname) = @_;
 8023:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 8024:     my @lines;
 8025:     if ($scanlines ne '-1') {
 8026:         @lines=split("\n",$scanlines,-1);
 8027:     }
 8028:     my $output;
 8029:     if (@lines) {
 8030:         my (%counts,$max_match_format);
 8031:         my ($max_match_count,$max_match_pct) = (0,0);
 8032:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 8033:         my %idmap = &username_to_idmap($classlist);
 8034:         foreach my $key (keys(%idmap)) {
 8035:             my $lckey = lc($key);
 8036:             $idmap{$lckey} = $idmap{$key};
 8037:         }
 8038:         my %unique_formats;
 8039:         my @formatlines = &get_scantronformat_file();
 8040:         foreach my $line (@formatlines) {
 8041:             chomp($line);
 8042:             my @config = split(/:/,$line);
 8043:             my $idstart = $config[5];
 8044:             my $idlength = $config[6];
 8045:             if (($idstart ne '') && ($idlength > 0)) {
 8046:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 8047:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 8048:                 } else {
 8049:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 8050:                 }
 8051:             }
 8052:         }
 8053:         foreach my $key (keys(%unique_formats)) {
 8054:             my ($idstart,$idlength) = split(':',$key);
 8055:             %{$counts{$key}} = (
 8056:                                'found'   => 0,
 8057:                                'total'   => 0,
 8058:                               );
 8059:             foreach my $line (@lines) {
 8060:                 next if ($line =~ /^#/);
 8061:                 next if ($line =~ /^[\s\cz]*$/);
 8062:                 my $id = substr($line,$idstart-1,$idlength);
 8063:                 $id = lc($id);
 8064:                 if (exists($idmap{$id})) {
 8065:                     $counts{$key}{'found'} ++;
 8066:                 }
 8067:                 $counts{$key}{'total'} ++;
 8068:             }
 8069:             if ($counts{$key}{'total'}) {
 8070:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 8071:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 8072:                     $max_match_pct = $percent_match;
 8073:                     $max_match_format = $key;
 8074:                     $max_match_count = $counts{$key}{'total'};
 8075:                 }
 8076:             }
 8077:         }
 8078:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 8079:             my $format_descs;
 8080:             my $numwithformat = @{$unique_formats{$max_match_format}};
 8081:             for (my $i=0; $i<$numwithformat; $i++) {
 8082:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 8083:                 if ($i<$numwithformat-2) {
 8084:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 8085:                 } elsif ($i==$numwithformat-2) {
 8086:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 8087:                 } elsif ($i==$numwithformat-1) {
 8088:                     $format_descs .= '"<i>'.$desc.'</i>"';
 8089:                 }
 8090:             }
 8091:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 8092:             $output .= '<br />'.&mt('Comparison of student IDs in the uploaded file with the course roster found matches for [_1] of the [_2] entries in the file (for the format defined for [_3]).','<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
 8093:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
 8094:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
 8095:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
 8096:                                   '<i>'.$cdom.'</i>').'</li>'.
 8097:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 8098:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
 8099:                        '</ul>';
 8100:         }
 8101:     } else {
 8102:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
 8103:     }
 8104:     return $output;
 8105: }
 8106: 
 8107: sub valid_file {
 8108:     my ($requested_file)=@_;
 8109:     foreach my $filename (sort(&scantron_filenames())) {
 8110: 	if ($requested_file eq $filename) { return 1; }
 8111:     }
 8112:     return 0;
 8113: }
 8114: 
 8115: sub scantron_download_scantron_data {
 8116:     my ($r)=@_;
 8117:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 8118:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8119:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8120:     my $file=$env{'form.scantron_selectfile'};
 8121:     if (! &valid_file($file)) {
 8122: 	$r->print('
 8123: 	<p>
 8124: 	    '.&mt('The requested file name was invalid.').'
 8125:         </p>
 8126: ');
 8127: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
 8128: 	return;
 8129:     }
 8130:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 8131:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 8132:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 8133:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 8134:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 8135:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 8136:     $r->print('
 8137:     <p>
 8138: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
 8139: 	      '<a href="'.$orig.'">','</a>').'
 8140:     </p>
 8141:     <p>
 8142: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 8143: 	      '<a href="'.$corrected.'">','</a>').'
 8144:     </p>
 8145:     <p>
 8146: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 8147: 	      '<a href="'.$skipped.'">','</a>').'
 8148:     </p>
 8149: ');
 8150:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
 8151:     return '';
 8152: }
 8153: 
 8154: sub checkscantron_results {
 8155:     my ($r) = @_;
 8156:     my ($symb)=&get_symb($r);
 8157:     if (!$symb) {return '';}
 8158:     my $grading_menu_button=&show_grading_menu_form($symb);
 8159:     my $cid = $env{'request.course.id'};
 8160:     my %lettdig = &letter_to_digits();
 8161:     my $numletts = scalar(keys(%lettdig));
 8162:     my $cnum = $env{'course.'.$cid.'.num'};
 8163:     my $cdom = $env{'course.'.$cid.'.domain'};
 8164:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8165:     my %record;
 8166:     my %scantron_config =
 8167:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 8168:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 8169:     my $classlist=&Apache::loncoursedata::get_classlist();
 8170:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 8171:     my $navmap=Apache::lonnavmaps::navmap->new();
 8172:     unless (ref($navmap)) {
 8173:         $r->print(&navmap_errormsg());
 8174:         return '';
 8175:     }
 8176:     my $map=$navmap->getResourceByUrl($sequence);
 8177:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8178:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 8179:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
 8180: 
 8181:     my ($uname,$udom);
 8182:     my (%scandata,%lastname,%bylast);
 8183:     $r->print('
 8184: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 8185: 
 8186:     my @delayqueue;
 8187:     my %completedstudents;
 8188: 
 8189:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
 8190:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
 8191:                                     'Progress of Bubblesheet Data/Submission Records Comparison',$count,
 8192:                                     'inline',undef,'checkscantron');
 8193:     my ($username,$domain,$started);
 8194:     my $nav_error;
 8195:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
 8196:     if ($nav_error) {
 8197:         $r->print(&navmap_errormsg());
 8198:         return '';
 8199:     }
 8200: 
 8201:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 8202:                                           'Processing first student');
 8203:     my $start=&Time::HiRes::time();
 8204:     my $i=-1;
 8205: 
 8206:     while ($i<$scanlines->{'count'}) {
 8207:         ($username,$domain,$uname)=('','','');
 8208:         $i++;
 8209:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 8210:         if ($line=~/^[\s\cz]*$/) { next; }
 8211:         if ($started) {
 8212:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 8213:                                                      'last student');
 8214:         }
 8215:         $started=1;
 8216:         my $scan_record=
 8217:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 8218:                                                      $scan_data);
 8219:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
 8220:                                                               \%idmap,$i)) {
 8221:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8222:                                 'Unable to find a student that matches',1);
 8223:             next;
 8224:         }
 8225:         if (exists $completedstudents{$uname}) {
 8226:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8227:                                 'Student '.$uname.' has multiple sheets',2);
 8228:             next;
 8229:         }
 8230:         my $pid = $scan_record->{'scantron.ID'};
 8231:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 8232:         push(@{$bylast{$lastname{$pid}}},$pid);
 8233:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8234:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8235:         chomp($scandata{$pid});
 8236:         $scandata{$pid} =~ s/\r$//;
 8237:         ($username,$domain)=split(/:/,$uname);
 8238:         my $counter = -1;
 8239:         foreach my $resource (@resources) {
 8240:             my $parts;
 8241:             my $ressymb = $resource->symb();
 8242:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8243:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8244:                 (my $analysis,$parts) =
 8245:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
 8246:             } else {
 8247:                 $parts = $grader_partids_by_symb{$ressymb};
 8248:             }
 8249:             ($counter,my $recording) =
 8250:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 8251:                                          $scandata{$pid},$parts,
 8252:                                          \%scantron_config,\%lettdig,$numletts);
 8253:             $record{$pid} .= $recording;
 8254:         }
 8255:     }
 8256:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8257:     $r->print('<br />');
 8258:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 8259:     $passed = 0;
 8260:     $failed = 0;
 8261:     $numstudents = 0;
 8262:     foreach my $last (sort(keys(%bylast))) {
 8263:         if (ref($bylast{$last}) eq 'ARRAY') {
 8264:             foreach my $pid (sort(@{$bylast{$last}})) {
 8265:                 my $showscandata = $scandata{$pid};
 8266:                 my $showrecord = $record{$pid};
 8267:                 $showscandata =~ s/\s/&nbsp;/g;
 8268:                 $showrecord =~ s/\s/&nbsp;/g;
 8269:                 if ($scandata{$pid} eq $record{$pid}) {
 8270:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 8271:                     $okstudents .= '<tr class="'.$css_class.'">'.
 8272: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 8273: '</tr>'."\n".
 8274: '<tr class="'.$css_class.'">'."\n".
 8275: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
 8276:                     $passed ++;
 8277:                 } else {
 8278:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 8279:                     $badstudents .= '<tr class="'.$css_class.'"><td>'.&mt('Bubblesheet').'</td><td><span class="LC_nobreak">'.$scandata{$pid}.'</span></td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 8280: '</tr>'."\n".
 8281: '<tr class="'.$css_class.'">'."\n".
 8282: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 8283: '</tr>'."\n";
 8284:                     $failed ++;
 8285:                 }
 8286:                 $numstudents ++;
 8287:             }
 8288:         }
 8289:     }
 8290:     $r->print('<p>'.&mt('Comparison of bubblesheet data (including corrections) with corresponding submission records (most recent submission) for <b>[quant,_1,student]</b>  ([_2] scantron lines/student).',$numstudents,$env{'form.scantron_maxbubble'}).'</p>');
 8291:     $r->print('<p>'.&mt('Exact matches for <b>[quant,_1,student]</b>.',$passed).'<br />'.&mt('Discrepancies detected for <b>[quant,_1,student]</b>.',$failed).'</p>');
 8292:     if ($passed) {
 8293:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 8294:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8295:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8296:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8297:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8298:                  $okstudents."\n".
 8299:                  &Apache::loncommon::end_data_table().'<br />');
 8300:     }
 8301:     if ($failed) {
 8302:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 8303:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8304:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8305:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8306:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8307:                  $badstudents."\n".
 8308:                  &Apache::loncommon::end_data_table()).'<br />'.
 8309:                  &mt('Differences can occur if submissions were modified using manual grading after a bubblesheet grading pass.').'<br />'.&mt('If unexpected discrepancies were detected, it is recommended that you inspect the original bubblesheets.');  
 8310:     }
 8311:     $r->print('</form><br />'.$grading_menu_button);
 8312:     return;
 8313: }
 8314: 
 8315: sub verify_scantron_grading {
 8316:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 8317:         $scantron_config,$lettdig,$numletts) = @_;
 8318:     my ($record,%expected,%startpos);
 8319:     return ($counter,$record) if (!ref($resource));
 8320:     return ($counter,$record) if (!$resource->is_problem());
 8321:     my $symb = $resource->symb();
 8322:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 8323:     foreach my $part_id (@{$partids}) {
 8324:         $counter ++;
 8325:         $expected{$part_id} = 0;
 8326:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
 8327:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
 8328:             foreach my $item (@sub_lines) {
 8329:                 $expected{$part_id} += $item;
 8330:             }
 8331:         } else {
 8332:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
 8333:         }
 8334:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 8335:     }
 8336:     if ($symb) {
 8337:         my %recorded;
 8338:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 8339:         if ($returnhash{'version'}) {
 8340:             my %lasthash=();
 8341:             my $version;
 8342:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 8343:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 8344:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 8345:                 }
 8346:             }
 8347:             foreach my $key (keys(%lasthash)) {
 8348:                 if ($key =~ /\.scantron$/) {
 8349:                     my $value = &unescape($lasthash{$key});
 8350:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 8351:                     if ($value eq '') {
 8352:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 8353:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 8354:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8355:                             }
 8356:                         }
 8357:                     } else {
 8358:                         my @tocheck;
 8359:                         my @items = split(//,$value);
 8360:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 8361:                             ($scantron_config->{'Qon'} eq 'number')) {
 8362:                             if (@items < $expected{$part_id}) {
 8363:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 8364:                                 my @singles = split(//,$fragment);
 8365:                                 foreach my $pos (@singles) {
 8366:                                     if ($pos eq ' ') {
 8367:                                         push(@tocheck,$pos);
 8368:                                     } else {
 8369:                                         my $next = shift(@items);
 8370:                                         push(@tocheck,$next);
 8371:                                     }
 8372:                                 }
 8373:                             } else {
 8374:                                 @tocheck = @items;
 8375:                             }
 8376:                             foreach my $letter (@tocheck) {
 8377:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 8378:                                     if ($letter !~ /^[A-J]$/) {
 8379:                                         $letter = $scantron_config->{'Qoff'};
 8380:                                     }
 8381:                                     $recorded{$part_id} .= $letter;
 8382:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 8383:                                     my $digit;
 8384:                                     if ($letter !~ /^[A-J]$/) {
 8385:                                         $digit = $scantron_config->{'Qoff'};
 8386:                                     } else {
 8387:                                         $digit = $lettdig->{$letter};
 8388:                                     }
 8389:                                     $recorded{$part_id} .= $digit;
 8390:                                 }
 8391:                             }
 8392:                         } else {
 8393:                             @tocheck = @items;
 8394:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 8395:                                 my $curr_sub = shift(@tocheck);
 8396:                                 my $digit;
 8397:                                 if ($curr_sub =~ /^[A-J]$/) {
 8398:                                     $digit = $lettdig->{$curr_sub}-1;
 8399:                                 }
 8400:                                 if ($curr_sub eq 'J') {
 8401:                                     $digit += scalar($numletts);
 8402:                                 }
 8403:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8404:                                     if ($j == $digit) {
 8405:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 8406:                                     } else {
 8407:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8408:                                     }
 8409:                                 }
 8410:                             }
 8411:                         }
 8412:                     }
 8413:                 }
 8414:             }
 8415:         }
 8416:         foreach my $part_id (@{$partids}) {
 8417:             if ($recorded{$part_id} eq '') {
 8418:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 8419:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8420:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8421:                     }
 8422:                 }
 8423:             }
 8424:             $record .= $recorded{$part_id};
 8425:         }
 8426:     }
 8427:     return ($counter,$record);
 8428: }
 8429: 
 8430: sub letter_to_digits { 
 8431:     my %lettdig = (
 8432:                     A => 1,
 8433:                     B => 2,
 8434:                     C => 3,
 8435:                     D => 4,
 8436:                     E => 5,
 8437:                     F => 6,
 8438:                     G => 7,
 8439:                     H => 8,
 8440:                     I => 9,
 8441:                     J => 0,
 8442:                   );
 8443:     return %lettdig;
 8444: }
 8445: 
 8446: 
 8447: #-------- end of section for handling grading scantron forms -------
 8448: #
 8449: #-------------------------------------------------------------------
 8450: 
 8451: #-------------------------- Menu interface -------------------------
 8452: #
 8453: #--- Show a Grading Menu button - Calls the next routine ---
 8454: sub show_grading_menu_form {
 8455:     my ($symb)=@_;
 8456:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
 8457: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8458: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 8459: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
 8460: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
 8461: 	'</form>'."\n";
 8462:     return $result;
 8463: }
 8464: 
 8465: sub grading_menu {
 8466:     my ($request) = @_;
 8467:     my ($symb)=&get_symb($request);
 8468:     if (!$symb) {return '';}
 8469: 
 8470:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 8471:                   'command'=>'individual',
 8472:                   'gradingMenu'=>1,
 8473:                   'showgrading'=>"yes");
 8474:     
 8475:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8476: 
 8477:     $fields{'command'}='ungraded';
 8478:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8479: 
 8480:     $fields{'command'}='table';
 8481:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8482: 
 8483:     $fields{'command'}='all_for_one';
 8484:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8485: 
 8486:     $fields{'command'} = 'csvform';
 8487:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8488:     
 8489:     $fields{'command'} = 'processclicker';
 8490:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8491:     
 8492:     $fields{'command'} = 'scantron_selectphase';
 8493:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8494: 
 8495:     $fields{'command'} = 'initialverifyreceipt';
 8496:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8497:     
 8498:     my @menu = ({	categorytitle=>'Hand Grading',
 8499:             items =>[
 8500:                         {	linktext => 'Select individual students to grade',
 8501:                     		url => $url1a,
 8502:                     		permission => 'F',
 8503:                     		icon => 'edit-find-replace.png',
 8504:                     		linktitle => 'Grade current resource for a selection of students.'
 8505:                         }, 
 8506:                         {       linktext => 'Grade ungraded submissions.',
 8507:                                 url => $url1b,
 8508:                                 permission => 'F',
 8509:                                 icon => 'edit-find-replace.png',
 8510:                                 linktitle => 'Grade all submissions that have not been graded yet.'
 8511:                         },
 8512: 
 8513:                         {       linktext => 'Grading table',
 8514:                                 url => $url1c,
 8515:                                 permission => 'F',
 8516:                                 icon => 'edit-find-replace.png',
 8517:                                 linktitle => 'Grade current resource for all students.'
 8518:                         },
 8519:                         {       linktext => 'Grade complete page/sequence/folder for one student',
 8520:                                 url => $url1d,
 8521:                                 permission => 'F',
 8522:                                 icon => 'edit-find-replace.png',
 8523:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
 8524:                         }]},
 8525:                          { categorytitle=>'Automated Grading',
 8526:                items =>[
 8527: 
 8528:                 	    {	linktext => 'Upload Scores',
 8529:                     		url => $url2,
 8530:                     		permission => 'F',
 8531:                     		icon => 'uploadscores.png',
 8532:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 8533:                 	    },
 8534:                 	    {	linktext => 'Process Clicker',
 8535:                     		url => $url3,
 8536:                     		permission => 'F',
 8537:                     		icon => 'addClickerInfoFile.png',
 8538:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 8539:                 	    },
 8540:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
 8541:                     		url => $url4,
 8542:                     		permission => 'F',
 8543:                     		icon => 'stat.png',
 8544:                     		linktitle => 'Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.'
 8545:                 	    },
 8546:                             {   linktext => 'Verify Receipt No.',
 8547:                                 url => $url5,
 8548:                                 permission => 'F',
 8549:                                 icon => 'edit-find-replace.png',
 8550:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
 8551:                             }
 8552: 
 8553:                     ]
 8554:             });
 8555: 
 8556:     # Create the menu
 8557:     my $Str;
 8558:     $Str .= '<form method="post" action="" name="gradingMenu">';
 8559:     $Str .= '<input type="hidden" name="command" value="" />'.
 8560:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8561: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8562: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8563: 
 8564:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
 8565:     return $Str;    
 8566: }
 8567: 
 8568: 
 8569: sub ungraded {
 8570:     my ($request)=@_;
 8571:     &submit_options($request);
 8572: }
 8573: 
 8574: sub submit_options_sequence {
 8575:     my ($request) = @_;
 8576:     my ($symb)=&get_symb($request);
 8577:     if (!$symb) {return '';}
 8578:     &commonJSfunctions($request);
 8579:     my $result;
 8580: 
 8581:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8582:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8583:         '<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8584:         '<input type="hidden" name="showgrading" value="yes" />'."\n";
 8585: 
 8586:     $result.='
 8587: <h2>
 8588:   '.&mt('Grade complete page/sequence/folder for one student').'
 8589: </h2>'.
 8590:             &selectfield(0).
 8591:             '<input type="hidden" name="command" value="pickStudentPage" />
 8592:             <div>
 8593:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 8594:             </div>
 8595:         </div>
 8596:   </form>';
 8597:     $result .= &show_grading_menu_form($symb);
 8598:     return $result;
 8599: }
 8600: 
 8601: sub submit_options_table {
 8602:     my ($request) = @_;
 8603:     my ($symb)=&get_symb($request);
 8604:     if (!$symb) {return '';}
 8605:     &commonJSfunctions($request);
 8606:     my $result;
 8607: 
 8608:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8609:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8610:         '<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8611:         '<input type="hidden" name="showgrading" value="yes" />'."\n";
 8612: 
 8613:     $result.='
 8614: <h2>
 8615:   '.&mt('Grading table').'
 8616: </h2>'.
 8617:             &selectfield(0).
 8618:             '<input type="hidden" name="command" value="viewgrades" />
 8619:             <div>
 8620:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 8621:             </div>
 8622:         </div>
 8623:   </form>';
 8624:     $result .= &show_grading_menu_form($symb);
 8625:     return $result;
 8626: }
 8627: 
 8628: 
 8629: 
 8630: #--- Displays the submissions first page -------
 8631: sub submit_options {
 8632:     my ($request) = @_;
 8633:     my ($symb)=&get_symb($request);
 8634:     if (!$symb) {return '';}
 8635: 
 8636:     &commonJSfunctions($request);
 8637:     my $result;
 8638: 
 8639:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8640: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8641: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8642: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8643: 
 8644:     $result.='
 8645: <h2>
 8646:   '.&mt('Select individual students to grade').'
 8647: </h2>'.&selectfield(1).'
 8648:                 <input type="hidden" name="command" value="submission" /> 
 8649: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
 8650:             </div>
 8651:           </div>
 8652: 
 8653: 
 8654:   </form>';
 8655:     $result .= &show_grading_menu_form($symb);
 8656:     return $result;
 8657: }
 8658: 
 8659: sub selectfield {
 8660:    my ($full)=@_;
 8661:    my $result='<div class="LC_columnSection">
 8662:   
 8663:     <fieldset>
 8664:       <legend>
 8665:        '.&mt('Sections').'
 8666:       </legend>
 8667:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
 8668:     </fieldset>
 8669:   
 8670:     <fieldset>
 8671:       <legend>
 8672:         '.&mt('Groups').'
 8673:       </legend>
 8674:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 8675:     </fieldset>
 8676:   
 8677:     <fieldset>
 8678:       <legend>
 8679:         '.&mt('Access Status').'
 8680:       </legend>
 8681:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
 8682:     </fieldset>';
 8683:     if ($full) {
 8684:        $result.='
 8685:     <fieldset>
 8686:       <legend>
 8687:         '.&mt('Submission Status').'
 8688:       </legend>'.
 8689:        &Apache::loncommon::select_form('all','submitonly',
 8690:           (&Apache::lonlocal::texthash(
 8691:              'yes'       => 'with submissions',
 8692:              'queued'    => 'in grading queue',
 8693:              'graded'    => 'with ungraded submissions',
 8694:              'incorrect' => 'with incorrect submissions',
 8695:              'all'       => 'with any status'),
 8696:              'select_form_order' => ['yes','queued','graded','incorrect','all'])).
 8697:    '</fieldset>';
 8698:     }
 8699:     $result.='</div><br />';
 8700:     return $result;
 8701: }
 8702: 
 8703: sub reset_perm {
 8704:     undef(%perm);
 8705: }
 8706: 
 8707: sub init_perm {
 8708:     &reset_perm();
 8709:     foreach my $test_perm ('vgr','mgr','opa') {
 8710: 
 8711: 	my $scope = $env{'request.course.id'};
 8712: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 8713: 
 8714: 	    $scope .= '/'.$env{'request.course.sec'};
 8715: 	    if ( $perm{$test_perm}=
 8716: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 8717: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 8718: 	    } else {
 8719: 		delete($perm{$test_perm});
 8720: 	    }
 8721: 	}
 8722:     }
 8723: }
 8724: 
 8725: sub gather_clicker_ids {
 8726:     my %clicker_ids;
 8727: 
 8728:     my $classlist = &Apache::loncoursedata::get_classlist();
 8729: 
 8730:     # Set up a couple variables.
 8731:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 8732:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 8733:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 8734: 
 8735:     foreach my $student (keys(%$classlist)) {
 8736:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 8737:         my $username = $classlist->{$student}->[$username_idx];
 8738:         my $domain   = $classlist->{$student}->[$domain_idx];
 8739:         my $clickers =
 8740: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 8741:         foreach my $id (split(/\,/,$clickers)) {
 8742:             $id=~s/^[\#0]+//;
 8743:             $id=~s/[\-\:]//g;
 8744:             if (exists($clicker_ids{$id})) {
 8745: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 8746:             } else {
 8747: 		$clicker_ids{$id}=$username.':'.$domain;
 8748:             }
 8749:         }
 8750:     }
 8751:     return %clicker_ids;
 8752: }
 8753: 
 8754: sub gather_adv_clicker_ids {
 8755:     my %clicker_ids;
 8756:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 8757:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8758:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 8759:     foreach my $element (sort(keys(%coursepersonnel))) {
 8760:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 8761:             my ($puname,$pudom)=split(/\:/,$person);
 8762:             my $clickers =
 8763: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 8764:             foreach my $id (split(/\,/,$clickers)) {
 8765: 		$id=~s/^[\#0]+//;
 8766:                 $id=~s/[\-\:]//g;
 8767: 		if (exists($clicker_ids{$id})) {
 8768: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 8769: 		} else {
 8770: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 8771: 		}
 8772:             }
 8773:         }
 8774:     }
 8775:     return %clicker_ids;
 8776: }
 8777: 
 8778: sub clicker_grading_parameters {
 8779:     return ('gradingmechanism' => 'scalar',
 8780:             'upfiletype' => 'scalar',
 8781:             'specificid' => 'scalar',
 8782:             'pcorrect' => 'scalar',
 8783:             'pincorrect' => 'scalar');
 8784: }
 8785: 
 8786: sub process_clicker {
 8787:     my ($r)=@_;
 8788:     my ($symb)=&get_symb($r);
 8789:     if (!$symb) {return '';}
 8790:     my $result=&checkforfile_js();
 8791:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 8792:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 8793:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
 8794:         '</b></td></tr>'."\n";
 8795:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
 8796: # Attempt to restore parameters from last session, set defaults if not present
 8797:     my %Saveable_Parameters=&clicker_grading_parameters();
 8798:     &Apache::loncommon::restore_course_settings('grades_clicker',
 8799:                                                  \%Saveable_Parameters);
 8800:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 8801:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 8802:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 8803:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 8804: 
 8805:     my %checked;
 8806:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 8807:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 8808:           $checked{$gradingmechanism}=' checked="checked"';
 8809:        }
 8810:     }
 8811: 
 8812:     my $upload=&mt("Upload File");
 8813:     my $type=&mt("Type");
 8814:     my $attendance=&mt("Award points just for participation");
 8815:     my $personnel=&mt("Correctness determined from response by course personnel");
 8816:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 8817:     my $given=&mt("Correctness determined from given list of answers").' '.
 8818:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 8819:     my $pcorrect=&mt("Percentage points for correct solution");
 8820:     my $pincorrect=&mt("Percentage points for incorrect solution");
 8821:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 8822: 						   ('iclicker' => 'i>clicker',
 8823:                                                     'interwrite' => 'interwrite PRS'));
 8824:     $symb = &Apache::lonenc::check_encrypt($symb);
 8825:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
 8826: function sanitycheck() {
 8827: // Accept only integer percentages
 8828:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 8829:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 8830: // Find out grading choice
 8831:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8832:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 8833:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 8834:       }
 8835:    }
 8836: // By default, new choice equals user selection
 8837:    newgradingchoice=gradingchoice;
 8838: // Not good to give more points for false answers than correct ones
 8839:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 8840:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 8841:    }
 8842: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 8843:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 8844:       document.forms.gradesupload.pcorrect.value=100;
 8845:       document.forms.gradesupload.pincorrect.value=100;
 8846:    }
 8847: // If the values are different, cannot be attendance only
 8848:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 8849:        (gradingchoice=='attendance')) {
 8850:        newgradingchoice='personnel';
 8851:    }
 8852: // Change grading choice to new one
 8853:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8854:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 8855:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 8856:       } else {
 8857:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 8858:       }
 8859:    }
 8860: // Remember the old state
 8861:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 8862: }
 8863: ENDUPFORM
 8864:     $result.= <<ENDUPFORM;
 8865: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 8866: <input type="hidden" name="symb" value="$symb" />
 8867: <input type="hidden" name="command" value="processclickerfile" />
 8868: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 8869: <input type="file" name="upfile" size="50" />
 8870: <br /><label>$type: $selectform</label>
 8871: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
 8872: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
 8873: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
 8874: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 8875: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
 8876: <br />&nbsp;&nbsp;&nbsp;
 8877: <input type="text" name="givenanswer" size="50" />
 8878: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 8879: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
 8880: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
 8881: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 8882: </form>'
 8883: ENDUPFORM
 8884:     $result.='</td></tr></table>'."\n".
 8885:              '</td></tr></table><br /><br />'."\n";
 8886:     $result.=&show_grading_menu_form($symb);
 8887:     return $result;
 8888: }
 8889: 
 8890: sub process_clicker_file {
 8891:     my ($r)=@_;
 8892:     my ($symb)=&get_symb($r);
 8893:     if (!$symb) {return '';}
 8894: 
 8895:     my %Saveable_Parameters=&clicker_grading_parameters();
 8896:     &Apache::loncommon::store_course_settings('grades_clicker',
 8897:                                               \%Saveable_Parameters);
 8898:     my $result='';
 8899:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 8900: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 8901: 	return $result.&show_grading_menu_form($symb);
 8902:     }
 8903:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 8904:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 8905:         return $result.&show_grading_menu_form($symb);
 8906:     }
 8907:     my $foundgiven=0;
 8908:     if ($env{'form.gradingmechanism'} eq 'given') {
 8909:         $env{'form.givenanswer'}=~s/^\s*//gs;
 8910:         $env{'form.givenanswer'}=~s/\s*$//gs;
 8911:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
 8912:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 8913:         my @answers=split(/\,/,$env{'form.givenanswer'});
 8914:         $foundgiven=$#answers+1;
 8915:     }
 8916:     my %clicker_ids=&gather_clicker_ids();
 8917:     my %correct_ids;
 8918:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 8919: 	%correct_ids=&gather_adv_clicker_ids();
 8920:     }
 8921:     if ($env{'form.gradingmechanism'} eq 'specific') {
 8922: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 8923: 	   $correct_id=~tr/a-z/A-Z/;
 8924: 	   $correct_id=~s/\s//gs;
 8925: 	   $correct_id=~s/^[\#0]+//;
 8926:            $correct_id=~s/[\-\:]//g;
 8927:            if ($correct_id) {
 8928: 	      $correct_ids{$correct_id}='specified';
 8929:            }
 8930:         }
 8931:     }
 8932:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 8933: 	$result.=&mt('Score based on attendance only');
 8934:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
 8935:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
 8936:     } else {
 8937: 	my $number=0;
 8938: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 8939: 	foreach my $id (sort(keys(%correct_ids))) {
 8940: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 8941: 	    if ($correct_ids{$id} eq 'specified') {
 8942: 		$result.=&mt('specified');
 8943: 	    } else {
 8944: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 8945: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 8946: 	    }
 8947: 	    $number++;
 8948: 	}
 8949:         $result.="</p>\n";
 8950: 	if ($number==0) {
 8951: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
 8952: 	    return $result.&show_grading_menu_form($symb);
 8953: 	}
 8954:     }
 8955:     if (length($env{'form.upfile'}) < 2) {
 8956:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
 8957: 		     '<span class="LC_error">',
 8958: 		     '</span>',
 8959: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
 8960:         return $result.&show_grading_menu_form($symb);
 8961:     }
 8962: 
 8963: # Were able to get all the info needed, now analyze the file
 8964: 
 8965:     $result.=&Apache::loncommon::studentbrowser_javascript();
 8966:     $symb = &Apache::lonenc::check_encrypt($symb);
 8967:     my $heading=&mt('Scanning clicker file');
 8968:     $result.=(<<ENDHEADER);
 8969: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 8970: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 8971: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 8972: <form method="post" action="/adm/grades" name="clickeranalysis">
 8973: <input type="hidden" name="symb" value="$symb" />
 8974: <input type="hidden" name="command" value="assignclickergrades" />
 8975: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 8976: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 8977: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 8978: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 8979: ENDHEADER
 8980:     if ($env{'form.gradingmechanism'} eq 'given') {
 8981:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
 8982:     } 
 8983:     my %responses;
 8984:     my @questiontitles;
 8985:     my $errormsg='';
 8986:     my $number=0;
 8987:     if ($env{'form.upfiletype'} eq 'iclicker') {
 8988: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 8989:     }
 8990:     if ($env{'form.upfiletype'} eq 'interwrite') {
 8991:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 8992:     }
 8993:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 8994:              '<input type="hidden" name="number" value="'.$number.'" />'.
 8995:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 8996:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 8997:              '<br />';
 8998:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
 8999:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
 9000:        return $result.&show_grading_menu_form($symb);
 9001:     } 
 9002: # Remember Question Titles
 9003: # FIXME: Possibly need delimiter other than ":"
 9004:     for (my $i=0;$i<$number;$i++) {
 9005:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 9006:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 9007:     }
 9008:     my $correct_count=0;
 9009:     my $student_count=0;
 9010:     my $unknown_count=0;
 9011: # Match answers with usernames
 9012: # FIXME: Possibly need delimiter other than ":"
 9013:     foreach my $id (keys(%responses)) {
 9014:        if ($correct_ids{$id}) {
 9015:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 9016:           $correct_count++;
 9017:        } elsif ($clicker_ids{$id}) {
 9018:           if ($clicker_ids{$id}=~/\,/) {
 9019: # More than one user with the same clicker!
 9020:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 9021:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9022:                            "<select name='multi".$id."'>";
 9023:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 9024:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 9025:              }
 9026:              $result.='</select>';
 9027:              $unknown_count++;
 9028:           } else {
 9029: # Good: found one and only one user with the right clicker
 9030:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 9031:              $student_count++;
 9032:           }
 9033:        } else {
 9034:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 9035:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9036:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 9037:                    "\n".&mt("Domain").": ".
 9038:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 9039:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
 9040:           $unknown_count++;
 9041:        }
 9042:     }
 9043:     $result.='<hr />'.
 9044:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 9045:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
 9046:        if ($correct_count==0) {
 9047:           $errormsg.="Found no correct answers answers for grading!";
 9048:        } elsif ($correct_count>1) {
 9049:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 9050:        }
 9051:     }
 9052:     if ($number<1) {
 9053:        $errormsg.="Found no questions.";
 9054:     }
 9055:     if ($errormsg) {
 9056:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 9057:     } else {
 9058:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 9059:     }
 9060:     $result.='</form></td></tr></table>'."\n".
 9061:              '</td></tr></table><br /><br />'."\n";
 9062:     return $result.&show_grading_menu_form($symb);
 9063: }
 9064: 
 9065: sub iclicker_eval {
 9066:     my ($questiontitles,$responses)=@_;
 9067:     my $number=0;
 9068:     my $errormsg='';
 9069:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9070:         my %components=&Apache::loncommon::record_sep($line);
 9071:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9072: 	if ($entries[0] eq 'Question') {
 9073: 	    for (my $i=3;$i<$#entries;$i+=6) {
 9074: 		$$questiontitles[$number]=$entries[$i];
 9075: 		$number++;
 9076: 	    }
 9077: 	}
 9078: 	if ($entries[0]=~/^\#/) {
 9079: 	    my $id=$entries[0];
 9080: 	    my @idresponses;
 9081: 	    $id=~s/^[\#0]+//;
 9082: 	    for (my $i=0;$i<$number;$i++) {
 9083: 		my $idx=3+$i*6;
 9084: 		push(@idresponses,$entries[$idx]);
 9085: 	    }
 9086: 	    $$responses{$id}=join(',',@idresponses);
 9087: 	}
 9088:     }
 9089:     return ($errormsg,$number);
 9090: }
 9091: 
 9092: sub interwrite_eval {
 9093:     my ($questiontitles,$responses)=@_;
 9094:     my $number=0;
 9095:     my $errormsg='';
 9096:     my $skipline=1;
 9097:     my $questionnumber=0;
 9098:     my %idresponses=();
 9099:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9100:         my %components=&Apache::loncommon::record_sep($line);
 9101:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9102:         if ($entries[1] eq 'Time') { $skipline=0; next; }
 9103:         if ($entries[1] eq 'Response') { $skipline=1; }
 9104:         next if $skipline;
 9105:         if ($entries[0]!=$questionnumber) {
 9106:            $questionnumber=$entries[0];
 9107:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
 9108:            $number++;
 9109:         }
 9110:         my $id=$entries[4];
 9111:         $id=~s/^[\#0]+//;
 9112:         $id=~s/^v\d*\://i;
 9113:         $id=~s/[\-\:]//g;
 9114:         $idresponses{$id}[$number]=$entries[6];
 9115:     }
 9116:     foreach my $id (keys(%idresponses)) {
 9117:        $$responses{$id}=join(',',@{$idresponses{$id}});
 9118:        $$responses{$id}=~s/^\s*\,//;
 9119:     }
 9120:     return ($errormsg,$number);
 9121: }
 9122: 
 9123: sub assign_clicker_grades {
 9124:     my ($r)=@_;
 9125:     my ($symb)=&get_symb($r);
 9126:     if (!$symb) {return '';}
 9127: # See which part we are saving to
 9128:     my $res_error;
 9129:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 9130:     if ($res_error) {
 9131:         return &navmap_errormsg();
 9132:     }
 9133: # FIXME: This should probably look for the first handgradeable part
 9134:     my $part=$$partlist[0];
 9135: # Start screen output
 9136:     my $result='';
 9137: 
 9138:     my $heading=&mt('Assigning grades based on clicker file');
 9139:     $result.=(<<ENDHEADER);
 9140: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 9141: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 9142: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 9143: ENDHEADER
 9144: # Get correct result
 9145: # FIXME: Possibly need delimiter other than ":"
 9146:     my @correct=();
 9147:     my $gradingmechanism=$env{'form.gradingmechanism'};
 9148:     my $number=$env{'form.number'};
 9149:     if ($gradingmechanism ne 'attendance') {
 9150:        foreach my $key (keys(%env)) {
 9151:           if ($key=~/^form\.correct\:/) {
 9152:              my @input=split(/\,/,$env{$key});
 9153:              for (my $i=0;$i<=$#input;$i++) {
 9154:                  if (($correct[$i]) && ($input[$i]) &&
 9155:                      ($correct[$i] ne $input[$i])) {
 9156:                     $result.='<br /><span class="LC_warning">'.
 9157:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
 9158:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
 9159:                  } elsif ($input[$i]) {
 9160:                     $correct[$i]=$input[$i];
 9161:                  }
 9162:              }
 9163:           }
 9164:        }
 9165:        for (my $i=0;$i<$number;$i++) {
 9166:           if (!$correct[$i]) {
 9167:              $result.='<br /><span class="LC_error">'.
 9168:                       &mt('No correct result given for question "[_1]"!',
 9169:                           $env{'form.question:'.$i}).'</span>';
 9170:           }
 9171:        }
 9172:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
 9173:     }
 9174: # Start grading
 9175:     my $pcorrect=$env{'form.pcorrect'};
 9176:     my $pincorrect=$env{'form.pincorrect'};
 9177:     my $storecount=0;
 9178:     foreach my $key (keys(%env)) {
 9179:        my $user='';
 9180:        if ($key=~/^form\.student\:(.*)$/) {
 9181:           $user=$1;
 9182:        }
 9183:        if ($key=~/^form\.unknown\:(.*)$/) {
 9184:           my $id=$1;
 9185:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
 9186:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
 9187:           } elsif ($env{'form.multi'.$id}) {
 9188:              $user=$env{'form.multi'.$id};
 9189:           }
 9190:        }
 9191:        if ($user) { 
 9192:           my @answer=split(/\,/,$env{$key});
 9193:           my $sum=0;
 9194:           my $realnumber=$number;
 9195:           for (my $i=0;$i<$number;$i++) {
 9196:              if  ($correct[$i] eq '-') {
 9197:                 $realnumber--;
 9198:              } elsif ($answer[$i]) {
 9199:                 if ($gradingmechanism eq 'attendance') {
 9200:                    $sum+=$pcorrect;
 9201:                 } elsif ($correct[$i] eq '*') {
 9202:                    $sum+=$pcorrect;
 9203:                 } else {
 9204:                    if ($answer[$i] eq $correct[$i]) {
 9205:                       $sum+=$pcorrect;
 9206:                    } else {
 9207:                       $sum+=$pincorrect;
 9208:                    }
 9209:                 }
 9210:              }
 9211:           }
 9212:           my $ave=$sum/(100*$realnumber);
 9213: # Store
 9214:           my ($username,$domain)=split(/\:/,$user);
 9215:           my %grades=();
 9216:           $grades{"resource.$part.solved"}='correct_by_override';
 9217:           $grades{"resource.$part.awarded"}=$ave;
 9218:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 9219:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
 9220:                                                  $env{'request.course.id'},
 9221:                                                  $domain,$username);
 9222:           if ($returncode ne 'ok') {
 9223:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
 9224:           } else {
 9225:              $storecount++;
 9226:           }
 9227:        }
 9228:     }
 9229: # We are done
 9230:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
 9231:              '</td></tr></table>'."\n".
 9232:              '</td></tr></table><br /><br />'."\n";
 9233:     return $result.&show_grading_menu_form($symb);
 9234: }
 9235: 
 9236: sub navmap_errormsg {
 9237:     return '<div class="LC_error">'.
 9238:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
 9239:            &mt('It is recommended that you [_1]re-initialize the course[_2] and then return to this grading page.','<a href="/adm/roles?selectrole=1&newrole='.$env{'request.role'}.'">','</a>').
 9240:            '</div>';
 9241: }
 9242: sub startpage{
 9243:     my ($r,$crumbs) = @_;
 9244: 
 9245:     unshift(@$crumbs,  {href=>"/adm/grades",text=>"Grading"});
 9246:     $r->print(&Apache::loncommon::start_page('Grading',undef,
 9247:                                           {'bread_crumbs' => $crumbs}));
 9248: }
 9249: 
 9250: sub handler {
 9251:     my $request=$_[0];
 9252:     &reset_caches();
 9253:     if ($env{'browser.mathml'}) {
 9254: 	&Apache::loncommon::content_type($request,'text/xml');
 9255:     } else {
 9256: 	&Apache::loncommon::content_type($request,'text/html');
 9257:     }
 9258:     $request->send_http_header;
 9259:     return '' if $request->header_only;
 9260:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
 9261:     my $symb=&get_symb($request,1);
 9262:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
 9263:     my $command=$commands[0];
 9264: 
 9265:     if ($#commands > 0) {
 9266: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
 9267:     }
 9268:                              
 9269:     $ssi_error = 0;
 9270:     if ($symb eq '' && $command eq '') {
 9271: #
 9272: # Not called from a resource
 9273: #    
 9274: 
 9275:     } else {
 9276: 	&init_perm();
 9277: 	if ($command eq 'submission' && $perm{'vgr'}) {
 9278:         &startpage($request, [{href=>"", text=>"Student Submissions"}]);
 9279: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
 9280: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
 9281: 	    &pickStudentPage($request);
 9282: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
 9283: 	    &displayPage($request);
 9284: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
 9285: 	    &updateGradeByPage($request);
 9286: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
 9287: 	    &processGroup($request);
 9288: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
 9289:         &startpage($request);
 9290: 	    $request->print(&grading_menu($request));
 9291: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
 9292: 	    $request->print(&submit_options($request));
 9293:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
 9294:             $request->print(&submit_options($request));
 9295:         } elsif ($command eq 'table' && $perm{'vgr'}) {
 9296:             $request->print(&submit_options_table($request));
 9297:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
 9298:             $request->print(&submit_options_sequence($request));
 9299: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
 9300: 	    $request->print(&viewgrades($request));
 9301: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
 9302: 	    $request->print(&processHandGrade($request));
 9303: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
 9304: 	    $request->print(&editgrades($request));
 9305:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
 9306:             $request->print(&initialverifyreceipt($request));
 9307: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
 9308: 	    $request->print(&verifyreceipt($request));
 9309:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
 9310:             $request->print(&process_clicker($request));
 9311:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
 9312:             $request->print(&process_clicker_file($request));
 9313:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
 9314:             $request->print(&assign_clicker_grades($request));
 9315: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
 9316: 	    $request->print(&upcsvScores_form($request));
 9317: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
 9318: 	    $request->print(&csvupload($request));
 9319: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
 9320: 	    $request->print(&csvuploadmap($request));
 9321: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
 9322: 	    if ($env{'form.associate'} ne 'Reverse Association') {
 9323: 		$request->print(&csvuploadoptions($request));
 9324: 	    } else {
 9325: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
 9326: 		    $env{'form.upfile_associate'} = 'reverse';
 9327: 		} else {
 9328: 		    $env{'form.upfile_associate'} = 'forward';
 9329: 		}
 9330: 		$request->print(&csvuploadmap($request));
 9331: 	    }
 9332: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
 9333: 	    $request->print(&csvuploadassign($request));
 9334: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
 9335: 	    $request->print(&scantron_selectphase($request));
 9336:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
 9337:  	    $request->print(&scantron_do_warning($request));
 9338: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
 9339: 	    $request->print(&scantron_validate_file($request));
 9340: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
 9341: 	    $request->print(&scantron_process_students($request));
 9342:  	} elsif ($command eq 'scantronupload' && 
 9343:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9344: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9345:  	    $request->print(&scantron_upload_scantron_data($request)); 
 9346:  	} elsif ($command eq 'scantronupload_save' &&
 9347:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9348: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9349:  	    $request->print(&scantron_upload_scantron_data_save($request));
 9350:  	} elsif ($command eq 'scantron_download' &&
 9351: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 9352:  	    $request->print(&scantron_download_scantron_data($request));
 9353:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
 9354:             $request->print(&checkscantron_results($request));     
 9355: 	} elsif ($command) {
 9356: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
 9357: 	}
 9358:     }
 9359:     if ($ssi_error) {
 9360: 	&ssi_print_error($request);
 9361:     }
 9362:     $request->print(&Apache::loncommon::end_page());
 9363:     &reset_caches();
 9364:     return '';
 9365: }
 9366: 
 9367: 1;
 9368: 
 9369: __END__;
 9370: 
 9371: 
 9372: =head1 NAME
 9373: 
 9374: Apache::grades
 9375: 
 9376: =head1 SYNOPSIS
 9377: 
 9378: Handles the viewing of grades.
 9379: 
 9380: This is part of the LearningOnline Network with CAPA project
 9381: described at http://www.lon-capa.org.
 9382: 
 9383: =head1 OVERVIEW
 9384: 
 9385: Do an ssi with retries:
 9386: While I'd love to factor out this with the vesrion in lonprintout,
 9387: that would either require a data coupling between modules, which I refuse to perpetuate (there's quite enough of that already), or would require the invention of another infrastructure
 9388: I'm not quite ready to invent (e.g. an ssi_with_retry object).
 9389: 
 9390: At least the logic that drives this has been pulled out into loncommon.
 9391: 
 9392: 
 9393: 
 9394: ssi_with_retries - Does the server side include of a resource.
 9395:                      if the ssi call returns an error we'll retry it up to
 9396:                      the number of times requested by the caller.
 9397:                      If we still have a proble, no text is appended to the
 9398:                      output and we set some global variables.
 9399:                      to indicate to the caller an SSI error occurred.  
 9400:                      All of this is supposed to deal with the issues described
 9401:                      in LonCAPA BZ 5631 see:
 9402:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
 9403:                      by informing the user that this happened.
 9404: 
 9405: Parameters:
 9406:   resource   - The resource to include.  This is passed directly, without
 9407:                interpretation to lonnet::ssi.
 9408:   form       - The form hash parameters that guide the interpretation of the resource
 9409:                
 9410:   retries    - Number of retries allowed before giving up completely.
 9411: Returns:
 9412:   On success, returns the rendered resource identified by the resource parameter.
 9413: Side Effects:
 9414:   The following global variables can be set:
 9415:    ssi_error                - If an unrecoverable error occurred this becomes true.
 9416:                               It is up to the caller to initialize this to false
 9417:                               if desired.
 9418:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
 9419:                               of the resource that could not be rendered by the ssi
 9420:                               call.
 9421:    ssi_error_message   - The error string fetched from the ssi response
 9422:                               in the event of an error.
 9423: 
 9424: 
 9425: =head1 HANDLER SUBROUTINE
 9426: 
 9427: ssi_with_retries()
 9428: 
 9429: =head1 SUBROUTINES
 9430: 
 9431: =over
 9432: 
 9433: =item scantron_get_correction() : 
 9434: 
 9435:    Builds the interface screen to interact with the operator to fix a
 9436:    specific error condition in a specific scanline
 9437: 
 9438:  Arguments:
 9439:     $r           - Apache request object
 9440:     $i           - number of the current scanline
 9441:     $scan_record - hash ref as returned from &scantron_parse_scanline()
 9442:     $scan_config - hash ref as returned from &get_scantron_config()
 9443:     $line        - full contents of the current scanline
 9444:     $error       - error condition, valid values are
 9445:                    'incorrectCODE', 'duplicateCODE',
 9446:                    'doublebubble', 'missingbubble',
 9447:                    'duplicateID', 'incorrectID'
 9448:     $arg         - extra information needed
 9449:        For errors:
 9450:          - duplicateID   - paper number that this studentID was seen before on
 9451:          - duplicateCODE - array ref of the paper numbers this CODE was
 9452:                            seen on before
 9453:          - incorrectCODE - current incorrect CODE 
 9454:          - doublebubble  - array ref of the bubble lines that have double
 9455:                            bubble errors
 9456:          - missingbubble - array ref of the bubble lines that have missing
 9457:                            bubble errors
 9458: 
 9459: =item  scantron_get_maxbubble() : 
 9460: 
 9461:    Arguments:
 9462:        $nav_error  - Reference to scalar which is a flag to indicate a
 9463:                       failure to retrieve a navmap object.
 9464:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
 9465:        calling routine should trap the error condition and display the warning
 9466:        found in &navmap_errormsg().
 9467: 
 9468:    Returns the maximum number of bubble lines that are expected to
 9469:    occur. Does this by walking the selected sequence rendering the
 9470:    resource and then checking &Apache::lonxml::get_problem_counter()
 9471:    for what the current value of the problem counter is.
 9472: 
 9473:    Caches the results to $env{'form.scantron_maxbubble'},
 9474:    $env{'form.scantron.bubble_lines.n'}, 
 9475:    $env{'form.scantron.first_bubble_line.n'} and
 9476:    $env{"form.scantron.sub_bubblelines.n"}
 9477:    which are the total number of bubble, lines, the number of bubble
 9478:    lines for response n and number of the first bubble line for response n,
 9479:    and a comma separated list of numbers of bubble lines for sub-questions
 9480:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
 9481: 
 9482: 
 9483: =item  scantron_validate_missingbubbles() : 
 9484: 
 9485:    Validates all scanlines in the selected file to not have any
 9486:     answers that don't have bubbles that have not been verified
 9487:     to be bubble free.
 9488: 
 9489: =item  scantron_process_students() : 
 9490: 
 9491:    Routine that does the actual grading of the bubble sheet information.
 9492: 
 9493:    The parsed scanline hash is added to %env 
 9494: 
 9495:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
 9496:    foreach resource , with the form data of
 9497: 
 9498: 	'submitted'     =>'scantron' 
 9499: 	'grade_target'  =>'grade',
 9500: 	'grade_username'=> username of student
 9501: 	'grade_domain'  => domain of student
 9502: 	'grade_courseid'=> of course
 9503: 	'grade_symb'    => symb of resource to grade
 9504: 
 9505:     This triggers a grading pass. The problem grading code takes care
 9506:     of converting the bubbled letter information (now in %env) into a
 9507:     valid submission.
 9508: 
 9509: =item  scantron_upload_scantron_data() :
 9510: 
 9511:     Creates the screen for adding a new bubble sheet data file to a course.
 9512: 
 9513: =item  scantron_upload_scantron_data_save() : 
 9514: 
 9515:    Adds a provided bubble information data file to the course if user
 9516:    has the correct privileges to do so. 
 9517: 
 9518: =item  valid_file() :
 9519: 
 9520:    Validates that the requested bubble data file exists in the course.
 9521: 
 9522: =item  scantron_download_scantron_data() : 
 9523: 
 9524:    Shows a list of the three internal files (original, corrected,
 9525:    skipped) for a specific bubble sheet data file that exists in the
 9526:    course.
 9527: 
 9528: =item  scantron_validate_ID() : 
 9529: 
 9530:    Validates all scanlines in the selected file to not have any
 9531:    invalid or underspecified student/employee IDs
 9532: 
 9533: =item navmap_errormsg() :
 9534: 
 9535:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
 9536:    Should be called whenever the request to instantiate a navmap object fails.  
 9537: 
 9538: =back
 9539: 
 9540: =cut

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