File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.653: download - view: text, annotated - select for diffs
Sat Oct 1 15:48:18 2011 UTC (12 years, 7 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Move html tags outside phrase to be translated.

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.653 2011/10/01 15:48:18 raeburn 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 :http);
   44: use Apache::lonlocal;
   45: use Apache::lonenc;
   46: use Apache::lonstathelpers;
   47: use Apache::lonquickgrades;
   48: use String::Similarity;
   49: use LONCAPA;
   50: 
   51: use POSIX qw(floor);
   52: 
   53: 
   54: 
   55: my %perm=();
   56: 
   57: #  These variables are used to recover from ssi errors
   58: 
   59: my $ssi_retries = 5;
   60: my $ssi_error;
   61: my $ssi_error_resource;
   62: my $ssi_error_message;
   63: 
   64: 
   65: sub ssi_with_retries {
   66:     my ($resource, $retries, %form) = @_;
   67:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
   68:     if ($response->is_error) {
   69: 	$ssi_error          = 1;
   70: 	$ssi_error_resource = $resource;
   71: 	$ssi_error_message  = $response->code . " " . $response->message;
   72:     }
   73: 
   74:     return $content;
   75: 
   76: }
   77: #
   78: #  Prodcuces an ssi retry failure error message to the user:
   79: #
   80: 
   81: sub ssi_print_error {
   82:     my ($r) = @_;
   83:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
   84:     $r->print('
   85: <br />
   86: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
   87: <p>
   88: '.&mt('Unable to retrieve a resource from a server:').'<br />
   89: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
   90: '.&mt('Error:').' '.$ssi_error_message.'
   91: </p>
   92: <p>'.
   93: &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 />'.
   94: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
   95: '</p>');
   96:     return;
   97: }
   98: 
   99: #
  100: # --- Retrieve the parts from the metadata file.---
  101: # Returns an array of everything that the resources stores away
  102: #
  103: 
  104: sub getpartlist {
  105:     my ($symb,$errorref) = @_;
  106: 
  107:     my $navmap   = Apache::lonnavmaps::navmap->new();
  108:     unless (ref($navmap)) {
  109:         if (ref($errorref)) { 
  110:             $$errorref = 'navmap';
  111:             return;
  112:         }
  113:     }
  114:     my $res      = $navmap->getBySymb($symb);
  115:     my $partlist = $res->parts();
  116:     my $url      = $res->src();
  117:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
  118: 
  119:     my @stores;
  120:     foreach my $part (@{ $partlist }) {
  121: 	foreach my $key (@metakeys) {
  122: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
  123: 	}
  124:     }
  125:     return @stores;
  126: }
  127: 
  128: #--- Format fullname, username:domain if different for display
  129: #--- Use anywhere where the student names are listed
  130: sub nameUserString {
  131:     my ($type,$fullname,$uname,$udom) = @_;
  132:     if ($type eq 'header') {
  133: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
  134:     } else {
  135: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
  136: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
  137:     }
  138: }
  139: 
  140: #--- Get the partlist and the response type for a given problem. ---
  141: #--- Indicate if a response type is coded handgraded or not. ---
  142: #--- Sets response_error pointer to "1" if navmaps object broken ---
  143: sub response_type {
  144:     my ($symb,$response_error) = @_;
  145: 
  146:     my $navmap = Apache::lonnavmaps::navmap->new();
  147:     unless (ref($navmap)) {
  148:         if (ref($response_error)) {
  149:             $$response_error = 1;
  150:         }
  151:         return;
  152:     }
  153:     my $res = $navmap->getBySymb($symb);
  154:     unless (ref($res)) {
  155:         $$response_error = 1;
  156:         return;
  157:     }
  158:     my $partlist = $res->parts();
  159:     my %vPart = 
  160: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
  161:     my (%response_types,%handgrade);
  162:     foreach my $part (@{ $partlist }) {
  163: 	next if (%vPart && !exists($vPart{$part}));
  164: 
  165: 	my @types = $res->responseType($part);
  166: 	my @ids = $res->responseIds($part);
  167: 	for (my $i=0; $i < scalar(@ids); $i++) {
  168: 	    $response_types{$part}{$ids[$i]} = $types[$i];
  169: 	    $handgrade{$part.'_'.$ids[$i]} = 
  170: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
  171: 				     '.handgrade',$symb);
  172: 	}
  173:     }
  174:     return ($partlist,\%handgrade,\%response_types);
  175: }
  176: 
  177: sub flatten_responseType {
  178:     my ($responseType) = @_;
  179:     my @part_response_id =
  180: 	map { 
  181: 	    my $part = $_;
  182: 	    map {
  183: 		[$part,$_]
  184: 		} sort(keys(%{ $responseType->{$part} }));
  185: 	} sort(keys(%$responseType));
  186:     return @part_response_id;
  187: }
  188: 
  189: sub get_display_part {
  190:     my ($partID,$symb)=@_;
  191:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
  192:     if (defined($display) and $display ne '') {
  193:         $display.= ' (<span class="LC_internal_info">'
  194:                   .&mt('Part ID: [_1]',$partID).'</span>)';
  195:     } else {
  196: 	$display=$partID;
  197:     }
  198:     return $display;
  199: }
  200: 
  201: sub reset_caches {
  202:     &reset_analyze_cache();
  203:     &reset_perm();
  204: }
  205: 
  206: {
  207:     my %analyze_cache;
  208:     my %analyze_cache_formkeys;
  209: 
  210:     sub reset_analyze_cache {
  211: 	undef(%analyze_cache);
  212:         undef(%analyze_cache_formkeys);
  213:     }
  214: 
  215:     sub get_analyze {
  216: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
  217: 	my $key = "$symb\0$uname\0$udom";
  218:         if ($type eq 'randomizetry') {
  219:             if ($trial ne '') {
  220:                 $key .= "\0".$trial;
  221:             }
  222:         }
  223: 	if (exists($analyze_cache{$key})) {
  224:             my $getupdate = 0;
  225:             if (ref($add_to_hash) eq 'HASH') {
  226:                 foreach my $item (keys(%{$add_to_hash})) {
  227:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
  228:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
  229:                             $getupdate = 1;
  230:                             last;
  231:                         }
  232:                     } else {
  233:                         $getupdate = 1;
  234:                     }
  235:                 }
  236:             }
  237:             if (!$getupdate) {
  238:                 return $analyze_cache{$key};
  239:             }
  240:         }
  241: 
  242: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  243: 	$url=&Apache::lonnet::clutter($url);
  244:         my %form = ('grade_target'      => 'analyze',
  245:                     'grade_domain'      => $udom,
  246:                     'grade_symb'        => $symb,
  247:                     'grade_courseid'    =>  $env{'request.course.id'},
  248:                     'grade_username'    => $uname,
  249:                     'grade_noincrement' => $no_increment);
  250:         if ($bubbles_per_row ne '') {
  251:             $form{'bubbles_per_row'} = $bubbles_per_row;
  252:         }
  253:         if ($type eq 'randomizetry') {
  254:             $form{'grade_questiontype'} = $type;
  255:             if ($rndseed ne '') {
  256:                 $form{'grade_rndseed'} = $rndseed;
  257:             }
  258:         }
  259:         if (ref($add_to_hash)) {
  260:             %form = (%form,%{$add_to_hash});
  261:         }
  262: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
  263: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  264: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  265:         if (ref($add_to_hash) eq 'HASH') {
  266:             $analyze_cache_formkeys{$key} = $add_to_hash;
  267:         } else {
  268:             $analyze_cache_formkeys{$key} = {};
  269:         }
  270: 	return $analyze_cache{$key} = \%analyze;
  271:     }
  272: 
  273:     sub get_order {
  274: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
  275: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
  276: 	return $analyze->{"$partid.$respid.shown"};
  277:     }
  278: 
  279:     sub get_radiobutton_correct_foil {
  280: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
  281: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
  282:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
  283:         if (ref($foils) eq 'ARRAY') {
  284: 	    foreach my $foil (@{$foils}) {
  285: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  286: 		    return $foil;
  287: 	        }
  288: 	    }
  289: 	}
  290:     }
  291: 
  292:     sub scantron_partids_tograde {
  293:         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row) = @_;
  294:         my (%analysis,@parts);
  295:         if (ref($resource)) {
  296:             my $symb = $resource->symb();
  297:             my $add_to_form;
  298:             if ($check_for_randomlist) {
  299:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
  300:             }
  301:             my $analyze = 
  302:                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
  303:                              undef,undef,undef,$bubbles_per_row);
  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,$type,$trial,$rndseed) = @_;
  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,$type,$trial,$rndseed);
  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="Status"  value="'.$stu_status.'" />'."\n".
  640: 	'<input type="hidden" name="command" value="submission" />'."\n".
  641: 	'<input type="hidden" name="student" value="" />'."\n".
  642: 	'<input type="hidden" name="userdom" value="" />'."\n".
  643: 	'</form>'."\n";
  644:     return $jscript;
  645: }
  646: 
  647: 
  648: 
  649: # Given the score (as a number [0-1] and the weight) what is the final
  650: # point value? This function will round to the nearest tenth, third,
  651: # or quarter if one of those is within the tolerance of .00001.
  652: sub compute_points {
  653:     my ($score, $weight) = @_;
  654:     
  655:     my $tolerance = .00001;
  656:     my $points = $score * $weight;
  657: 
  658:     # Check for nearness to 1/x.
  659:     my $check_for_nearness = sub {
  660:         my ($factor) = @_;
  661:         my $num = ($points * $factor) + $tolerance;
  662:         my $floored_num = floor($num);
  663:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  664:             return $floored_num / $factor;
  665:         }
  666:         return $points;
  667:     };
  668: 
  669:     $points = $check_for_nearness->(10);
  670:     $points = $check_for_nearness->(3);
  671:     $points = $check_for_nearness->(4);
  672:     
  673:     return $points;
  674: }
  675: 
  676: #------------------ End of general use routines --------------------
  677: 
  678: #
  679: # Find most similar essay
  680: #
  681: 
  682: sub most_similar {
  683:     my ($uname,$udom,$uessay,$old_essays)=@_;
  684: 
  685: # ignore spaces and punctuation
  686: 
  687:     $uessay=~s/\W+/ /gs;
  688: 
  689: # ignore empty submissions (occuring when only files are sent)
  690: 
  691:     unless ($uessay=~/\w+/s) { return ''; }
  692: 
  693: # these will be returned. Do not care if not at least 50 percent similar
  694:     my $limit=0.6;
  695:     my $sname='';
  696:     my $sdom='';
  697:     my $scrsid='';
  698:     my $sessay='';
  699: # go through all essays ...
  700:     foreach my $tkey (keys(%$old_essays)) {
  701: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  702: # ... except the same student
  703:         next if (($tname eq $uname) && ($tdom eq $udom));
  704: 	my $tessay=$old_essays->{$tkey};
  705: 	$tessay=~s/\W+/ /gs;
  706: # String similarity gives up if not even limit
  707: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  708: # Found one
  709: 	if ($tsimilar>$limit) {
  710: 	    $limit=$tsimilar;
  711: 	    $sname=$tname;
  712: 	    $sdom=$tdom;
  713: 	    $scrsid=$tcrsid;
  714: 	    $sessay=$old_essays->{$tkey};
  715: 	}
  716:     }
  717:     if ($limit>0.6) {
  718:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  719:     } else {
  720:        return ('','','','',0);
  721:     }
  722: }
  723: 
  724: #-------------------------------------------------------------------
  725: 
  726: #------------------------------------ Receipt Verification Routines
  727: #
  728: 
  729: sub initialverifyreceipt {
  730:    my ($request,$symb) = @_;
  731:    &commonJSfunctions($request);
  732:    return '<form name="gradingMenu"><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
  733:         &Apache::lonnet::recprefix($env{'request.course.id'}).
  734:         '-<input type="text" name="receipt" size="4" />'.
  735:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  736:         '<input type="hidden" name="command" value="verify" />'.
  737:         "</form>\n";
  738: }
  739: 
  740: #--- Check whether a receipt number is valid.---
  741: sub verifyreceipt {
  742:     my ($request,$symb)  = @_;
  743: 
  744:     my $courseid = $env{'request.course.id'};
  745:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  746: 	$env{'form.receipt'};
  747:     $receipt     =~ s/[^\-\d]//g;
  748: 
  749:     my $title.=
  750: 	'<h3><span class="LC_info">'.
  751: 	&mt('Verifying Receipt Number [_1]',$receipt).
  752: 	'</span></h3>'."\n";
  753: 
  754:     my ($string,$contents,$matches) = ('','',0);
  755:     my (undef,undef,$fullname) = &getclasslist('all','0');
  756:     
  757:     my $receiptparts=0;
  758:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  759: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  760:     my $parts=['0'];
  761:     if ($receiptparts) {
  762:         my $res_error; 
  763:         ($parts)=&response_type($symb,\$res_error);
  764:         if ($res_error) {
  765:             return &navmap_errormsg();
  766:         } 
  767:     }
  768:     
  769:     my $header = 
  770: 	&Apache::loncommon::start_data_table().
  771: 	&Apache::loncommon::start_data_table_header_row().
  772: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  773: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  774: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  775:     if ($receiptparts) {
  776: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  777:     }
  778:     $header.=
  779: 	&Apache::loncommon::end_data_table_header_row();
  780: 
  781:     foreach (sort 
  782: 	     {
  783: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  784: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  785: 		 }
  786: 		 return $a cmp $b;
  787: 	     } (keys(%$fullname))) {
  788: 	my ($uname,$udom)=split(/\:/);
  789: 	foreach my $part (@$parts) {
  790: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  791: 		$contents.=
  792: 		    &Apache::loncommon::start_data_table_row().
  793: 		    '<td>&nbsp;'."\n".
  794: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  795: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  796: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  797: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  798: 		if ($receiptparts) {
  799: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  800: 		}
  801: 		$contents.= 
  802: 		    &Apache::loncommon::end_data_table_row()."\n";
  803: 		
  804: 		$matches++;
  805: 	    }
  806: 	}
  807:     }
  808:     if ($matches == 0) {
  809:         $string = $title
  810:                  .'<p class="LC_warning">'
  811:                  .&mt('No match found for the above receipt number.')
  812:                  .'</p>';
  813:     } else {
  814: 	$string = &jscriptNform($symb).$title.
  815: 	    '<p>'.
  816: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
  817: 	    '</p>'.
  818: 	    $header.
  819: 	    $contents.
  820: 	    &Apache::loncommon::end_data_table()."\n";
  821:     }
  822:     return $string;
  823: }
  824: 
  825: #--- This is called by a number of programs.
  826: #--- Called from the Grading Menu - View/Grade an individual student
  827: #--- Also called directly when one clicks on the subm button 
  828: #    on the problem page.
  829: sub listStudents {
  830:     my ($request,$symb,$submitonly) = @_;
  831: 
  832:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  833:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  834:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  835:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  836:     unless ($submitonly) {
  837:        $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  838:     }
  839: 
  840:     my $result='';
  841:     my $res_error;
  842:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
  843: 
  844:     my %lt = &Apache::lonlocal::texthash (
  845: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
  846: 		'single'   => 'Please select the student before clicking on the Next button.',
  847: 	     );
  848:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
  849:     function checkSelect(checkBox) {
  850: 	var ctr=0;
  851: 	var sense="";
  852: 	if (checkBox.length > 1) {
  853: 	    for (var i=0; i<checkBox.length; i++) {
  854: 		if (checkBox[i].checked) {
  855: 		    ctr++;
  856: 		}
  857: 	    }
  858: 	    sense = '$lt{'multiple'}';
  859: 	} else {
  860: 	    if (checkBox.checked) {
  861: 		ctr = 1;
  862: 	    }
  863: 	    sense = '$lt{'single'}';
  864: 	}
  865: 	if (ctr == 0) {
  866: 	    alert(sense);
  867: 	    return false;
  868: 	}
  869: 	document.gradesub.submit();
  870:     }
  871: 
  872:     function reLoadList(formname) {
  873: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  874: 	formname.command.value = 'submission';
  875: 	formname.submit();
  876:     }
  877: LISTJAVASCRIPT
  878: 
  879:     &commonJSfunctions($request);
  880:     $request->print($result);
  881: 
  882:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  883: 	"\n";
  884: 	
  885:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
  886:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
  887:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
  888:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
  889:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
  890:                   .&Apache::lonhtmlcommon::row_closure();
  891:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
  892:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
  893:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
  894:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
  895:                   .&Apache::lonhtmlcommon::row_closure();
  896: 
  897:     my $submission_options;
  898:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  899:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  900:     $env{'form.Status'} = $saveStatus;
  901:     $submission_options.=
  902:         '<span class="LC_nobreak">'.
  903:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
  904:         &mt('last submission only').' </label></span>'."\n".
  905:         '<span class="LC_nobreak">'.
  906:         '<label><input type="radio" name="lastSub" value="last" /> '.
  907:         &mt('last submission &amp; parts info').' </label></span>'."\n".
  908:         '<span class="LC_nobreak">'.
  909:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
  910:         &mt('by dates and submissions').'</label></span>'."\n".
  911:         '<span class="LC_nobreak">'.
  912:         '<label><input type="radio" name="lastSub" value="all" /> '.
  913:         &mt('all details').'</label></span>';
  914:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
  915:                   .$submission_options
  916:                   .&Apache::lonhtmlcommon::row_closure();
  917: 
  918:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
  919:                   .'<select name="increment">'
  920:                   .'<option value="1">'.&mt('Whole Points').'</option>'
  921:                   .'<option value=".5">'.&mt('Half Points').'</option>'
  922:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
  923:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
  924:                   .'</select>'
  925:                   .&Apache::lonhtmlcommon::row_closure();
  926: 
  927:     $gradeTable .= 
  928:         &build_section_inputs().
  929: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
  930: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  931: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
  932: 
  933:     if (exists($env{'form.Status'})) {
  934: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
  935:     } else {
  936:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
  937:                       .&Apache::lonhtmlcommon::StatusOptions(
  938:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
  939:                       .&Apache::lonhtmlcommon::row_closure();
  940:     }
  941: 
  942:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
  943:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
  944:                   .&Apache::lonhtmlcommon::row_closure(1)
  945:                   .&Apache::lonhtmlcommon::end_pick_box();
  946: 
  947:     $gradeTable .= '<p>'
  948:                   .&mt("To view/grade/regrade 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"
  949:                   .'<input type="hidden" name="command" value="processGroup" />'
  950:                   .'</p>';
  951: 
  952: # checkall buttons
  953:     $gradeTable.=&check_script('gradesub', 'stuinfo');
  954:     $gradeTable.='<input type="button" '."\n".
  955:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
  956:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
  957:     $gradeTable.=&check_buttons();
  958:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
  959:     $gradeTable.= &Apache::loncommon::start_data_table().
  960: 	&Apache::loncommon::start_data_table_header_row();
  961:     my $loop = 0;
  962:     while ($loop < 2) {
  963: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
  964: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
  965: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
  966: 	    foreach my $part (sort(@$partlist)) {
  967: 		my $display_part=
  968: 		    &get_display_part((split(/_/,$part))[0],$symb);
  969: 		$gradeTable.=
  970: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
  971: 	    }
  972: 	} elsif ($submitonly eq 'queued') {
  973: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
  974: 	}
  975: 	$loop++;
  976: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
  977:     }
  978:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
  979: 
  980:     my $ctr = 0;
  981:     foreach my $student (sort 
  982: 			 {
  983: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  984: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  985: 			     }
  986: 			     return $a cmp $b;
  987: 			 }
  988: 			 (keys(%$fullname))) {
  989: 	my ($uname,$udom) = split(/:/,$student);
  990: 
  991: 	my %status = ();
  992: 
  993: 	if ($submitonly eq 'queued') {
  994: 	    my %queue_status = 
  995: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
  996: 							$udom,$uname);
  997: 	    next if (!defined($queue_status{'gradingqueue'}));
  998: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
  999: 	}
 1000: 
 1001: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1002: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
 1003: 	    my $submitted = 0;
 1004: 	    my $graded = 0;
 1005: 	    my $incorrect = 0;
 1006: 	    foreach (keys(%status)) {
 1007: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1008: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1009: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1010: 		
 1011: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1012: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1013: 		    $submitted = 0;
 1014: 		    my ($part)=split(/\./,$partid);
 1015: 		    $gradeTable.='<input type="hidden" name="'.
 1016: 			$student.':'.$part.':submitted_by" value="'.
 1017: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1018: 		}
 1019: 	    }
 1020: 	    
 1021: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1022: 				     $submitonly eq 'incorrect' ||
 1023: 				     $submitonly eq 'graded'));
 1024: 	    next if (!$graded && ($submitonly eq 'graded'));
 1025: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1026: 	}
 1027: 
 1028: 	$ctr++;
 1029: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1030:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1031: 	if ( $perm{'vgr'} eq 'F' ) {
 1032: 	    if ($ctr%2 ==1) {
 1033: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1034: 	    }
 1035: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1036:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1037:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1038: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1039: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1040: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1041: 
 1042: 	    if ($submitonly ne 'all') {
 1043: 		foreach (sort(keys(%status))) {
 1044: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1045: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1046: 		}
 1047: 	    }
 1048: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1049: 	    if ($ctr%2 ==0) {
 1050: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1051: 	    }
 1052: 	}
 1053:     }
 1054:     if ($ctr%2 ==1) {
 1055: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1056: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1057: 		foreach (@$partlist) {
 1058: 		    $gradeTable.='<td>&nbsp;</td>';
 1059: 		}
 1060: 	    } elsif ($submitonly eq 'queued') {
 1061: 		$gradeTable.='<td>&nbsp;</td>';
 1062: 	    }
 1063: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1064:     }
 1065: 
 1066:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1067:         '<input type="button" '.
 1068:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
 1069:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1070:     if ($ctr == 0) {
 1071: 	my $num_students=(scalar(keys(%$fullname)));
 1072: 	if ($num_students eq 0) {
 1073: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1074: 	} else {
 1075: 	    my $submissions='submissions';
 1076: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1077: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1078: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1079: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1080: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
 1081: 		    $num_students).
 1082: 		'</span><br />';
 1083: 	}
 1084:     } elsif ($ctr == 1) {
 1085: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1086:     }
 1087:     $request->print($gradeTable);
 1088:     return '';
 1089: }
 1090: 
 1091: #---- Called from the listStudents routine
 1092: 
 1093: sub check_script {
 1094:     my ($form, $type)=@_;
 1095:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
 1096:     function checkall() {
 1097:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1098:             ele = document.forms.'.$form.'.elements[i];
 1099:             if (ele.name == "'.$type.'") {
 1100:             document.forms.'.$form.'.elements[i].checked=true;
 1101:                                        }
 1102:         }
 1103:     }
 1104: 
 1105:     function checksec() {
 1106:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1107:             ele = document.forms.'.$form.'.elements[i];
 1108:            string = document.forms.'.$form.'.chksec.value;
 1109:            if
 1110:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1111:               document.forms.'.$form.'.elements[i].checked=true;
 1112:             }
 1113:         }
 1114:     }
 1115: 
 1116: 
 1117:     function uncheckall() {
 1118:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1119:             ele = document.forms.'.$form.'.elements[i];
 1120:             if (ele.name == "'.$type.'") {
 1121:             document.forms.'.$form.'.elements[i].checked=false;
 1122:                                        }
 1123:         }
 1124:     }
 1125: 
 1126: '."\n");
 1127:     return $chkallscript;
 1128: }
 1129: 
 1130: sub check_buttons {
 1131:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1132:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1133:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1134:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1135:     return $buttons;
 1136: }
 1137: 
 1138: #     Displays the submissions for one student or a group of students
 1139: sub processGroup {
 1140:     my ($request,$symb)  = @_;
 1141:     my $ctr        = 0;
 1142:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1143:     my $total      = scalar(@stuchecked)-1;
 1144: 
 1145:     foreach my $student (@stuchecked) {
 1146: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1147: 	$env{'form.student'}        = $uname;
 1148: 	$env{'form.userdom'}        = $udom;
 1149: 	$env{'form.fullname'}       = $fullname;
 1150: 	&submission($request,$ctr,$total,$symb);
 1151: 	$ctr++;
 1152:     }
 1153:     return '';
 1154: }
 1155: 
 1156: #------------------------------------------------------------------------------------
 1157: #
 1158: #-------------------------- Next few routines handles grading by student, essentially
 1159: #                           handles essay response type problem/part
 1160: #
 1161: #--- Javascript to handle the submission page functionality ---
 1162: sub sub_page_js {
 1163:     my $request = shift;
 1164: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1165:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1166:     function updateRadio(formname,id,weight) {
 1167: 	var gradeBox = formname["GD_BOX"+id];
 1168: 	var radioButton = formname["RADVAL"+id];
 1169: 	var oldpts = formname["oldpts"+id].value;
 1170: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1171: 	gradeBox.value = pts;
 1172: 	var resetbox = false;
 1173: 	if (isNaN(pts) || pts < 0) {
 1174: 	    alert("$alertmsg"+pts);
 1175: 	    for (var i=0; i<radioButton.length; i++) {
 1176: 		if (radioButton[i].checked) {
 1177: 		    gradeBox.value = i;
 1178: 		    resetbox = true;
 1179: 		}
 1180: 	    }
 1181: 	    if (!resetbox) {
 1182: 		formtextbox.value = "";
 1183: 	    }
 1184: 	    return;
 1185: 	}
 1186: 
 1187: 	if (pts > weight) {
 1188: 	    var resp = confirm("You entered a value ("+pts+
 1189: 			       ") greater than the weight for the part. Accept?");
 1190: 	    if (resp == false) {
 1191: 		gradeBox.value = oldpts;
 1192: 		return;
 1193: 	    }
 1194: 	}
 1195: 
 1196: 	for (var i=0; i<radioButton.length; i++) {
 1197: 	    radioButton[i].checked=false;
 1198: 	    if (pts == i && pts != "") {
 1199: 		radioButton[i].checked=true;
 1200: 	    }
 1201: 	}
 1202: 	updateSelect(formname,id);
 1203: 	formname["stores"+id].value = "0";
 1204:     }
 1205: 
 1206:     function writeBox(formname,id,pts) {
 1207: 	var gradeBox = formname["GD_BOX"+id];
 1208: 	if (checkSolved(formname,id) == 'update') {
 1209: 	    gradeBox.value = pts;
 1210: 	} else {
 1211: 	    var oldpts = formname["oldpts"+id].value;
 1212: 	    gradeBox.value = oldpts;
 1213: 	    var radioButton = formname["RADVAL"+id];
 1214: 	    for (var i=0; i<radioButton.length; i++) {
 1215: 		radioButton[i].checked=false;
 1216: 		if (i == oldpts) {
 1217: 		    radioButton[i].checked=true;
 1218: 		}
 1219: 	    }
 1220: 	}
 1221: 	formname["stores"+id].value = "0";
 1222: 	updateSelect(formname,id);
 1223: 	return;
 1224:     }
 1225: 
 1226:     function clearRadBox(formname,id) {
 1227: 	if (checkSolved(formname,id) == 'noupdate') {
 1228: 	    updateSelect(formname,id);
 1229: 	    return;
 1230: 	}
 1231: 	gradeSelect = formname["GD_SEL"+id];
 1232: 	for (var i=0; i<gradeSelect.length; i++) {
 1233: 	    if (gradeSelect[i].selected) {
 1234: 		var selectx=i;
 1235: 	    }
 1236: 	}
 1237: 	var stores = formname["stores"+id];
 1238: 	if (selectx == stores.value) { return };
 1239: 	var gradeBox = formname["GD_BOX"+id];
 1240: 	gradeBox.value = "";
 1241: 	var radioButton = formname["RADVAL"+id];
 1242: 	for (var i=0; i<radioButton.length; i++) {
 1243: 	    radioButton[i].checked=false;
 1244: 	}
 1245: 	stores.value = selectx;
 1246:     }
 1247: 
 1248:     function checkSolved(formname,id) {
 1249: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1250: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1251: 	    if (!reply) {return "noupdate";}
 1252: 	    formname.overRideScore.value = 'yes';
 1253: 	}
 1254: 	return "update";
 1255:     }
 1256: 
 1257:     function updateSelect(formname,id) {
 1258: 	formname["GD_SEL"+id][0].selected = true;
 1259: 	return;
 1260:     }
 1261: 
 1262: //=========== Check that a point is assigned for all the parts  ============
 1263:     function checksubmit(formname,val,total,parttot) {
 1264: 	formname.gradeOpt.value = val;
 1265: 	if (val == "Save & Next") {
 1266: 	    for (i=0;i<=total;i++) {
 1267: 		for (j=0;j<parttot;j++) {
 1268: 		    var partid = formname["partid"+i+"_"+j].value;
 1269: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1270: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1271: 			if (points == "") {
 1272: 			    var name = formname["name"+i].value;
 1273: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1274: 			    var resp = confirm("You did not assign a score for "+studentID+
 1275: 					       ", part "+partid+". Continue?");
 1276: 			    if (resp == false) {
 1277: 				formname["GD_BOX"+i+"_"+partid].focus();
 1278: 				return false;
 1279: 			    }
 1280: 			}
 1281: 		    }
 1282: 		    
 1283: 		}
 1284: 	    }
 1285: 	    
 1286: 	}
 1287: 	formname.submit();
 1288:     }
 1289: 
 1290: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1291:     function checkSubmitPage(formname,total) {
 1292: 	noscore = new Array(100);
 1293: 	var ptr = 0;
 1294: 	for (i=1;i<total;i++) {
 1295: 	    var partid = formname["q_"+i].value;
 1296: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1297: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1298: 		var status = formname["solved"+i+"_"+partid].value;
 1299: 		if (points == "" && status != "correct_by_student") {
 1300: 		    noscore[ptr] = i;
 1301: 		    ptr++;
 1302: 		}
 1303: 	    }
 1304: 	}
 1305: 	if (ptr != 0) {
 1306: 	    var sense = ptr == 1 ? ": " : "s: ";
 1307: 	    var prolist = "";
 1308: 	    if (ptr == 1) {
 1309: 		prolist = noscore[0];
 1310: 	    } else {
 1311: 		var i = 0;
 1312: 		while (i < ptr-1) {
 1313: 		    prolist += noscore[i]+", ";
 1314: 		    i++;
 1315: 		}
 1316: 		prolist += "and "+noscore[i];
 1317: 	    }
 1318: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1319: 	    if (resp == false) {
 1320: 		return false;
 1321: 	    }
 1322: 	}
 1323: 
 1324: 	formname.submit();
 1325:     }
 1326: SUBJAVASCRIPT
 1327: }
 1328: 
 1329: #--- javascript for essay type problem --
 1330: sub sub_page_kw_js {
 1331:     my $request = shift;
 1332:     my $iconpath = $request->dir_config('lonIconsURL');
 1333:     &commonJSfunctions($request);
 1334: 
 1335:     my $inner_js_msg_central= (<<INNERJS);
 1336: <script type="text/javascript">
 1337:     function checkInput() {
 1338:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1339:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1340:       var usrctr = document.msgcenter.usrctr.value;
 1341:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1342:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1343: 
 1344:       var msgchk = "";
 1345:       if (document.msgcenter.subchk.checked) {
 1346:          msgchk = "msgsub,";
 1347:       }
 1348:       var includemsg = 0;
 1349:       for (var i=1; i<=nmsg; i++) {
 1350:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1351:           var frmmsg = document.msgcenter["msg"+i];
 1352:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1353:           var showflg = opener.document.SCORE["shownOnce"+i];
 1354:           showflg.value = "1";
 1355:           var chkbox = document.msgcenter["msgn"+i];
 1356:           if (chkbox.checked) {
 1357:              msgchk += "savemsg"+i+",";
 1358:              includemsg = 1;
 1359:           }
 1360:       }
 1361:       if (document.msgcenter.newmsgchk.checked) {
 1362:          msgchk += "newmsg"+usrctr;
 1363:          includemsg = 1;
 1364:       }
 1365:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1366:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1367:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1368:       includemsg.value = msgchk;
 1369: 
 1370:       self.close()
 1371: 
 1372:     }
 1373: </script>
 1374: INNERJS
 1375: 
 1376:     my $inner_js_highlight_central= (<<INNERJS);
 1377: <script type="text/javascript">
 1378:     function updateChoice(flag) {
 1379:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1380:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1381:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1382:       opener.document.SCORE.refresh.value = "on";
 1383:       if (opener.document.SCORE.keywords.value!=""){
 1384:          opener.document.SCORE.submit();
 1385:       }
 1386:       self.close()
 1387:     }
 1388: </script>
 1389: INNERJS
 1390: 
 1391:     my $start_page_msg_central = 
 1392:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1393: 				       {'js_ready'  => 1,
 1394: 					'only_body' => 1,
 1395: 					'bgcolor'   =>'#FFFFFF',});
 1396:     my $end_page_msg_central = 
 1397: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1398: 
 1399: 
 1400:     my $start_page_highlight_central = 
 1401:         &Apache::loncommon::start_page('Highlight Central',
 1402: 				       $inner_js_highlight_central,
 1403: 				       {'js_ready'  => 1,
 1404: 					'only_body' => 1,
 1405: 					'bgcolor'   =>'#FFFFFF',});
 1406:     my $end_page_highlight_central = 
 1407: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1408: 
 1409:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1410:     $docopen=~s/^document\.//;
 1411:     my %lt = &Apache::lonlocal::texthash(
 1412:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
 1413:                 plse => 'Please select a word or group of words from document and then click this link.',
 1414:                 adds => 'Add selection to keyword list? Edit if desired.',
 1415:                 comp => 'Compose Message for: ',
 1416:                 incl => 'Include',
 1417:                 subj => 'Subject',
 1418:                 mesa => 'Message',
 1419:                 new  => 'New',
 1420:                 save => 'Save',
 1421:                 canc => 'Cancel',
 1422:                 kehi => 'Keyword Highlight Options',
 1423:                 txtc => 'Text Color',
 1424:                 font => 'Font Size',
 1425:              );
 1426:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1427: 
 1428: //===================== Show list of keywords ====================
 1429:   function keywords(formname) {
 1430:     var nret = prompt("$lt{'keyw'}",formname.keywords.value);
 1431:     if (nret==null) return;
 1432:     formname.keywords.value = nret;
 1433: 
 1434:     if (formname.keywords.value != "") {
 1435: 	formname.refresh.value = "on";
 1436: 	formname.submit();
 1437:     }
 1438:     return;
 1439:   }
 1440: 
 1441: //===================== Script to view submitted by ==================
 1442:   function viewSubmitter(submitter) {
 1443:     document.SCORE.refresh.value = "on";
 1444:     document.SCORE.NCT.value = "1";
 1445:     document.SCORE.unamedom0.value = submitter;
 1446:     document.SCORE.submit();
 1447:     return;
 1448:   }
 1449: 
 1450: //===================== Script to add keyword(s) ==================
 1451:   function getSel() {
 1452:     if (document.getSelection) txt = document.getSelection();
 1453:     else if (document.selection) txt = document.selection.createRange().text;
 1454:     else return;
 1455:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1456:     if (cleantxt=="") {
 1457: 	alert("$lt{'plse'}");
 1458: 	return;
 1459:     }
 1460:     var nret = prompt("$lt{'adds'}",cleantxt);
 1461:     if (nret==null) return;
 1462:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1463:     if (document.SCORE.keywords.value != "") {
 1464: 	document.SCORE.refresh.value = "on";
 1465: 	document.SCORE.submit();
 1466:     }
 1467:     return;
 1468:   }
 1469: 
 1470: //====================== Script for composing message ==============
 1471:    // preload images
 1472:    img1 = new Image();
 1473:    img1.src = "$iconpath/mailbkgrd.gif";
 1474:    img2 = new Image();
 1475:    img2.src = "$iconpath/mailto.gif";
 1476: 
 1477:   function msgCenter(msgform,usrctr,fullname) {
 1478:     var Nmsg  = msgform.savemsgN.value;
 1479:     savedMsgHeader(Nmsg,usrctr,fullname);
 1480:     var subject = msgform.msgsub.value;
 1481:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1482:     re = /msgsub/;
 1483:     var shwsel = "";
 1484:     if (re.test(msgchk)) { shwsel = "checked" }
 1485:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1486:     displaySubject(checkEntities(subject),shwsel);
 1487:     for (var i=1; i<=Nmsg; i++) {
 1488: 	var testmsg = "savemsg"+i+",";
 1489: 	re = new RegExp(testmsg,"g");
 1490: 	shwsel = "";
 1491: 	if (re.test(msgchk)) { shwsel = "checked" }
 1492: 	var message = document.SCORE["savemsg"+i].value;
 1493: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1494: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1495: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1496:     }
 1497:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1498:     shwsel = "";
 1499:     re = /newmsg/;
 1500:     if (re.test(msgchk)) { shwsel = "checked" }
 1501:     newMsg(newmsg,shwsel);
 1502:     msgTail(); 
 1503:     return;
 1504:   }
 1505: 
 1506:   function checkEntities(strx) {
 1507:     if (strx.length == 0) return strx;
 1508:     var orgStr = ["&", "<", ">", '"']; 
 1509:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1510:     var counter = 0;
 1511:     while (counter < 4) {
 1512: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1513: 	counter++;
 1514:     }
 1515:     return strx;
 1516:   }
 1517: 
 1518:   function strReplace(strx, orgStr, newStr) {
 1519:     return strx.split(orgStr).join(newStr);
 1520:   }
 1521: 
 1522:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1523:     var height = 70*Nmsg+250;
 1524:     var scrollbar = "no";
 1525:     if (height > 600) {
 1526: 	height = 600;
 1527: 	scrollbar = "yes";
 1528:     }
 1529:     var xpos = (screen.width-600)/2;
 1530:     xpos = (xpos < 0) ? '0' : xpos;
 1531:     var ypos = (screen.height-height)/2-30;
 1532:     ypos = (ypos < 0) ? '0' : ypos;
 1533: 
 1534:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
 1535:     pWin.focus();
 1536:     pDoc = pWin.document;
 1537:     pDoc.$docopen;
 1538:     pDoc.write('$start_page_msg_central');
 1539: 
 1540:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1541:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1542:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;$lt{'comp'}\"+fullname+\"<\\/span><\\/h3><br /><br />");
 1543: 
 1544:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1545:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1546:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>$lt{'incl'}<\\/b><\\/td><td><b>$lt{'mesa'}<\\/td><\\/tr>");
 1547: }
 1548:     function displaySubject(msg,shwsel) {
 1549:     pDoc = pWin.document;
 1550:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1551:     pDoc.write("<td>$lt{'subj'}<\\/td>");
 1552:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1553:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1554: }
 1555: 
 1556:   function displaySavedMsg(ctr,msg,shwsel) {
 1557:     pDoc = pWin.document;
 1558:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1559:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1560:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1561:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1562: }
 1563: 
 1564:   function newMsg(newmsg,shwsel) {
 1565:     pDoc = pWin.document;
 1566:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1567:     pDoc.write("<td align=\\"center\\">$lt{'new'}<\\/td>");
 1568:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1569:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1570: }
 1571: 
 1572:   function msgTail() {
 1573:     pDoc = pWin.document;
 1574:     pDoc.write("<\\/table>");
 1575:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1576:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1577:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
 1578:     pDoc.write("<\\/form>");
 1579:     pDoc.write('$end_page_msg_central');
 1580:     pDoc.close();
 1581: }
 1582: 
 1583: //====================== Script for keyword highlight options ==============
 1584:   function kwhighlight() {
 1585:     var kwclr    = document.SCORE.kwclr.value;
 1586:     var kwsize   = document.SCORE.kwsize.value;
 1587:     var kwstyle  = document.SCORE.kwstyle.value;
 1588:     var redsel = "";
 1589:     var grnsel = "";
 1590:     var blusel = "";
 1591:     if (kwclr=="red")   {var redsel="checked"};
 1592:     if (kwclr=="green") {var grnsel="checked"};
 1593:     if (kwclr=="blue")  {var blusel="checked"};
 1594:     var sznsel = "";
 1595:     var sz1sel = "";
 1596:     var sz2sel = "";
 1597:     if (kwsize=="0")  {var sznsel="checked"};
 1598:     if (kwsize=="+1") {var sz1sel="checked"};
 1599:     if (kwsize=="+2") {var sz2sel="checked"};
 1600:     var synsel = "";
 1601:     var syisel = "";
 1602:     var sybsel = "";
 1603:     if (kwstyle=="")    {var synsel="checked"};
 1604:     if (kwstyle=="<i>") {var syisel="checked"};
 1605:     if (kwstyle=="<b>") {var sybsel="checked"};
 1606:     highlightCentral();
 1607:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
 1608:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
 1609:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
 1610:     highlightend();
 1611:     return;
 1612:   }
 1613: 
 1614:   function highlightCentral() {
 1615: //    if (window.hwdWin) window.hwdWin.close();
 1616:     var xpos = (screen.width-400)/2;
 1617:     xpos = (xpos < 0) ? '0' : xpos;
 1618:     var ypos = (screen.height-330)/2-30;
 1619:     ypos = (ypos < 0) ? '0' : ypos;
 1620: 
 1621:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1622:     hwdWin.focus();
 1623:     var hDoc = hwdWin.document;
 1624:     hDoc.$docopen;
 1625:     hDoc.write('$start_page_highlight_central');
 1626:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1627:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;$lt{'kehi'}<\\/span><\\/h3><br /><br />");
 1628: 
 1629:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1630:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1631:     hDoc.write("<td><b>$lt{'txtc'}<\\/b><\\/td><td><b>$lt{'font'}<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
 1632:   }
 1633: 
 1634:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1635:     var hDoc = hwdWin.document;
 1636:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1637:     hDoc.write("<td align=\\"left\\">");
 1638:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
 1639:     hDoc.write("<td align=\\"left\\">");
 1640:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
 1641:     hDoc.write("<td align=\\"left\\">");
 1642:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
 1643:     hDoc.write("<\\/tr>");
 1644:   }
 1645: 
 1646:   function highlightend() { 
 1647:     var hDoc = hwdWin.document;
 1648:     hDoc.write("<\\/table>");
 1649:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1650:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
 1651:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
 1652:     hDoc.write("<\\/form>");
 1653:     hDoc.write('$end_page_highlight_central');
 1654:     hDoc.close();
 1655:   }
 1656: 
 1657: SUBJAVASCRIPT
 1658: }
 1659: 
 1660: sub get_increment {
 1661:     my $increment = $env{'form.increment'};
 1662:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1663:         $increment != .1) {
 1664:         $increment = 1;
 1665:     }
 1666:     return $increment;
 1667: }
 1668: 
 1669: sub gradeBox_start {
 1670:     return (
 1671:         &Apache::loncommon::start_data_table()
 1672:        .&Apache::loncommon::start_data_table_header_row()
 1673:        .'<th>'.&mt('Part').'</th>'
 1674:        .'<th>'.&mt('Points').'</th>'
 1675:        .'<th>&nbsp;</th>'
 1676:        .'<th>'.&mt('Assign Grade').'</th>'
 1677:        .'<th>'.&mt('Weight').'</th>'
 1678:        .'<th>'.&mt('Grade Status').'</th>'
 1679:        .&Apache::loncommon::end_data_table_header_row()
 1680:     );
 1681: }
 1682: 
 1683: sub gradeBox_end {
 1684:     return (
 1685:         &Apache::loncommon::end_data_table()
 1686:     );
 1687: }
 1688: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1689: sub gradeBox {
 1690:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1691:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1692: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1693:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1694:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1695:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1696:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1697:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1698: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1699:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1700:     my $display_part= &get_display_part($partid,$symb);
 1701:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1702: 				       [$partid]);
 1703:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1704:     if ($last_resets{$partid}) {
 1705:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1706:     }
 1707:     $result.=&Apache::loncommon::start_data_table_row();
 1708:     my $ctr = 0;
 1709:     my $thisweight = 0;
 1710:     my $increment = &get_increment();
 1711: 
 1712:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1713:     while ($thisweight<=$wgt) {
 1714: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1715:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1716: 	    $thisweight.')" value="'.$thisweight.'" '.
 1717: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1718: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1719:         $thisweight += $increment;
 1720: 	$ctr++;
 1721:     }
 1722:     $radio.='</tr></table>';
 1723: 
 1724:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1725: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1726: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1727: 	$wgt.')" /></td>'."\n";
 1728:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1729: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1730: 	' </td>'."\n";
 1731:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1732: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1733:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1734: 	$line.='<option></option>'.
 1735: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1736:     } else {
 1737: 	$line.='<option selected="selected"></option>'.
 1738: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1739:     }
 1740:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1741: 
 1742: 
 1743:     $result .= 
 1744: 	    '<td>'.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 1745:     $result.=&Apache::loncommon::end_data_table_row();
 1746:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1747: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1748: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1749: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1750:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1751:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1752:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1753:         $aggtries.'" />'."\n";
 1754:     my $res_error;
 1755:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 1756:     if ($res_error) {
 1757:         return &navmap_errormsg();
 1758:     }
 1759:     return $result;
 1760: }
 1761: 
 1762: sub handback_box {
 1763:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
 1764:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
 1765:     my (@respids);
 1766:     my @part_response_id = &flatten_responseType($responseType);
 1767:     foreach my $part_response_id (@part_response_id) {
 1768:     	my ($part,$resp) = @{ $part_response_id };
 1769:         if ($part eq $partid) {
 1770:             push(@respids,$resp);
 1771:         }
 1772:     }
 1773:     my $result;
 1774:     foreach my $respid (@respids) {
 1775: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1776: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1777: 	next if (!@$files);
 1778: 	my $file_counter = 1;
 1779: 	foreach my $file (@$files) {
 1780: 	    if ($file =~ /\/portfolio\//) {
 1781:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1782:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1783:     	        $file_disp = "$name.$ext";
 1784:     	        $file = $file_path.$file_disp;
 1785:     	        $result.=&mt('Return commented version of [_1] to student.',
 1786:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1787:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1788:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
 1789:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
 1790:     	        $file_counter++;
 1791: 	    }
 1792: 	}
 1793:     }
 1794:     return $result;    
 1795: }
 1796: 
 1797: sub show_problem {
 1798:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1799:     my $rendered;
 1800:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1801:     &Apache::lonxml::remember_problem_counter();
 1802:     if ($mode eq 'both' or $mode eq 'text') {
 1803: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1804: 						       $env{'request.course.id'},
 1805: 						       undef,\%form);
 1806:     }
 1807:     if ($removeform) {
 1808: 	$rendered=~s|<form(.*?)>||g;
 1809: 	$rendered=~s|</form>||g;
 1810: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1811:     }
 1812:     my $companswer;
 1813:     if ($mode eq 'both' or $mode eq 'answer') {
 1814: 	&Apache::lonxml::restore_problem_counter();
 1815: 	$companswer=
 1816: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1817: 						    $env{'request.course.id'},
 1818: 						    %form);
 1819:     }
 1820:     if ($removeform) {
 1821: 	$companswer=~s|<form(.*?)>||g;
 1822: 	$companswer=~s|</form>||g;
 1823: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1824:     }
 1825:     $rendered=
 1826:         '<div class="LC_Box">'
 1827:        .'<h3 class="LC_hcell">'.&mt('View of the problem').'</h3>'
 1828:        .$rendered
 1829:        .'</div>';
 1830:     $companswer=
 1831:         '<div class="LC_Box">'
 1832:        .'<h3 class="LC_hcell">'.&mt('Correct answer').'</h3>'
 1833:        .$companswer
 1834:        .'</div>';
 1835:     my $result;
 1836:     if ($mode eq 'both') {
 1837:         $result=$rendered.$companswer;
 1838:     } elsif ($mode eq 'text') {
 1839:         $result=$rendered;
 1840:     } elsif ($mode eq 'answer') {
 1841:         $result=$companswer;
 1842:     }
 1843:     return $result;
 1844: }
 1845: 
 1846: sub files_exist {
 1847:     my ($r, $symb) = @_;
 1848:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1849: 
 1850:     foreach my $student (@students) {
 1851:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1852:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1853: 					      $udom,$uname);
 1854:         my ($string,$timestamp)= &get_last_submission(\%record);
 1855:         foreach my $submission (@$string) {
 1856:             my ($partid,$respid) =
 1857: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1858:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1859: 					   \%record);
 1860:             return 1 if (@$files);
 1861:         }
 1862:     }
 1863:     return 0;
 1864: }
 1865: 
 1866: sub download_all_link {
 1867:     my ($r,$symb) = @_;
 1868:     unless (&files_exist($r, $symb)) {
 1869:        $r->print(&mt('There are currently no submitted documents.'));
 1870:        return;
 1871:     }
 1872: 
 1873:     my $all_students = 
 1874: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1875: 
 1876:     my $parts =
 1877: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1878: 
 1879:     my $identifier = &Apache::loncommon::get_cgi_id();
 1880:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 1881:                              'cgi.'.$identifier.'.symb' => $symb,
 1882:                              'cgi.'.$identifier.'.parts' => $parts,});
 1883:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1884: 	      &mt('Download All Submitted Documents').'</a>');
 1885:     return;
 1886: }
 1887: 
 1888: sub submit_download_link {
 1889:     my ($request,$symb) = @_;
 1890:     if (!$symb) { return ''; }
 1891: #FIXME: Figure out which type of problem this is and provide appropriate download
 1892:     &download_all_link($request,$symb);
 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,$symb) = @_;
 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: 
 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: 	return;
 1924:     }
 1925: 
 1926:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 1927:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 1928:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 1929:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 1930:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1931: 	'" src="'.$request->dir_config('lonIconsURL').
 1932: 	'/check.gif" height="16" border="0" />';
 1933: 
 1934:     my %old_essays;
 1935:     # header info
 1936:     if ($counter == 0) {
 1937: 	&sub_page_js($request);
 1938: 	&sub_page_kw_js($request);
 1939: 
 1940: 	# option to display problem, only once else it cause problems 
 1941:         # with the form later since the problem has a form.
 1942: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 1943: 	    my $mode;
 1944: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 1945: 		$mode='both';
 1946: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 1947: 		$mode='text';
 1948: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 1949: 		$mode='answer';
 1950: 	    }
 1951: 	    &Apache::lonxml::clear_problem_counter();
 1952: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 1953: 	}
 1954: 
 1955: 	# kwclr is the only variable that is guaranteed to be non blank 
 1956:         # if this subroutine has been called once.
 1957: 	my %keyhash = ();
 1958: #	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 1959:         if (1) {
 1960: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 1961: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 1962: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 1963: 
 1964: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 1965: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 1966: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 1967: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 1968: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 1969: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 1970: 		$keyhash{$symb.'_subject'} : $probtitle;
 1971: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 1972: 	}
 1973: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 1974: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 1975: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 1976: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 1977: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 1978: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 1979: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 1980: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 1981: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 1982: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1983: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 1984: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 1985: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 1986: 			&build_section_inputs().
 1987: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 1988: 			'<input type="hidden" name="NCT"'.
 1989: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 1990: #	if ($env{'form.handgrade'} eq 'yes') {
 1991:         if (1) {
 1992: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 1993: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 1994: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 1995: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 1996: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 1997: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 1998: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 1999: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 2000: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 2001: 	    }
 2002: 	}
 2003: 	
 2004: 	my ($cts,$prnmsg) = (1,'');
 2005: 	while ($cts <= $env{'form.savemsgN'}) {
 2006: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2007: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2008: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2009: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2010: 		'" />'."\n".
 2011: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2012: 	    $cts++;
 2013: 	}
 2014: 	$request->print($prnmsg);
 2015: 
 2016: #	if ($env{'form.handgrade'} eq 'yes') {
 2017:         if (1) {
 2018: 
 2019:             my %lt = &Apache::lonlocal::texthash(
 2020:                           keyw => 'Keyword Options',
 2021:                           past => 'Paste Selection to List',
 2022:                           high => 'Hightlight Attribute',
 2023:                      );    
 2024: #
 2025: # Print out the keyword options line
 2026: #
 2027: 	    $request->print(<<KEYWORDS);
 2028: <br /><b>$lt{'keyw'}:</b>&nbsp;
 2029: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
 2030: <a href="#" onmousedown="javascript:getSel(); return false"
 2031:  CLASS="page">$lt{'past'}</a>&nbsp; &nbsp;
 2032: <a href="javascript:kwhighlight();" target="_self">$lt{'high'}</a><br /><br />
 2033: KEYWORDS
 2034: #
 2035: # Load the other essays for similarity check
 2036: #
 2037:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2038: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2039: 	    $apath=&escape($apath);
 2040: 	    $apath=~s/\W/\_/gs;
 2041: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 2042:         }
 2043:     }
 2044: 
 2045: # This is where output for one specific student would start
 2046:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2047:     $request->print(
 2048:         "\n\n"
 2049:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2050:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2051:        ."\n"
 2052:     );
 2053: 
 2054:     # Show additional functions if allowed
 2055:     if ($perm{'vgr'}) {
 2056:         $request->print(
 2057:             &Apache::loncommon::track_student_link(
 2058:                 &mt('View recent activity'),
 2059:                 $uname,$udom,'check')
 2060:            .' '
 2061:         );
 2062:     }
 2063:     if ($perm{'opa'}) {
 2064:         $request->print(
 2065:             &Apache::loncommon::pprmlink(
 2066:                 &mt('Set/Change parameters'),
 2067:                 $uname,$udom,$symb,'check'));
 2068:     }
 2069: 
 2070:     # Show Problem
 2071:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2072: 	my $mode;
 2073: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2074: 	    $mode='both';
 2075: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2076: 	    $mode='text';
 2077: 	} elsif ($env{'form.vAns'} eq 'all') {
 2078: 	    $mode='answer';
 2079: 	}
 2080: 	&Apache::lonxml::clear_problem_counter();
 2081: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2082:     }
 2083: 
 2084:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2085:     my $res_error;
 2086:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2087:     if ($res_error) {
 2088:         $request->print(&navmap_errormsg());
 2089:         return;
 2090:     }
 2091: 
 2092:     # Display student info
 2093:     $request->print(($counter == 0 ? '' : '<br />'));
 2094: 
 2095:     my $result='<div class="LC_Box">'
 2096:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
 2097:     $result.='<input type="hidden" name="name'.$counter.
 2098:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2099: #    if ($env{'form.handgrade'} eq 'no') {
 2100:     if (1) {
 2101:         $result.='<p class="LC_info">'
 2102:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2103:                 ."</p>\n";
 2104:     }
 2105: 
 2106:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2107:     my $fullname;
 2108:     my $col_fullnames = [];
 2109: #    if ($env{'form.handgrade'} eq 'yes') {
 2110:     if (1) {
 2111: 	(my $sub_result,$fullname,$col_fullnames)=
 2112: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2113: 				 $counter);
 2114: 	$result.=$sub_result;
 2115:     }
 2116:     $request->print($result."\n");
 2117: 
 2118:     # print student answer/submission
 2119:     # Options are (1) Handgraded submission only
 2120:     #             (2) Last submission, includes submission that is not handgraded 
 2121:     #                  (for multi-response type part)
 2122:     #             (3) Last submission plus the parts info
 2123:     #             (4) The whole record for this student
 2124:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
 2125: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2126: 	
 2127: 	my $lastsubonly;
 2128: 
 2129:         if ($$timestamp eq '') {
 2130:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2131:         } else {
 2132:             $lastsubonly =
 2133:                 '<div class="LC_grade_submissions_body">'
 2134:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
 2135: 
 2136: 	    my %seenparts;
 2137: 	    my @part_response_id = &flatten_responseType($responseType);
 2138: 	    foreach my $part (@part_response_id) {
 2139: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2140: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2141: 
 2142: 		my ($partid,$respid) = @{ $part };
 2143: 		my $display_part=&get_display_part($partid,$symb);
 2144: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2145: 		    if (exists($seenparts{$partid})) { next; }
 2146: 		    $seenparts{$partid}=1;
 2147: 		    my $submitby='<b>Part:</b> '.$display_part.
 2148: 			' <b>Collaborative submission by:</b> '.
 2149: 			'<a href="javascript:viewSubmitter(\''.
 2150: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
 2151: 			'\');" target="_self">'.
 2152: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
 2153: 		    $request->print($submitby);
 2154: 		    next;
 2155: 		}
 2156: 		my $responsetype = $responseType->{$partid}->{$respid};
 2157: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2158:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2159:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2160:                         ' <span class="LC_internal_info">'.
 2161:                         '('.&mt('Response ID: [_1]',$respid).')'.
 2162:                         '</span>&nbsp; &nbsp;'.
 2163: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2164: 		    next;
 2165: 		}
 2166: 		foreach my $submission (@$string) {
 2167: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2168: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2169: 		    my ($ressub,$hide,$subval) = split(/:/,$submission,3);
 2170: 		    # Similarity check
 2171: 		    my $similar='';
 2172:                     my ($type,$trial,$rndseed);
 2173:                     if ($hide eq 'rand') {
 2174:                         $type = 'randomizetry';
 2175:                         $trial = $record{"resource.$partid.tries"};
 2176:                         $rndseed = $record{"resource.$partid.rndseed"};
 2177:                     }
 2178: 		    if($env{'form.checkPlag'}){
 2179: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2180: 			    &most_similar($uname,$udom,$subval,\%old_essays);
 2181: 			if ($osim) {
 2182: 			    $osim=int($osim*100.0);
 2183: 			    my %old_course_desc = 
 2184: 				&Apache::lonnet::coursedescription($ocrsid,
 2185: 								   {'one_time' => 1});
 2186: 
 2187:                             if ($hide eq 'anon') {
 2188:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2189:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2190:                             } else {
 2191: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
 2192: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2193: 				        $osim,
 2194: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2195: 				        $old_course_desc{'description'},
 2196: 				        $old_course_desc{'num'},
 2197: 				        $old_course_desc{'domain'}).
 2198: 				    '</span></h3><blockquote><i>'.
 2199: 				    &keywords_highlight($oessay).
 2200: 				    '</i></blockquote><hr />';
 2201:                             }
 2202: 			}
 2203: 		    }
 2204: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom,
 2205:                                          undef,$type,$trial,$rndseed);
 2206: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
 2207: 			($env{'form.lastSub'} eq 'hdgrade' && 
 2208: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2209: 			my $display_part=&get_display_part($partid,$symb);
 2210:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
 2211:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2212:                             ' <span class="LC_internal_info">'.
 2213:                             '('.&mt('Response ID: [_1]',$respid).')'.
 2214:                             '</span>&nbsp; &nbsp;';
 2215: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2216: 			if (@$files) {
 2217:                             if ($hide eq 'anon') {
 2218:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2219:                             } else {
 2220:                                 $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
 2221:                                 foreach my $file (@$files) {
 2222:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2223:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
 2224:                                 }
 2225:                             }
 2226: 			    $lastsubonly.='<br />';
 2227: 			}
 2228:                         if ($hide eq 'anon') {
 2229:                             $lastsubonly.='<b>'.&mt('Anonymous Survey').'</b>'; 
 2230:                         } else {
 2231: 			    $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
 2232: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
 2233: 					     $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
 2234:                         }
 2235: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2236: 			$lastsubonly.='</div>';
 2237: 		    }
 2238: 		}
 2239: 	    }
 2240: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2241: 	}
 2242: 	$request->print($lastsubonly);
 2243:    } elsif ($env{'form.lastSub'} eq 'datesub') {
 2244:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2245: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2246:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2247: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2248: 								 $env{'request.course.id'},
 2249: 								 $last,'.submission',
 2250: 								 'Apache::grades::keywords_highlight'));
 2251:     }
 2252:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2253: 	.$udom.'" />'."\n");
 2254:     # return if view submission with no grading option
 2255:     if (!&canmodify($usec)) {
 2256: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
 2257: 	return;
 2258:     } else {
 2259: 	$request->print('</div>'."\n");
 2260:     }
 2261: 
 2262:     # essay grading message center
 2263: #    if ($env{'form.handgrade'} eq 'yes') {
 2264:     if (1) {
 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: 	$request->print($endform);
 2357:     }
 2358:     return '';
 2359: }
 2360: 
 2361: sub check_collaborators {
 2362:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2363:     my ($result,@col_fullnames);
 2364:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2365:     foreach my $part (keys(%$handgrade)) {
 2366: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2367: 					'.maxcollaborators',
 2368: 					$symb,$udom,$uname);
 2369: 	next if ($ncol <= 0);
 2370: 	$part =~ s/\_/\./g;
 2371: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2372: 	my (@good_collaborators, @bad_collaborators);
 2373: 	foreach my $possible_collaborator
 2374: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2375: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2376: 	    next if ($possible_collaborator eq '');
 2377: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
 2378: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2379: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2380: 	    # Doing this grep allows 'fuzzy' specification
 2381: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2382: 			       keys(%$classlist));
 2383: 	    if (! scalar(@matches)) {
 2384: 		push(@bad_collaborators, $possible_collaborator);
 2385: 	    } else {
 2386: 		push(@good_collaborators, @matches);
 2387: 	    }
 2388: 	}
 2389: 	if (scalar(@good_collaborators) != 0) {
 2390: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
 2391: 	    foreach my $name (@good_collaborators) {
 2392: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2393: 		push(@col_fullnames, $givenn.' '.$lastname);
 2394: 		$result.='<li>'.$fullname->{$name}.'</li>';
 2395: 	    }
 2396: 	    $result.='</ol><br />'."\n";
 2397: 	    my ($part)=split(/\./,$part);
 2398: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2399: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2400: 		"\n";
 2401: 	}
 2402: 	if (scalar(@bad_collaborators) > 0) {
 2403: 	    $result.='<div class="LC_warning">';
 2404: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2405: 	    $result .= '</div>';
 2406: 	}         
 2407: 	if (scalar(@bad_collaborators > $ncol)) {
 2408: 	    $result .= '<div class="LC_warning">';
 2409: 	    $result .= &mt('This student has submitted too many '.
 2410: 		'collaborators.  Maximum is [_1].',$ncol);
 2411: 	    $result .= '</div>';
 2412: 	}
 2413:     }
 2414:     return ($result,$fullname,\@col_fullnames);
 2415: }
 2416: 
 2417: #--- Retrieve the last submission for all the parts
 2418: sub get_last_submission {
 2419:     my ($returnhash)=@_;
 2420:     my (@string,$timestamp,%lasthidden);
 2421:     if ($$returnhash{'version'}) {
 2422: 	my %lasthash=();
 2423: 	my ($version);
 2424: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2425: 	    foreach my $key (sort(split(/\:/,
 2426: 					$$returnhash{$version.':keys'}))) {
 2427: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2428: 		$timestamp = 
 2429: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2430: 	    }
 2431: 	}
 2432:         my (%typeparts,%randombytry);
 2433:         my $showsurv = 
 2434:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2435:         foreach my $key (sort(keys(%lasthash))) {
 2436:             if ($key =~ /\.type$/) {
 2437:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2438:                     ($lasthash{$key} eq 'anonsurveycred') ||
 2439:                     ($lasthash{$key} eq 'randomizetry')) {
 2440:                     my ($ign,@parts) = split(/\./,$key);
 2441:                     pop(@parts);
 2442:                     my $id = join('.',@parts);
 2443:                     if ($lasthash{$key} eq 'randomizetry') {
 2444:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
 2445:                     } else {
 2446:                         unless ($showsurv) {
 2447:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2448:                         }
 2449:                     }
 2450:                     delete($lasthash{$key});
 2451:                 }
 2452:             }
 2453:         }
 2454:         my @hidden = keys(%typeparts);
 2455:         my @randomize = keys(%randombytry);
 2456: 	foreach my $key (keys(%lasthash)) {
 2457: 	    next if ($key !~ /\.submission$/);
 2458:             my $hide;
 2459:             if (@hidden) {
 2460:                 foreach my $id (@hidden) {
 2461:                     if ($key =~ /^\Q$id\E/) {
 2462:                         $hide = 'anon';
 2463:                         last;
 2464:                     }
 2465:                 }
 2466:             }
 2467:             unless ($hide) {
 2468:                 if (@randomize) {
 2469:                     foreach my $id (@hidden) {
 2470:                         if ($key =~ /^\Q$id\E/) {
 2471:                             $hide = 'rand';
 2472:                             last;
 2473:                         }
 2474:                     }
 2475:                 }
 2476:             }
 2477: 	    my ($partid,$foo) = split(/submission$/,$key);
 2478: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 2479: 		'<span class="LC_warning">Draft Copy</span> ' : '';
 2480: 	    push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
 2481: 	}
 2482:     }
 2483:     if (!@string) {
 2484: 	$string[0] =
 2485: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2486:     }
 2487:     return (\@string,\$timestamp);
 2488: }
 2489: 
 2490: #--- High light keywords, with style choosen by user.
 2491: sub keywords_highlight {
 2492:     my $string    = shift;
 2493:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2494:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2495:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2496:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2497:     foreach my $keyword (@keylist) {
 2498: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2499:     }
 2500:     return $string;
 2501: }
 2502: 
 2503: #--- Called from submission routine
 2504: sub processHandGrade {
 2505:     my ($request,$symb) = @_;
 2506:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2507:     my $button = $env{'form.gradeOpt'};
 2508:     my $ngrade = $env{'form.NCT'};
 2509:     my $ntstu  = $env{'form.NTSTU'};
 2510:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2511:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2512: 
 2513:     if ($button eq 'Save & Next') {
 2514: 	my $ctr = 0;
 2515: 	while ($ctr < $ngrade) {
 2516: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2517: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2518: 	    if ($errorflag eq 'no_score') {
 2519: 		$ctr++;
 2520: 		next;
 2521: 	    }
 2522: 	    if ($errorflag eq 'not_allowed') {
 2523: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
 2524: 		$ctr++;
 2525: 		next;
 2526: 	    }
 2527: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2528: 	    my ($subject,$message,$msgstatus) = ('','','');
 2529: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2530:             my ($feedurl,$showsymb) =
 2531: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2532: 	    my $messagetail;
 2533: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2534: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2535: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2536: 		$subject.=' ['.$restitle.']';
 2537: 		my (@msgnum) = split(/,/,$includemsg);
 2538: 		foreach (@msgnum) {
 2539: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2540: 		}
 2541: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2542: 		if ($env{'form.withgrades'.$ctr}) {
 2543: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2544: 		    $messagetail = " for <a href=\"".
 2545: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
 2546: 		}
 2547: 		$msgstatus = 
 2548:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2549: 						     $message.$messagetail,
 2550:                                                      undef,$feedurl,undef,
 2551:                                                      undef,undef,$showsymb,
 2552:                                                      $restitle);
 2553: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 2554: 				$msgstatus.'<br />');
 2555: 	    }
 2556: 	    if ($env{'form.collaborator'.$ctr}) {
 2557: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2558: 		foreach my $collabstr (@collabstrs) {
 2559: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2560: 		    foreach my $collaborator (@collaborators) {
 2561: 			my ($errorflag,$pts,$wgt) = 
 2562: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2563: 					   $env{'form.unamedom'.$ctr},$part);
 2564: 			if ($errorflag eq 'not_allowed') {
 2565: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2566: 			    next;
 2567: 			} elsif ($message ne '') {
 2568: 			    my ($baseurl,$showsymb) = 
 2569: 				&get_feedurl_and_symb($symb,$collaborator,
 2570: 						      $udom);
 2571: 			    if ($env{'form.withgrades'.$ctr}) {
 2572: 				$messagetail = " for <a href=\"".
 2573:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
 2574: 			    }
 2575: 			    $msgstatus = 
 2576: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2577: 			}
 2578: 		    }
 2579: 		}
 2580: 	    }
 2581: 	    $ctr++;
 2582: 	}
 2583:     }
 2584: 
 2585: #    if ($env{'form.handgrade'} eq 'yes') {
 2586:     if (1) {
 2587: 	# Keywords sorted in alphabatical order
 2588: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2589: 	my %keyhash = ();
 2590: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2591: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2592: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2593: 	$env{'form.keywords'} = join(' ',@keywords);
 2594: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2595: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2596: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2597: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2598: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2599: 
 2600: 	# message center - Order of message gets changed. Blank line is eliminated.
 2601: 	# New messages are saved in env for the next student.
 2602: 	# All messages are saved in nohist_handgrade.db
 2603: 	my ($ctr,$idx) = (1,1);
 2604: 	while ($ctr <= $env{'form.savemsgN'}) {
 2605: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2606: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2607: 		$idx++;
 2608: 	    }
 2609: 	    $ctr++;
 2610: 	}
 2611: 	$ctr = 0;
 2612: 	while ($ctr < $ngrade) {
 2613: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2614: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2615: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2616: 		$idx++;
 2617: 	    }
 2618: 	    $ctr++;
 2619: 	}
 2620: 	$env{'form.savemsgN'} = --$idx;
 2621: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2622: 	my $putresult = &Apache::lonnet::put
 2623: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2624:     }
 2625:     # Called by Save & Refresh from Highlight Attribute Window
 2626:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2627:     if ($env{'form.refresh'} eq 'on') {
 2628: 	my ($ctr,$total) = (0,0);
 2629: 	while ($ctr < $ngrade) {
 2630: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2631: 	    $ctr++;
 2632: 	}
 2633: 	$env{'form.NTSTU'}=$ngrade;
 2634: 	$ctr = 0;
 2635: 	while ($ctr < $total) {
 2636: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2637: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2638: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2639: 	    &submission($request,$ctr,$total-1,$symb);
 2640: 	    $ctr++;
 2641: 	}
 2642: 	return '';
 2643:     }
 2644: 
 2645:     # Get the next/previous one or group of students
 2646:     my $firststu = $env{'form.unamedom0'};
 2647:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2648:     my $ctr = 2;
 2649:     while ($laststu eq '') {
 2650: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2651: 	$ctr++;
 2652: 	$laststu = $firststu if ($ctr > $ngrade);
 2653:     }
 2654: 
 2655:     my (@parsedlist,@nextlist);
 2656:     my ($nextflg) = 0;
 2657:     foreach my $item (sort 
 2658: 	     {
 2659: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2660: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2661: 		 }
 2662: 		 return $a cmp $b;
 2663: 	     } (keys(%$fullname))) {
 2664: # FIXME: this is fishy, looks like the button label
 2665: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2666: 	    push(@parsedlist,$item);
 2667: 	}
 2668: 	$nextflg = 1 if ($item eq $laststu);
 2669: 	if ($button eq 'Previous') {
 2670: 	    last if ($item eq $firststu);
 2671: 	    push(@parsedlist,$item);
 2672: 	}
 2673:     }
 2674:     $ctr = 0;
 2675: # FIXME: this is fishy, looks like the button label
 2676:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2677:     my $res_error;
 2678:     my ($partlist) = &response_type($symb,\$res_error);
 2679:     if ($res_error) {
 2680:         $request->print(&navmap_errormsg());
 2681:         return;
 2682:     }
 2683:     foreach my $student (@parsedlist) {
 2684: 	my $submitonly=$env{'form.submitonly'};
 2685: 	my ($uname,$udom) = split(/:/,$student);
 2686: 	
 2687: 	if ($submitonly eq 'queued') {
 2688: 	    my %queue_status = 
 2689: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2690: 							$udom,$uname);
 2691: 	    next if (!defined($queue_status{'gradingqueue'}));
 2692: 	}
 2693: 
 2694: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2695: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2696: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2697: 	    my $submitted = 0;
 2698: 	    my $ungraded = 0;
 2699: 	    my $incorrect = 0;
 2700: 	    foreach my $item (keys(%status)) {
 2701: 		$submitted = 1 if ($status{$item} ne 'nothing');
 2702: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 2703: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 2704: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 2705: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2706: 		    $submitted = 0;
 2707: 		}
 2708: 	    }
 2709: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2710: 				     $submitonly eq 'incorrect' ||
 2711: 				     $submitonly eq 'graded'));
 2712: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2713: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2714: 	}
 2715: 	push(@nextlist,$student) if ($ctr < $ntstu);
 2716: 	last if ($ctr == $ntstu);
 2717: 	$ctr++;
 2718:     }
 2719: 
 2720:     $ctr = 0;
 2721:     my $total = scalar(@nextlist)-1;
 2722: 
 2723:     foreach (sort(@nextlist)) {
 2724: 	my ($uname,$udom,$submitter) = split(/:/);
 2725: 	$env{'form.student'}  = $uname;
 2726: 	$env{'form.userdom'}  = $udom;
 2727: 	$env{'form.fullname'} = $$fullname{$_};
 2728: 	&submission($request,$ctr,$total,$symb);
 2729: 	$ctr++;
 2730:     }
 2731:     if ($total < 0) {
 2732: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
 2733: 	$request->print($the_end);
 2734:     }
 2735:     return '';
 2736: }
 2737: 
 2738: #---- Save the score and award for each student, if changed
 2739: sub saveHandGrade {
 2740:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 2741:     my @version_parts;
 2742:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 2743: 					   $env{'request.course.id'});
 2744:     if (!&canmodify($usec)) { return('not_allowed'); }
 2745:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 2746:     my @parts_graded;
 2747:     my %newrecord  = ();
 2748:     my ($pts,$wgt) = ('','');
 2749:     my %aggregate = ();
 2750:     my $aggregateflag = 0;
 2751:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 2752:     foreach my $new_part (@parts) {
 2753: 	#collaborator ($submi may vary for different parts
 2754: 	if ($submitter && $new_part ne $part) { next; }
 2755: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 2756: 	if ($dropMenu eq 'excused') {
 2757: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 2758: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 2759: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 2760: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 2761: 		}
 2762: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 2763: 	    }
 2764: 	} elsif ($dropMenu eq 'reset status'
 2765: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 2766: 	    foreach my $key (keys(%record)) {
 2767: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 2768: 	    }
 2769: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2770: 		"$env{'user.name'}:$env{'user.domain'}";
 2771:             my $totaltries = $record{'resource.'.$part.'.tries'};
 2772: 
 2773:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2774: 					       [$new_part]);
 2775:             my $aggtries =$totaltries;
 2776:             if ($last_resets{$new_part}) {
 2777:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 2778: 					   $new_part);
 2779:             }
 2780: 
 2781:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 2782:             if ($aggtries > 0) {
 2783:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 2784:                 $aggregateflag = 1;
 2785:             }
 2786: 	} elsif ($dropMenu eq '') {
 2787: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 2788: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 2789: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 2790: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 2791: 		next;
 2792: 	    }
 2793: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 2794: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 2795: 	    my $partial= $pts/$wgt;
 2796: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 2797: 		#do not update score for part if not changed.
 2798:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 2799: 		next;
 2800: 	    } else {
 2801: 	        push(@parts_graded,$new_part);
 2802: 	    }
 2803: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 2804: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 2805: 	    }
 2806: 	    my $reckey = 'resource.'.$new_part.'.solved';
 2807: 	    if ($partial == 0) {
 2808: 		if ($record{$reckey} ne 'incorrect_by_override') {
 2809: 		    $newrecord{$reckey} = 'incorrect_by_override';
 2810: 		}
 2811: 	    } else {
 2812: 		if ($record{$reckey} ne 'correct_by_override') {
 2813: 		    $newrecord{$reckey} = 'correct_by_override';
 2814: 		}
 2815: 	    }	    
 2816: 	    if ($submitter && 
 2817: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 2818: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 2819: 	    }
 2820: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2821: 		"$env{'user.name'}:$env{'user.domain'}";
 2822: 	}
 2823: 	# unless problem has been graded, set flag to version the submitted files
 2824: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 2825: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 2826: 	        $dropMenu eq 'reset status')
 2827: 	   {
 2828: 	    push(@version_parts,$new_part);
 2829: 	}
 2830:     }
 2831:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2832:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2833: 
 2834:     if (%newrecord) {
 2835:         if (@version_parts) {
 2836:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 2837:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 2838: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 2839: 	    foreach my $new_part (@version_parts) {
 2840: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 2841: 				$new_part,\%newrecord);
 2842: 	    }
 2843:         }
 2844: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 2845: 				$env{'request.course.id'},$domain,$stuname);
 2846: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 2847: 				     $cdom,$cnum,$domain,$stuname);
 2848:     }
 2849:     if ($aggregateflag) {
 2850:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 2851: 			      $cdom,$cnum);
 2852:     }
 2853:     return ('',$pts,$wgt);
 2854: }
 2855: 
 2856: sub check_and_remove_from_queue {
 2857:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 2858:     my @ungraded_parts;
 2859:     foreach my $part (@{$parts}) {
 2860: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 2861: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 2862: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 2863: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 2864: 		) {
 2865: 	    push(@ungraded_parts, $part);
 2866: 	}
 2867:     }
 2868:     if ( !@ungraded_parts ) {
 2869: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 2870: 					       $cnum,$domain,$stuname);
 2871:     }
 2872: }
 2873: 
 2874: sub handback_files {
 2875:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 2876:     my $portfolio_root = '/userfiles/portfolio';
 2877:     my $res_error;
 2878:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2879:     if ($res_error) {
 2880:         $request->print('<br />'.&navmap_errormsg().'<br />');
 2881:         return;
 2882:     }
 2883:     my @part_response_id = &flatten_responseType($responseType);
 2884:     foreach my $part_response_id (@part_response_id) {
 2885:     	my ($part_id,$resp_id) = @{ $part_response_id };
 2886: 	my $part_resp = join('_',@{ $part_response_id });
 2887:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part eq $part_id)) {
 2888:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 2889:                 my $file_counter = 1;
 2890: 		my $file_msg;
 2891:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
 2892:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
 2893:                     my ($directory,$answer_file) = 
 2894:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
 2895:                     my ($answer_name,$answer_ver,$answer_ext) =
 2896: 		        &file_name_version_ext($answer_file);
 2897: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 2898:                     my $getpropath = 1;
 2899: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
 2900: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2901:                     # fix file name
 2902:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 2903:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 2904:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
 2905:             	                                $save_file_name);
 2906:                     if ($result !~ m|^/uploaded/|) {
 2907:                         $request->print('<br /><span class="LC_error">'.
 2908:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 2909:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
 2910:                                         '</span>');
 2911:                     } else {
 2912:                         # mark the file as read only
 2913:                         my @files = ($save_file_name);
 2914:                         my @what = ($symb,$env{'request.course.id'},'handback');
 2915:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
 2916: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 2917: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 2918: 			}
 2919:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 2920: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
 2921: 
 2922:                     }
 2923:                     $request->print('<br />'.&mt('[_1] will be the uploaded file name [_2]','<span class="LC_info">'.$fname.'</span>','<span class="LC_filename">'.$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter}.'</span>'));
 2924:                     $file_counter++;
 2925:                 }
 2926: 		my $subject = "File Handed Back by Instructor ";
 2927: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
 2928: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
 2929: 		$message .= ' The returned file(s) are named: '. $file_msg;
 2930: 		$message .= " and can be found in your portfolio space.";
 2931: 		my ($feedurl,$showsymb) = 
 2932: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
 2933:                 my $restitle = &Apache::lonnet::gettitle($symb);
 2934: 		my $msgstatus = 
 2935:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
 2936: 			 ' (File Returned) ['.$restitle.']',$message,undef,
 2937:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
 2938:             }
 2939:         }
 2940:     return;
 2941: }
 2942: 
 2943: sub get_feedurl_and_symb {
 2944:     my ($symb,$uname,$udom) = @_;
 2945:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2946:     $url = &Apache::lonnet::clutter($url);
 2947:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 2948: 					$symb,$udom,$uname);
 2949:     if ($encrypturl =~ /^yes$/i) {
 2950: 	&Apache::lonenc::encrypted(\$url,1);
 2951: 	&Apache::lonenc::encrypted(\$symb,1);
 2952:     }
 2953:     return ($url,$symb);
 2954: }
 2955: 
 2956: sub get_submitted_files {
 2957:     my ($udom,$uname,$partid,$respid,$record) = @_;
 2958:     my @files;
 2959:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 2960:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 2961:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 2962:     	    push(@files,$file_url.$file);
 2963:         }
 2964:     }
 2965:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 2966:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 2967:     }
 2968:     return (\@files);
 2969: }
 2970: 
 2971: # ----------- Provides number of tries since last reset.
 2972: sub get_num_tries {
 2973:     my ($record,$last_reset,$part) = @_;
 2974:     my $timestamp = '';
 2975:     my $num_tries = 0;
 2976:     if ($$record{'version'}) {
 2977:         for (my $version=$$record{'version'};$version>=1;$version--) {
 2978:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 2979:                 $timestamp = $$record{$version.':timestamp'};
 2980:                 if ($timestamp > $last_reset) {
 2981:                     $num_tries ++;
 2982:                 } else {
 2983:                     last;
 2984:                 }
 2985:             }
 2986:         }
 2987:     }
 2988:     return $num_tries;
 2989: }
 2990: 
 2991: # ----------- Determine decrements required in aggregate totals 
 2992: sub decrement_aggs {
 2993:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 2994:     my %decrement = (
 2995:                         attempts => 0,
 2996:                         users => 0,
 2997:                         correct => 0
 2998:                     );
 2999:     $decrement{'attempts'} = $aggtries;
 3000:     if ($solvedstatus =~ /^correct/) {
 3001:         $decrement{'correct'} = 1;
 3002:     }
 3003:     if ($aggtries == $totaltries) {
 3004:         $decrement{'users'} = 1;
 3005:     }
 3006:     foreach my $type (keys(%decrement)) {
 3007:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 3008:     }
 3009:     return;
 3010: }
 3011: 
 3012: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3013: sub get_last_resets {
 3014:     my ($symb,$courseid,$partids) =@_;
 3015:     my %last_resets;
 3016:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3017:     my $cname = $env{'course.'.$courseid.'.num'};
 3018:     my @keys;
 3019:     foreach my $part (@{$partids}) {
 3020: 	push(@keys,"$symb\0$part\0resettime");
 3021:     }
 3022:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3023: 				     $cdom,$cname);
 3024:     foreach my $part (@{$partids}) {
 3025: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3026:     }
 3027:     return %last_resets;
 3028: }
 3029: 
 3030: # ----------- Handles creating versions for portfolio files as answers
 3031: sub version_portfiles {
 3032:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3033:     my $version_parts = join('|',@$v_flag);
 3034:     my @returned_keys;
 3035:     my $parts = join('|', @$parts_graded);
 3036:     my $portfolio_root = '/userfiles/portfolio';
 3037:     foreach my $key (keys(%$record)) {
 3038:         my $new_portfiles;
 3039:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3040:             my @versioned_portfiles;
 3041:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3042:             foreach my $file (@portfiles) {
 3043:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 3044:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 3045: 		my ($answer_name,$answer_ver,$answer_ext) =
 3046: 		    &file_name_version_ext($answer_file);
 3047:                 my $getpropath = 1;    
 3048:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
 3049:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 3050:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 3051:                 if ($new_answer ne 'problem getting file') {
 3052:                     push(@versioned_portfiles, $directory.$new_answer);
 3053:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 3054:                         [$directory.$new_answer],
 3055:                         [$symb,$env{'request.course.id'},'graded']);
 3056:                 }
 3057:             }
 3058:             $$record{$key} = join(',',@versioned_portfiles);
 3059:             push(@returned_keys,$key);
 3060:         }
 3061:     } 
 3062:     return (@returned_keys);   
 3063: }
 3064: 
 3065: sub get_next_version {
 3066:     my ($answer_name, $answer_ext, $dir_list) = @_;
 3067:     my $version;
 3068:     foreach my $row (@$dir_list) {
 3069:         my ($file) = split(/\&/,$row,2);
 3070:         my ($file_name,$file_version,$file_ext) =
 3071: 	    &file_name_version_ext($file);
 3072:         if (($file_name eq $answer_name) && 
 3073: 	    ($file_ext eq $answer_ext)) {
 3074:                 # gets here if filename and extension match, regardless of version
 3075:                 if ($file_version ne '') {
 3076:                 # a versioned file is found  so save it for later
 3077:                 if ($file_version > $version) {
 3078: 		    $version = $file_version;
 3079: 	        }
 3080:             }
 3081:         }
 3082:     } 
 3083:     $version ++;
 3084:     return($version);
 3085: }
 3086: 
 3087: sub version_selected_portfile {
 3088:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3089:     my ($answer_name,$answer_ver,$answer_ext) =
 3090:         &file_name_version_ext($file_name);
 3091:     my $new_answer;
 3092:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3093:     if($env{'form.copy'} eq '-1') {
 3094:         $new_answer = 'problem getting file';
 3095:     } else {
 3096:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3097:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3098:                             $stu_name,$domain,'copy',
 3099: 		        '/portfolio'.$directory.$new_answer);
 3100:     }    
 3101:     return ($new_answer);
 3102: }
 3103: 
 3104: sub file_name_version_ext {
 3105:     my ($file)=@_;
 3106:     my @file_parts = split(/\./, $file);
 3107:     my ($name,$version,$ext);
 3108:     if (@file_parts > 1) {
 3109: 	$ext=pop(@file_parts);
 3110: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3111: 	    $version=pop(@file_parts);
 3112: 	}
 3113: 	$name=join('.',@file_parts);
 3114:     } else {
 3115: 	$name=join('.',@file_parts);
 3116:     }
 3117:     return($name,$version,$ext);
 3118: }
 3119: 
 3120: #--------------------------------------------------------------------------------------
 3121: #
 3122: #-------------------------- Next few routines handles grading by section or whole class
 3123: #
 3124: #--- Javascript to handle grading by section or whole class
 3125: sub viewgrades_js {
 3126:     my ($request) = shift;
 3127: 
 3128:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3129:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
 3130:    function writePoint(partid,weight,point) {
 3131: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3132: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3133: 	if (point == "textval") {
 3134: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3135: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3136: 		alert("$alertmsg"+parseFloat(point));
 3137: 		var resetbox = false;
 3138: 		for (var i=0; i<radioButton.length; i++) {
 3139: 		    if (radioButton[i].checked) {
 3140: 			textbox.value = i;
 3141: 			resetbox = true;
 3142: 		    }
 3143: 		}
 3144: 		if (!resetbox) {
 3145: 		    textbox.value = "";
 3146: 		}
 3147: 		return;
 3148: 	    }
 3149: 	    if (parseFloat(point) > parseFloat(weight)) {
 3150: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3151: 				   ") greater than the weight for the part. Accept?");
 3152: 		if (resp == false) {
 3153: 		    textbox.value = "";
 3154: 		    return;
 3155: 		}
 3156: 	    }
 3157: 	    for (var i=0; i<radioButton.length; i++) {
 3158: 		radioButton[i].checked=false;
 3159: 		if (parseFloat(point) == i) {
 3160: 		    radioButton[i].checked=true;
 3161: 		}
 3162: 	    }
 3163: 
 3164: 	} else {
 3165: 	    textbox.value = parseFloat(point);
 3166: 	}
 3167: 	for (i=0;i<document.classgrade.total.value;i++) {
 3168: 	    var user = document.classgrade["ctr"+i].value;
 3169: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3170: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3171: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3172: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3173: 	    if (saveval != "correct") {
 3174: 		scorename.value = point;
 3175: 		if (selname[0].selected != true) {
 3176: 		    selname[0].selected = true;
 3177: 		}
 3178: 	    }
 3179: 	}
 3180: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3181:     }
 3182: 
 3183:     function writeRadText(partid,weight) {
 3184: 	var selval   = document.classgrade["SELVAL_"+partid];
 3185: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3186:         var override = document.classgrade["FORCE_"+partid].checked;
 3187: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3188: 	if (selval[1].selected || selval[2].selected) {
 3189: 	    for (var i=0; i<radioButton.length; i++) {
 3190: 		radioButton[i].checked=false;
 3191: 
 3192: 	    }
 3193: 	    textbox.value = "";
 3194: 
 3195: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3196: 		var user = document.classgrade["ctr"+i].value;
 3197: 		user = user.replace(new RegExp(':', 'g'),"_");
 3198: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3199: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3200: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3201: 		if ((saveval != "correct") || override) {
 3202: 		    scorename.value = "";
 3203: 		    if (selval[1].selected) {
 3204: 			selname[1].selected = true;
 3205: 		    } else {
 3206: 			selname[2].selected = true;
 3207: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3208: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3209: 		    }
 3210: 		}
 3211: 	    }
 3212: 	} else {
 3213: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3214: 		var user = document.classgrade["ctr"+i].value;
 3215: 		user = user.replace(new RegExp(':', 'g'),"_");
 3216: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3217: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3218: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3219: 		if ((saveval != "correct") || override) {
 3220: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3221: 		    selname[0].selected = true;
 3222: 		}
 3223: 	    }
 3224: 	}	    
 3225:     }
 3226: 
 3227:     function changeSelect(partid,user) {
 3228: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3229: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3230: 	var point  = textbox.value;
 3231: 	var weight = document.classgrade["weight_"+partid].value;
 3232: 
 3233: 	if (isNaN(point) || parseFloat(point) < 0) {
 3234: 	    alert("$alertmsg"+parseFloat(point));
 3235: 	    textbox.value = "";
 3236: 	    return;
 3237: 	}
 3238: 	if (parseFloat(point) > parseFloat(weight)) {
 3239: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3240: 			       ") greater than the weight of the part. Accept?");
 3241: 	    if (resp == false) {
 3242: 		textbox.value = "";
 3243: 		return;
 3244: 	    }
 3245: 	}
 3246: 	selval[0].selected = true;
 3247:     }
 3248: 
 3249:     function changeOneScore(partid,user) {
 3250: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3251: 	if (selval[1].selected || selval[2].selected) {
 3252: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3253: 	    if (selval[2].selected) {
 3254: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3255: 	    }
 3256:         }
 3257:     }
 3258: 
 3259:     function resetEntry(numpart) {
 3260: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3261: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3262: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3263: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3264: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3265: 	    for (var i=0; i<radioButton.length; i++) {
 3266: 		radioButton[i].checked=false;
 3267: 
 3268: 	    }
 3269: 	    textbox.value = "";
 3270: 	    selval[0].selected = true;
 3271: 
 3272: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3273: 		var user = document.classgrade["ctr"+i].value;
 3274: 		user = user.replace(new RegExp(':', 'g'),"_");
 3275: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3276: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3277: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3278: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3279: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3280: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3281: 		if (saveselval == "excused") {
 3282: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3283: 		} else {
 3284: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3285: 		}
 3286: 	    }
 3287: 	}
 3288:     }
 3289: 
 3290: VIEWJAVASCRIPT
 3291: }
 3292: 
 3293: #--- show scores for a section or whole class w/ option to change/update a score
 3294: sub viewgrades {
 3295:     my ($request,$symb) = @_;
 3296:     &viewgrades_js($request);
 3297: 
 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="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3317: 
 3318:     my ($common_header,$specific_header);
 3319:     if ($env{'form.section'} eq 'all') {
 3320: 	$common_header = &mt('Assign Common Grade to Class');
 3321:         $specific_header = &mt('Assign Grade to Specific Students in Class');
 3322:     } elsif ($env{'form.section'} eq 'none') {
 3323:         $common_header = &mt('Assign Common Grade to Students in no Section');
 3324: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
 3325:     } else {
 3326:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3327:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3328: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3329:     }
 3330:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
 3331:     #radio buttons/text box for assigning points for a section or class.
 3332:     #handles different parts of a problem
 3333:     my $res_error;
 3334:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3335:     if ($res_error) {
 3336:         return &navmap_errormsg();
 3337:     }
 3338:     my %weight = ();
 3339:     my $ctsparts = 0;
 3340:     my %seen = ();
 3341:     my @part_response_id = &flatten_responseType($responseType);
 3342:     foreach my $part_response_id (@part_response_id) {
 3343:     	my ($partid,$respid) = @{ $part_response_id };
 3344: 	my $part_resp = join('_',@{ $part_response_id });
 3345: 	next if $seen{$partid};
 3346: 	$seen{$partid}++;
 3347: 	my $handgrade=$$handgrade{$part_resp};
 3348: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3349: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3350: 
 3351: 	my $display_part=&get_display_part($partid,$symb);
 3352: 	my $radio.='<table border="0"><tr>';  
 3353: 	my $ctr = 0;
 3354: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3355: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3356: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3357: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3358: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3359: 	    $ctr++;
 3360: 	}
 3361: 	$radio.='</tr></table>';
 3362: 	my $line = '<input type="text" name="TEXTVAL_'.
 3363: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 3364: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3365: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3366: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
 3367: 	    'onchange="javascript:writeRadText(\''.$partid.'\','.
 3368: 		$weight{$partid}.')"> '.
 3369: 	    '<option selected="selected"> </option>'.
 3370: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3371: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3372: 	    '</select></td>'.
 3373:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3374: 	$line.='<input type="hidden" name="partid_'.
 3375: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3376: 	$line.='<input type="hidden" name="weight_'.
 3377: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3378: 
 3379: 	$result.=
 3380: 	    &Apache::loncommon::start_data_table_row()."\n".
 3381: 	    '<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>'.
 3382: 	    &Apache::loncommon::end_data_table_row()."\n";
 3383: 	$ctsparts++;
 3384:     }
 3385:     $result.=&Apache::loncommon::end_data_table()."\n".
 3386: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3387:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3388: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 3389: 
 3390:     #table listing all the students in a section/class
 3391:     #header of table
 3392:     $result.= '<h3>'.$specific_header.'</h3>'.
 3393:               &Apache::loncommon::start_data_table().
 3394: 	      &Apache::loncommon::start_data_table_header_row().
 3395: 	      '<th>'.&mt('No.').'</th>'.
 3396: 	      '<th>'.&nameUserString('header')."</th>\n";
 3397:     my $partserror;
 3398:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3399:     if ($partserror) {
 3400:         return &navmap_errormsg();
 3401:     }
 3402:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3403:     my @partids = ();
 3404:     foreach my $part (@parts) {
 3405: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3406:         my $narrowtext = &mt('Tries');
 3407: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3408: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3409: 	my ($partid) = &split_part_type($part);
 3410:         push(@partids,$partid);
 3411: #
 3412: # FIXME: Looks like $display looks at English text
 3413: #
 3414: 	my $display_part=&get_display_part($partid,$symb);
 3415: 	if ($display =~ /^Partial Credit Factor/) {
 3416: 	    $result.='<th>'.
 3417: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
 3418: 		    $display_part,$weight{$partid}).'</th>'."\n";
 3419: 	    next;
 3420: 	    
 3421: 	} else {
 3422: 	    if ($display =~ /Problem Status/) {
 3423: 		my $grade_status_mt = &mt('Grade Status');
 3424: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3425: 	    }
 3426: 	    my $part_mt = &mt('Part:');
 3427: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3428: 	}
 3429: 
 3430: 	$result.='<th>'.$display.'</th>'."\n";
 3431:     }
 3432:     $result.=&Apache::loncommon::end_data_table_header_row();
 3433: 
 3434:     my %last_resets = 
 3435: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3436: 
 3437:     #get info for each student
 3438:     #list all the students - with points and grade status
 3439:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3440:     my $ctr = 0;
 3441:     foreach (sort 
 3442: 	     {
 3443: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3444: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3445: 		 }
 3446: 		 return $a cmp $b;
 3447: 	     } (keys(%$fullname))) {
 3448: 	$ctr++;
 3449: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3450: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3451:     }
 3452:     $result.=&Apache::loncommon::end_data_table();
 3453:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3454:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3455: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 3456:     if (scalar(%$fullname) eq 0) {
 3457: 	my $colspan=3+scalar(@parts);
 3458: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3459:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3460: 	$result='<span class="LC_warning">'.
 3461: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3462: 	        $section_display, $stu_status).
 3463: 	    '</span>';
 3464:     }
 3465:     return $result;
 3466: }
 3467: 
 3468: #--- call by previous routine to display each student
 3469: sub viewstudentgrade {
 3470:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3471:     my ($uname,$udom) = split(/:/,$student);
 3472:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3473:     my %aggregates = (); 
 3474:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3475: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3476: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3477: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3478: 	'\');" target="_self">'.$fullname.'</a> '.
 3479: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3480:     $student=~s/:/_/; # colon doen't work in javascript for names
 3481:     foreach my $apart (@$parts) {
 3482: 	my ($part,$type) = &split_part_type($apart);
 3483: 	my $score=$record{"resource.$part.$type"};
 3484:         $result.='<td align="center">';
 3485:         my ($aggtries,$totaltries);
 3486:         unless (exists($aggregates{$part})) {
 3487: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3488: 
 3489: 	    $aggtries = $totaltries;
 3490:             if ($$last_resets{$part}) {  
 3491:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3492: 					   $part);
 3493:             }
 3494:             $result.='<input type="hidden" name="'.
 3495:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3496:             $result.='<input type="hidden" name="'.
 3497:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3498:             $aggregates{$part} = 1;
 3499:         }
 3500: 	if ($type eq 'awarded') {
 3501: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3502: 	    $result.='<input type="hidden" name="'.
 3503: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3504: 	    $result.='<input type="text" name="'.
 3505: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3506:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3507: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3508: 	} elsif ($type eq 'solved') {
 3509: 	    my ($status,$foo)=split(/_/,$score,2);
 3510: 	    $status = 'nothing' if ($status eq '');
 3511: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3512: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3513: 	    $result.='&nbsp;<select name="'.
 3514: 		'GD_'.$student.'_'.$part.'_solved" '.
 3515:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3516: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3517: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3518: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3519: 	    $result.="</select>&nbsp;</td>\n";
 3520: 	} else {
 3521: 	    $result.='<input type="hidden" name="'.
 3522: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3523: 		    "\n";
 3524: 	    $result.='<input type="text" name="'.
 3525: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3526: 		'value="'.$score.'" size="4" /></td>'."\n";
 3527: 	}
 3528:     }
 3529:     $result.=&Apache::loncommon::end_data_table_row();
 3530:     return $result;
 3531: }
 3532: 
 3533: #--- change scores for all the students in a section/class
 3534: #    record does not get update if unchanged
 3535: sub editgrades {
 3536:     my ($request,$symb) = @_;
 3537: 
 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:     my $msg = '<p><b>'.
 3749: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 3750: 	    $rec_update,$count).'</b><br />'.
 3751: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 3752: 	'</b></p>';
 3753:     return $title.$msg.$result;
 3754: }
 3755: 
 3756: sub split_part_type {
 3757:     my ($partstr) = @_;
 3758:     my ($temp,@allparts)=split(/_/,$partstr);
 3759:     my $type=pop(@allparts);
 3760:     my $part=join('_',@allparts);
 3761:     return ($part,$type);
 3762: }
 3763: 
 3764: #------------- end of section for handling grading by section/class ---------
 3765: #
 3766: #----------------------------------------------------------------------------
 3767: 
 3768: 
 3769: #----------------------------------------------------------------------------
 3770: #
 3771: #-------------------------- Next few routines handles grading by csv upload
 3772: #
 3773: #--- Javascript to handle csv upload
 3774: sub csvupload_javascript_reverse_associate {
 3775:     my $error1=&mt('You need to specify the username or the student/employee ID');
 3776:     my $error2=&mt('You need to specify at least one grading field');
 3777:   return(<<ENDPICK);
 3778:   function verify(vf) {
 3779:     var foundsomething=0;
 3780:     var founduname=0;
 3781:     var foundID=0;
 3782:     for (i=0;i<=vf.nfields.value;i++) {
 3783:       tw=eval('vf.f'+i+'.selectedIndex');
 3784:       if (i==0 && tw!=0) { foundID=1; }
 3785:       if (i==1 && tw!=0) { founduname=1; }
 3786:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 3787:     }
 3788:     if (founduname==0 && foundID==0) {
 3789: 	alert('$error1');
 3790: 	return;
 3791:     }
 3792:     if (foundsomething==0) {
 3793: 	alert('$error2');
 3794: 	return;
 3795:     }
 3796:     vf.submit();
 3797:   }
 3798:   function flip(vf,tf) {
 3799:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3800:     var i;
 3801:     for (i=0;i<=vf.nfields.value;i++) {
 3802:       //can not pick the same destination field for both name and domain
 3803:       if (((i ==0)||(i ==1)) && 
 3804:           ((tf==0)||(tf==1)) && 
 3805:           (i!=tf) &&
 3806:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3807:         eval('vf.f'+i+'.selectedIndex=0;')
 3808:       }
 3809:     }
 3810:   }
 3811: ENDPICK
 3812: }
 3813: 
 3814: sub csvupload_javascript_forward_associate {
 3815:     my $error1=&mt('You need to specify the username or the student/employee ID');
 3816:     my $error2=&mt('You need to specify at least one grading field');
 3817:   return(<<ENDPICK);
 3818:   function verify(vf) {
 3819:     var foundsomething=0;
 3820:     var founduname=0;
 3821:     var foundID=0;
 3822:     for (i=0;i<=vf.nfields.value;i++) {
 3823:       tw=eval('vf.f'+i+'.selectedIndex');
 3824:       if (tw==1) { foundID=1; }
 3825:       if (tw==2) { founduname=1; }
 3826:       if (tw>3) { foundsomething=1; }
 3827:     }
 3828:     if (founduname==0 && foundID==0) {
 3829: 	alert('$error1');
 3830: 	return;
 3831:     }
 3832:     if (foundsomething==0) {
 3833: 	alert('$error2');
 3834: 	return;
 3835:     }
 3836:     vf.submit();
 3837:   }
 3838:   function flip(vf,tf) {
 3839:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3840:     var i;
 3841:     //can not pick the same destination field twice
 3842:     for (i=0;i<=vf.nfields.value;i++) {
 3843:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3844:         eval('vf.f'+i+'.selectedIndex=0;')
 3845:       }
 3846:     }
 3847:   }
 3848: ENDPICK
 3849: }
 3850: 
 3851: sub csvuploadmap_header {
 3852:     my ($request,$symb,$datatoken,$distotal)= @_;
 3853:     my $javascript;
 3854:     if ($env{'form.upfile_associate'} eq 'reverse') {
 3855: 	$javascript=&csvupload_javascript_reverse_associate();
 3856:     } else {
 3857: 	$javascript=&csvupload_javascript_forward_associate();
 3858:     }
 3859: 
 3860:     $symb = &Apache::lonenc::check_encrypt($symb);
 3861:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
 3862:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
 3863:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
 3864:     my $reverse=&mt("Reverse Association");
 3865:     $request->print(<<ENDPICK);
 3866: <br />
 3867: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 3868: <input type="hidden" name="associate"  value="" />
 3869: <input type="hidden" name="phase"      value="three" />
 3870: <input type="hidden" name="datatoken"  value="$datatoken" />
 3871: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 3872: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 3873: <input type="hidden" name="upfile_associate" 
 3874:                                        value="$env{'form.upfile_associate'}" />
 3875: <input type="hidden" name="symb"       value="$symb" />
 3876: <input type="hidden" name="command"    value="csvuploadoptions" />
 3877: <hr />
 3878: ENDPICK
 3879:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
 3880:     return '';
 3881: 
 3882: }
 3883: 
 3884: sub csvupload_fields {
 3885:     my ($symb,$errorref) = @_;
 3886:     my (@parts) = &getpartlist($symb,$errorref);
 3887:     if (ref($errorref)) {
 3888:         if ($$errorref) {
 3889:             return;
 3890:         }
 3891:     }
 3892: 
 3893:     my @fields=(['ID','Student/Employee ID'],
 3894: 		['username','Student Username'],
 3895: 		['domain','Student Domain']);
 3896:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3897:     foreach my $part (sort(@parts)) {
 3898: 	my @datum;
 3899: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3900: 	my $name=$part;
 3901: 	if  (!$display) { $display = $name; }
 3902: 	@datum=($name,$display);
 3903: 	if ($name=~/^stores_(.*)_awarded/) {
 3904: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 3905: 	}
 3906: 	push(@fields,\@datum);
 3907:     }
 3908:     return (@fields);
 3909: }
 3910: 
 3911: sub csvuploadmap_footer {
 3912:     my ($request,$i,$keyfields) =@_;
 3913:     $request->print(<<ENDPICK);
 3914: </table>
 3915: <input type="hidden" name="nfields" value="$i" />
 3916: <input type="hidden" name="keyfields" value="$keyfields" />
 3917: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
 3918: </form>
 3919: ENDPICK
 3920: }
 3921: 
 3922: sub checkforfile_js {
 3923:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 3924:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
 3925:     function checkUpload(formname) {
 3926: 	if (formname.upfile.value == "") {
 3927: 	    alert("$alertmsg");
 3928: 	    return false;
 3929: 	}
 3930: 	formname.submit();
 3931:     }
 3932: CSVFORMJS
 3933:     return $result;
 3934: }
 3935: 
 3936: sub upcsvScores_form {
 3937:     my ($request,$symb) = @_;
 3938:     if (!$symb) {return '';}
 3939:     my $result=&checkforfile_js();
 3940:     $result.=&Apache::loncommon::start_data_table().
 3941:              &Apache::loncommon::start_data_table_header_row().
 3942:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
 3943:              &Apache::loncommon::end_data_table_header_row().
 3944:              &Apache::loncommon::start_data_table_row().'<td>';
 3945:     my $upload=&mt("Upload Scores");
 3946:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 3947:     my $ignore=&mt('Ignore First Line');
 3948:     $symb = &Apache::lonenc::check_encrypt($symb);
 3949:     $result.=<<ENDUPFORM;
 3950: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3951: <input type="hidden" name="symb" value="$symb" />
 3952: <input type="hidden" name="command" value="csvuploadmap" />
 3953: $upfile_select
 3954: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 3955: </form>
 3956: ENDUPFORM
 3957:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 3958:                            &mt("How do I create a CSV file from a spreadsheet")).
 3959:              '</td>'.
 3960:             &Apache::loncommon::end_data_table_row().
 3961:             &Apache::loncommon::end_data_table();
 3962:     return $result;
 3963: }
 3964: 
 3965: 
 3966: sub csvuploadmap {
 3967:     my ($request,$symb)= @_;
 3968:     if (!$symb) {return '';}
 3969: 
 3970:     my $datatoken;
 3971:     if (!$env{'form.datatoken'}) {
 3972: 	$datatoken=&Apache::loncommon::upfile_store($request);
 3973:     } else {
 3974: 	$datatoken=$env{'form.datatoken'};
 3975: 	&Apache::loncommon::load_tmp_file($request);
 3976:     }
 3977:     my @records=&Apache::loncommon::upfile_record_sep();
 3978:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 3979:     my ($i,$keyfields);
 3980:     if (@records) {
 3981:         my $fieldserror;
 3982: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 3983:         if ($fieldserror) {
 3984:             $request->print(&navmap_errormsg());
 3985:             return;
 3986:         }
 3987: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 3988: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 3989: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 3990: 							  \@fields);
 3991: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 3992: 	    chop($keyfields);
 3993: 	} else {
 3994: 	    unshift(@fields,['none','']);
 3995: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 3996: 							    \@fields);
 3997:             foreach my $rec (@records) {
 3998:                 my %temp = &Apache::loncommon::record_sep($rec);
 3999:                 if (%temp) {
 4000:                     $keyfields=join(',',sort(keys(%temp)));
 4001:                     last;
 4002:                 }
 4003:             }
 4004: 	}
 4005:     }
 4006:     &csvuploadmap_footer($request,$i,$keyfields);
 4007: 
 4008:     return '';
 4009: }
 4010: 
 4011: sub csvuploadoptions {
 4012:     my ($request,$symb)= @_;
 4013:     my $overwrite=&mt('Overwrite any existing score');
 4014:     $request->print(<<ENDPICK);
 4015: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4016: <input type="hidden" name="command"    value="csvuploadassign" />
 4017: <p>
 4018: <label>
 4019:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4020:    $overwrite
 4021: </label>
 4022: </p>
 4023: ENDPICK
 4024:     my %fields=&get_fields();
 4025:     if (!defined($fields{'domain'})) {
 4026: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4027: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
 4028:     }
 4029:     foreach my $key (sort(keys(%env))) {
 4030: 	if ($key !~ /^form\.(.*)$/) { next; }
 4031: 	my $cleankey=$1;
 4032: 	if ($cleankey eq 'command') { next; }
 4033: 	$request->print('<input type="hidden" name="'.$cleankey.
 4034: 			'"  value="'.$env{$key}.'" />'."\n");
 4035:     }
 4036:     # FIXME do a check for any duplicated user ids...
 4037:     # FIXME do a check for any invalid user ids?...
 4038:     $request->print('<input type="submit" value="Assign Grades" /><br />
 4039: <hr /></form>'."\n");
 4040:     return '';
 4041: }
 4042: 
 4043: sub get_fields {
 4044:     my %fields;
 4045:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4046:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4047: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4048: 	    if ($env{'form.f'.$i} ne 'none') {
 4049: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4050: 	    }
 4051: 	} else {
 4052: 	    if ($env{'form.f'.$i} ne 'none') {
 4053: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4054: 	    }
 4055: 	}
 4056:     }
 4057:     return %fields;
 4058: }
 4059: 
 4060: sub csvuploadassign {
 4061:     my ($request,$symb)= @_;
 4062:     if (!$symb) {return '';}
 4063:     my $error_msg = '';
 4064:     &Apache::loncommon::load_tmp_file($request);
 4065:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4066:     my %fields=&get_fields();
 4067:     my $courseid=$env{'request.course.id'};
 4068:     my ($classlist) = &getclasslist('all',0);
 4069:     my @notallowed;
 4070:     my @skipped;
 4071:     my $countdone=0;
 4072:     foreach my $grade (@gradedata) {
 4073: 	my %entries=&Apache::loncommon::record_sep($grade);
 4074: 	my $domain;
 4075: 	if ($entries{$fields{'domain'}}) {
 4076: 	    $domain=$entries{$fields{'domain'}};
 4077: 	} else {
 4078: 	    $domain=$env{'form.default_domain'};
 4079: 	}
 4080: 	$domain=~s/\s//g;
 4081: 	my $username=$entries{$fields{'username'}};
 4082: 	$username=~s/\s//g;
 4083: 	if (!$username) {
 4084: 	    my $id=$entries{$fields{'ID'}};
 4085: 	    $id=~s/\s//g;
 4086: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4087: 	    $username=$ids{$id};
 4088: 	}
 4089: 	if (!exists($$classlist{"$username:$domain"})) {
 4090: 	    my $id=$entries{$fields{'ID'}};
 4091: 	    $id=~s/\s//g;
 4092: 	    if ($id) {
 4093: 		push(@skipped,"$id:$domain");
 4094: 	    } else {
 4095: 		push(@skipped,"$username:$domain");
 4096: 	    }
 4097: 	    next;
 4098: 	}
 4099: 	my $usec=$classlist->{"$username:$domain"}[5];
 4100: 	if (!&canmodify($usec)) {
 4101: 	    push(@notallowed,"$username:$domain");
 4102: 	    next;
 4103: 	}
 4104: 	my %points;
 4105: 	my %grades;
 4106: 	foreach my $dest (keys(%fields)) {
 4107: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4108: 		$dest eq 'domain') { next; }
 4109: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4110: 	    if ($dest=~/stores_(.*)_points/) {
 4111: 		my $part=$1;
 4112: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4113: 					      $symb,$domain,$username);
 4114:                 if ($wgt) {
 4115:                     $entries{$fields{$dest}}=~s/\s//g;
 4116:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4117:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4118:                                           : 'correct_by_override';
 4119:                     if ($pcr>1) {
 4120:                        push(@skipped,&mt("[_1]: point value larger than weight","$username:$domain"));
 4121:                     }
 4122:                     $grades{"resource.$part.awarded"}=$pcr;
 4123:                     $grades{"resource.$part.solved"}=$award;
 4124:                     $points{$part}=1;
 4125:                 } else {
 4126:                     $error_msg = "<br />" .
 4127:                         &mt("Some point values were assigned"
 4128:                             ." for problems with a weight "
 4129:                             ."of zero. These values were "
 4130:                             ."ignored.");
 4131:                 }
 4132: 	    } else {
 4133: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4134: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4135: 		my $store_key=$dest;
 4136: 		$store_key=~s/^stores/resource/;
 4137: 		$store_key=~s/_/\./g;
 4138: 		$grades{$store_key}=$entries{$fields{$dest}};
 4139: 	    }
 4140: 	}
 4141: 	if (! %grades) { 
 4142:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4143:         } else {
 4144: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4145: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4146: 					   $env{'request.course.id'},
 4147: 					   $domain,$username);
 4148: 	   if ($result eq 'ok') {
 4149: # Successfully stored
 4150: 	      $request->print('.');
 4151: # Remove from grading queue
 4152:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
 4153:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
 4154:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
 4155:                                              $domain,$username);
 4156:               $countdone++;
 4157:            } else {
 4158: 	      $request->print("<p><span class=\"LC_error\">".
 4159:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4160:                                   "$username:$domain",$result)."</span></p>");
 4161: 	   }
 4162: 	   $request->rflush();
 4163:         }
 4164:     }
 4165:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 4166:     if (@skipped) {
 4167: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 4168:         $request->print(join(', ',@skipped));
 4169:     }
 4170:     if (@notallowed) {
 4171: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 4172: 	$request->print(join(', ',@notallowed));
 4173:     }
 4174:     $request->print("<br />\n");
 4175:     return $error_msg;
 4176: }
 4177: #------------- end of section for handling csv file upload ---------
 4178: #
 4179: #-------------------------------------------------------------------
 4180: #
 4181: #-------------- Next few routines handle grading by page/sequence
 4182: #
 4183: #--- Select a page/sequence and a student to grade
 4184: sub pickStudentPage {
 4185:     my ($request,$symb) = @_;
 4186: 
 4187:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4188:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
 4189: 
 4190: function checkPickOne(formname) {
 4191:     if (radioSelection(formname.student) == null) {
 4192: 	alert("$alertmsg");
 4193: 	return;
 4194:     }
 4195:     ptr = pullDownSelection(formname.selectpage);
 4196:     formname.page.value = formname["page"+ptr].value;
 4197:     formname.title.value = formname["title"+ptr].value;
 4198:     formname.submit();
 4199: }
 4200: 
 4201: LISTJAVASCRIPT
 4202:     &commonJSfunctions($request);
 4203: 
 4204:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4205:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4206:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4207: 
 4208:     my $result='<h3><span class="LC_info">&nbsp;'.
 4209: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4210: 
 4211:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4212:     my $map_error;
 4213:     my ($titles,$symbx) = &getSymbMap($map_error);
 4214:     if ($map_error) {
 4215:         $request->print(&navmap_errormsg());
 4216:         return; 
 4217:     }
 4218:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4219: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4220: #    my $type=($curpage =~ /\.(page|sequence)/);
 4221:     my $select = '<select name="selectpage">'."\n";
 4222:     my $ctr=0;
 4223:     foreach (@$titles) {
 4224: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4225: 	$select.='<option value="'.$ctr.'" '.
 4226: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4227: 	    '>'.$showtitle.'</option>'."\n";
 4228: 	$ctr++;
 4229:     }
 4230:     $select.= '</select>';
 4231:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
 4232: 
 4233:     $ctr=0;
 4234:     foreach (@$titles) {
 4235: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4236: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4237: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4238: 	$ctr++;
 4239:     }
 4240:     $result.='<input type="hidden" name="page" />'."\n".
 4241: 	'<input type="hidden" name="title" />'."\n";
 4242: 
 4243:     my $options =
 4244: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
 4245: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
 4246:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
 4247: 
 4248:     $options =
 4249: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
 4250: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
 4251: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
 4252:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
 4253:     
 4254:     $result.=&build_section_inputs();
 4255:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4256:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4257: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4258: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."<br />\n";
 4259: 
 4260:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
 4261: 
 4262:     $result.='&nbsp;<input type="button" '.
 4263:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4264: 
 4265:     $request->print($result);
 4266: 
 4267:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4268: 	&Apache::loncommon::start_data_table().
 4269: 	&Apache::loncommon::start_data_table_header_row().
 4270: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4271: 	'<th>'.&nameUserString('header').'</th>'.
 4272: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4273: 	'<th>'.&nameUserString('header').'</th>'.
 4274: 	&Apache::loncommon::end_data_table_header_row();
 4275:  
 4276:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4277:     my $ptr = 1;
 4278:     foreach my $student (sort 
 4279: 			 {
 4280: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4281: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4282: 			     }
 4283: 			     return $a cmp $b;
 4284: 			 } (keys(%$fullname))) {
 4285: 	my ($uname,$udom) = split(/:/,$student);
 4286: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4287:                                   : '</td>');
 4288: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4289: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4290: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4291: 	$studentTable.=
 4292: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4293:                          : '');
 4294: 	$ptr++;
 4295:     }
 4296:     if ($ptr%2 == 0) {
 4297: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4298: 	    &Apache::loncommon::end_data_table_row();
 4299:     }
 4300:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4301:     $studentTable.='<input type="button" '.
 4302:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4303: 
 4304:     $request->print($studentTable);
 4305: 
 4306:     return '';
 4307: }
 4308: 
 4309: sub getSymbMap {
 4310:     my ($map_error) = @_;
 4311:     my $navmap = Apache::lonnavmaps::navmap->new();
 4312:     unless (ref($navmap)) {
 4313:         if (ref($map_error)) {
 4314:             $$map_error = 'navmap';
 4315:         }
 4316:         return;
 4317:     }
 4318:     my %symbx = ();
 4319:     my @titles = ();
 4320:     my $minder = 0;
 4321: 
 4322:     # Gather every sequence that has problems.
 4323:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4324: 					       1,0,1);
 4325:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4326: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4327: 	    my $title = $minder.'.'.
 4328: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4329: 	    push(@titles, $title); # minder in case two titles are identical
 4330: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4331: 	    $minder++;
 4332: 	}
 4333:     }
 4334:     return \@titles,\%symbx;
 4335: }
 4336: 
 4337: #
 4338: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4339: sub displayPage {
 4340:     my ($request,$symb) = @_;
 4341:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4342:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4343:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4344:     my $pageTitle = $env{'form.page'};
 4345:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4346:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4347:     my $usec=$classlist->{$env{'form.student'}}[5];
 4348: 
 4349:     #need to make sure we have the correct data for later EXT calls, 
 4350:     #thus invalidate the cache
 4351:     &Apache::lonnet::devalidatecourseresdata(
 4352:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4353:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4354:     &Apache::lonnet::clear_EXT_cache_status();
 4355: 
 4356:     if (!&canview($usec)) {
 4357: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
 4358: 	return;
 4359:     }
 4360:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4361:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4362: 	'</h3>'."\n";
 4363:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4364:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4365: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4366:     } else {
 4367: 	delete($env{'form.CODE'});
 4368:     }
 4369:     &sub_page_js($request);
 4370:     $request->print($result);
 4371: 
 4372:     my $navmap = Apache::lonnavmaps::navmap->new();
 4373:     unless (ref($navmap)) {
 4374:         $request->print(&navmap_errormsg());
 4375:         return;
 4376:     }
 4377:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4378:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4379:     if (!$map) {
 4380: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4381: 	return; 
 4382:     }
 4383:     my $iterator = $navmap->getIterator($map->map_start(),
 4384: 					$map->map_finish());
 4385: 
 4386:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4387: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4388: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4389: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4390: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4391: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4392: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4393: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
 4394: 
 4395:     if (defined($env{'form.CODE'})) {
 4396: 	$studentTable.=
 4397: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4398:     }
 4399:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4400: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4401: 
 4402:     $studentTable.='&nbsp;<span class="LC_info">'.
 4403:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 4404:         '</span>'."\n".
 4405: 	&Apache::loncommon::start_data_table().
 4406: 	&Apache::loncommon::start_data_table_header_row().
 4407: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
 4408: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4409: 	&Apache::loncommon::end_data_table_header_row();
 4410: 
 4411:     &Apache::lonxml::clear_problem_counter();
 4412:     my ($depth,$question,$prob) = (1,1,1);
 4413:     $iterator->next(); # skip the first BEGIN_MAP
 4414:     my $curRes = $iterator->next(); # for "current resource"
 4415:     while ($depth > 0) {
 4416:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4417:         if($curRes == $iterator->END_MAP) { $depth--; }
 4418: 
 4419:         if (ref($curRes) && $curRes->is_problem()) {
 4420: 	    my $parts = $curRes->parts();
 4421:             my $title = $curRes->compTitle();
 4422: 	    my $symbx = $curRes->symb();
 4423: 	    $studentTable.=
 4424: 		&Apache::loncommon::start_data_table_row().
 4425: 		'<td align="center" valign="top" >'.$prob.
 4426: 		(scalar(@{$parts}) == 1 ? '' 
 4427: 		                        : '<br />('.&mt('[_1]parts)',
 4428: 							scalar(@{$parts}).'&nbsp;')
 4429: 		 ).
 4430: 		 '</td>';
 4431: 	    $studentTable.='<td valign="top">';
 4432: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4433: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4434: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4435: 					     undef,'both',\%form);
 4436: 	    } else {
 4437: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4438: 		$companswer =~ s|<form(.*?)>||g;
 4439: 		$companswer =~ s|</form>||g;
 4440: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4441: #		    $companswer =~ s/$1/ /ms;
 4442: #		    $request->print('match='.$1."<br />\n");
 4443: #		}
 4444: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4445: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 4446: 	    }
 4447: 
 4448: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4449: 
 4450: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4451: 		if ($record{'version'} eq '') {
 4452: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4453: 		} else {
 4454: 		    my %responseType = ();
 4455: 		    foreach my $partid (@{$parts}) {
 4456: 			my @responseIds =$curRes->responseIds($partid);
 4457: 			my @responseType =$curRes->responseType($partid);
 4458: 			my %responseIds;
 4459: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4460: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4461: 			}
 4462: 			$responseType{$partid} = \%responseIds;
 4463: 		    }
 4464: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4465: 
 4466: 		}
 4467: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4468: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4469: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4470: 									$env{'request.course.id'},
 4471: 									'','.submission');
 4472:  
 4473: 	    }
 4474: 	    if (&canmodify($usec)) {
 4475:             $studentTable.=&gradeBox_start();
 4476: 		foreach my $partid (@{$parts}) {
 4477: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4478: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4479: 		    $question++;
 4480: 		}
 4481:             $studentTable.=&gradeBox_end();
 4482: 		$prob++;
 4483: 	    }
 4484: 	    $studentTable.='</td></tr>';
 4485: 
 4486: 	}
 4487:         $curRes = $iterator->next();
 4488:     }
 4489: 
 4490:     $studentTable.=
 4491:         '</table>'."\n".
 4492:         '<input type="button" value="'.&mt('Save').'" '.
 4493:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4494:         '</form>'."\n";
 4495:     $request->print($studentTable);
 4496: 
 4497:     return '';
 4498: }
 4499: 
 4500: sub displaySubByDates {
 4501:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4502:     my $isCODE=0;
 4503:     my $isTask = ($symb =~/\.task$/);
 4504:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4505:     my $studentTable=&Apache::loncommon::start_data_table().
 4506: 	&Apache::loncommon::start_data_table_header_row().
 4507: 	'<th>'.&mt('Date/Time').'</th>'.
 4508: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4509: 	'<th>'.&mt('Submission').'</th>'.
 4510: 	'<th>'.&mt('Status').'</th>'.
 4511: 	&Apache::loncommon::end_data_table_header_row();
 4512:     my ($version);
 4513:     my %mark;
 4514:     my %orders;
 4515:     $mark{'correct_by_student'} = $checkIcon;
 4516:     if (!exists($$record{'1:timestamp'})) {
 4517: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 4518:     }
 4519: 
 4520:     my $interaction;
 4521:     my $no_increment = 1;
 4522:     my %lastrndseed;
 4523:     for ($version=1;$version<=$$record{'version'};$version++) {
 4524: 	my $timestamp = 
 4525: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4526: 	if (exists($$record{$version.':resource.0.version'})) {
 4527: 	    $interaction = $$record{$version.':resource.0.version'};
 4528: 	}
 4529: 
 4530: 	my $where = ($isTask ? "$version:resource.$interaction"
 4531: 		             : "$version:resource");
 4532: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4533: 	    '<td>'.$timestamp.'</td>';
 4534: 	if ($isCODE) {
 4535: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4536: 	}
 4537: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4538: 	my @displaySub = ();
 4539: 	foreach my $partid (@{$parts}) {
 4540:             my ($hidden,$type);
 4541:             $type = $$record{$version.':resource.'.$partid.'.type'};
 4542:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
 4543:                 $hidden = 1;
 4544:             }
 4545: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4546: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4547: 	    
 4548: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4549: 	    my $display_part=&get_display_part($partid,$symb);
 4550: 	    foreach my $matchKey (@matchKey) {
 4551: 		if (exists($$record{$version.':'.$matchKey}) &&
 4552: 		    $$record{$version.':'.$matchKey} ne '') {
 4553:                     
 4554: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4555: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4556:                     $displaySub[0].='<span class="LC_nobreak"';
 4557:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 4558:                                    .' <span class="LC_internal_info">'
 4559:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
 4560:                                    .'</span>'
 4561:                                    .' <b>';
 4562:                     if ($hidden) {
 4563:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
 4564:                     } else {
 4565:                         my ($trial,$rndseed,$newvariation);
 4566:                         if ($type eq 'randomizetry') {
 4567:                             $trial = $$record{"$where.$partid.tries"};
 4568:                             $rndseed = $$record{"$where.$partid.rndseed"};
 4569:                         }
 4570: 		        if ($$record{"$where.$partid.tries"} eq '') {
 4571: 			    $displaySub[0].=&mt('Trial not counted');
 4572: 		        } else {
 4573: 			    $displaySub[0].=&mt('Trial: [_1]',
 4574: 					    $$record{"$where.$partid.tries"});
 4575:                             if ($rndseed || $lastrndseed{$partid}) {
 4576:                                 if ($rndseed ne $lastrndseed{$partid}) {
 4577:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
 4578:                                 }
 4579:                             }
 4580:                             $lastrndseed{$partid} = $rndseed;
 4581: 		        }
 4582: 		        my $responseType=($isTask ? 'Task'
 4583:                                               : $responseType->{$partid}->{$responseId});
 4584: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4585: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
 4586: 			    $orders{$partid}->{$responseId}=
 4587: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
 4588:                                            $no_increment,$type,$trial,$rndseed);
 4589: 		        }
 4590: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
 4591: 		        $displaySub[0].='&nbsp; '.
 4592: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
 4593:                     }
 4594: 		}
 4595: 	    }
 4596: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4597: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 4598: 				    $$record{"$where.$partid.checkedin"},
 4599: 				    $$record{"$where.$partid.checkedin.slot"}).
 4600: 					'<br />';
 4601: 	    }
 4602: 	    if (exists $$record{"$where.$partid.award"}) {
 4603: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 4604: 		    lc($$record{"$where.$partid.award"}).' '.
 4605: 		    $mark{$$record{"$where.$partid.solved"}}.
 4606: 		    '<br />';
 4607: 	    }
 4608: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4609: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4610: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4611: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4612: 		$displaySub[2].=
 4613: 		    $$record{"$version:resource.$partid.regrader"}.
 4614: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4615: 	    }
 4616: 	}
 4617: 	# needed because old essay regrader has not parts info
 4618: 	if (exists $$record{"$version:resource.regrader"}) {
 4619: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 4620: 	}
 4621: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 4622: 	if ($displaySub[2]) {
 4623: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 4624: 	}
 4625: 	$studentTable.='&nbsp;</td>'.
 4626: 	    &Apache::loncommon::end_data_table_row();
 4627:     }
 4628:     $studentTable.=&Apache::loncommon::end_data_table();
 4629:     return $studentTable;
 4630: }
 4631: 
 4632: sub updateGradeByPage {
 4633:     my ($request,$symb) = @_;
 4634: 
 4635:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4636:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4637:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4638:     my $pageTitle = $env{'form.page'};
 4639:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4640:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4641:     my $usec=$classlist->{$env{'form.student'}}[5];
 4642:     if (!&canmodify($usec)) {
 4643: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 4644: 	return;
 4645:     }
 4646:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4647:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 4648: 	'</h3>'."\n";
 4649: 
 4650:     $request->print($result);
 4651: 
 4652: 
 4653:     my $navmap = Apache::lonnavmaps::navmap->new();
 4654:     unless (ref($navmap)) {
 4655:         $request->print(&navmap_errormsg());
 4656:         return;
 4657:     }
 4658:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 4659:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4660:     if (!$map) {
 4661: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 4662: 	return; 
 4663:     }
 4664:     my $iterator = $navmap->getIterator($map->map_start(),
 4665: 					$map->map_finish());
 4666: 
 4667:     my $studentTable=
 4668: 	&Apache::loncommon::start_data_table().
 4669: 	&Apache::loncommon::start_data_table_header_row().
 4670: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 4671: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 4672: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 4673: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 4674: 	&Apache::loncommon::end_data_table_header_row();
 4675: 
 4676:     $iterator->next(); # skip the first BEGIN_MAP
 4677:     my $curRes = $iterator->next(); # for "current resource"
 4678:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 4679:     while ($depth > 0) {
 4680:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4681:         if($curRes == $iterator->END_MAP) { $depth--; }
 4682: 
 4683:         if (ref($curRes) && $curRes->is_problem()) {
 4684: 	    my $parts = $curRes->parts();
 4685:             my $title = $curRes->compTitle();
 4686: 	    my $symbx = $curRes->symb();
 4687: 	    $studentTable.=
 4688: 		&Apache::loncommon::start_data_table_row().
 4689: 		'<td align="center" valign="top" >'.$prob.
 4690: 		(scalar(@{$parts}) == 1 ? '' 
 4691:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
 4692: 		.')').'</td>';
 4693: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 4694: 
 4695: 	    my %newrecord=();
 4696: 	    my @displayPts=();
 4697:             my %aggregate = ();
 4698:             my $aggregateflag = 0;
 4699: 	    foreach my $partid (@{$parts}) {
 4700: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 4701: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 4702: 
 4703: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 4704: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 4705: 		my $partial = $newpts/$wgt;
 4706: 		my $score;
 4707: 		if ($partial > 0) {
 4708: 		    $score = 'correct_by_override';
 4709: 		} elsif ($newpts ne '') { #empty is taken as 0
 4710: 		    $score = 'incorrect_by_override';
 4711: 		}
 4712: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 4713: 		if ($dropMenu eq 'excused') {
 4714: 		    $partial = '';
 4715: 		    $score = 'excused';
 4716: 		} elsif ($dropMenu eq 'reset status'
 4717: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 4718: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 4719: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 4720: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 4721: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 4722: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 4723: 		    $changeflag++;
 4724: 		    $newpts = '';
 4725:                     
 4726:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 4727:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 4728:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 4729:                     if ($aggtries > 0) {
 4730:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4731:                         $aggregateflag = 1;
 4732:                     }
 4733: 		}
 4734: 		my $display_part=&get_display_part($partid,$curRes->symb());
 4735: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 4736: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4737: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 4738: 		    '&nbsp;<br />';
 4739: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4740: 		     (($score eq 'excused') ? 'excused' : $newpts).
 4741: 		    '&nbsp;<br />';
 4742: 		$question++;
 4743: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 4744: 
 4745: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 4746: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 4747: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 4748: 		    if (scalar(keys(%newrecord)) > 0);
 4749: 
 4750: 		$changeflag++;
 4751: 	    }
 4752: 	    if (scalar(keys(%newrecord)) > 0) {
 4753: 		my %record = 
 4754: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 4755: 					     $udom,$uname);
 4756: 
 4757: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 4758: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 4759: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 4760: 		    $newrecord{'resource.CODE'} = '';
 4761: 		}
 4762: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 4763: 					$udom,$uname);
 4764: 		%record = &Apache::lonnet::restore($symbx,
 4765: 						   $env{'request.course.id'},
 4766: 						   $udom,$uname);
 4767: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 4768: 					     $cdom,$cnum,$udom,$uname);
 4769: 	    }
 4770: 	    
 4771:             if ($aggregateflag) {
 4772:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4773:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 4774:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 4775:             }
 4776: 
 4777: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 4778: 		'<td valign="top">'.$displayPts[1].'</td>'.
 4779: 		&Apache::loncommon::end_data_table_row();
 4780: 
 4781: 	    $prob++;
 4782: 	}
 4783:         $curRes = $iterator->next();
 4784:     }
 4785: 
 4786:     $studentTable.=&Apache::loncommon::end_data_table();
 4787:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 4788: 		  &mt('The scores were changed for [quant,_1,problem].',
 4789: 		  $changeflag));
 4790:     $request->print($grademsg.$studentTable);
 4791: 
 4792:     return '';
 4793: }
 4794: 
 4795: #-------- end of section for handling grading by page/sequence ---------
 4796: #
 4797: #-------------------------------------------------------------------
 4798: 
 4799: #-------------------- Bubblesheet (Scantron) Grading -------------------
 4800: #
 4801: #------ start of section for handling grading by page/sequence ---------
 4802: 
 4803: =pod
 4804: 
 4805: =head1 Bubble sheet grading routines
 4806: 
 4807:   For this documentation:
 4808: 
 4809:    'scanline' refers to the full line of characters
 4810:    from the file that we are parsing that represents one entire sheet
 4811: 
 4812:    'bubble line' refers to the data
 4813:    representing the line of bubbles that are on the physical bubble sheet
 4814: 
 4815: 
 4816: The overall process is that a scanned in bubble sheet data is uploaded
 4817: into a course. When a user wants to grade, they select a
 4818: sequence/folder of resources, a file of bubble sheet info, and pick
 4819: one of the predefined configurations for what each scanline looks
 4820: like.
 4821: 
 4822: Next each scanline is checked for any errors of either 'missing
 4823: bubbles' (it's an error because it may have been mis-scanned
 4824: because too light bubbling), 'double bubble' (each bubble line should
 4825: have no more that one letter picked), invalid or duplicated CODE,
 4826: invalid student/employee ID
 4827: 
 4828: If the CODE option is used that determines the randomization of the
 4829: homework problems, either way the student/employee ID is looked up into a
 4830: username:domain.
 4831: 
 4832: During the validation phase the instructor can choose to skip scanlines. 
 4833: 
 4834: After the validation phase, there are now 3 bubble sheet files
 4835: 
 4836:   scantron_original_filename (unmodified original file)
 4837:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 4838:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 4839: 
 4840: Also there is a separate hash nohist_scantrondata that contains extra
 4841: correction information that isn't representable in the bubble sheet
 4842: file (see &scantron_getfile() for more information)
 4843: 
 4844: After all scanlines are either valid, marked as valid or skipped, then
 4845: foreach line foreach problem in the picked sequence, an ssi request is
 4846: made that simulates a user submitting their selected letter(s) against
 4847: the homework problem.
 4848: 
 4849: =over 4
 4850: 
 4851: 
 4852: 
 4853: =item defaultFormData
 4854: 
 4855:   Returns html hidden inputs used to hold context/default values.
 4856: 
 4857:  Arguments:
 4858:   $symb - $symb of the current resource 
 4859: 
 4860: =cut
 4861: 
 4862: sub defaultFormData {
 4863:     my ($symb)=@_;
 4864:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
 4865: }
 4866: 
 4867: 
 4868: =pod 
 4869: 
 4870: =item getSequenceDropDown
 4871: 
 4872:    Return html dropdown of possible sequences to grade
 4873:  
 4874:  Arguments:
 4875:    $symb - $symb of the current resource
 4876:    $map_error - ref to scalar which will container error if
 4877:                 $navmap object is unavailable in &getSymbMap().
 4878: 
 4879: =cut
 4880: 
 4881: sub getSequenceDropDown {
 4882:     my ($symb,$map_error)=@_;
 4883:     my $result='<select name="selectpage">'."\n";
 4884:     my ($titles,$symbx) = &getSymbMap($map_error);
 4885:     if (ref($map_error)) {
 4886:         return if ($$map_error);
 4887:     }
 4888:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 4889:     my $ctr=0;
 4890:     foreach (@$titles) {
 4891: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4892: 	$result.='<option value="'.$$symbx{$_}.'" '.
 4893: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4894: 	    '>'.$showtitle.'</option>'."\n";
 4895: 	$ctr++;
 4896:     }
 4897:     $result.= '</select>';
 4898:     return $result;
 4899: }
 4900: 
 4901: my %bubble_lines_per_response;     # no. bubble lines for each response.
 4902:                                    # key is zero-based index - 0, 1, 2 ...
 4903: 
 4904: my %first_bubble_line;             # First bubble line no. for each bubble.
 4905: 
 4906: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 4907:                                    # matchresponse or rankresponse, where 
 4908:                                    # an individual response can have multiple 
 4909:                                    # lines
 4910: 
 4911: my %responsetype_per_response;     # responsetype for each response
 4912: 
 4913: # Save and restore the bubble lines array to the form env.
 4914: 
 4915: 
 4916: sub save_bubble_lines {
 4917:     foreach my $line (keys(%bubble_lines_per_response)) {
 4918: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 4919: 	$env{"form.scantron.first_bubble_line.$line"} =
 4920: 	    $first_bubble_line{$line};
 4921:         $env{"form.scantron.sub_bubblelines.$line"} = 
 4922:             $subdivided_bubble_lines{$line};
 4923:         $env{"form.scantron.responsetype.$line"} =
 4924:             $responsetype_per_response{$line};
 4925:     }
 4926: }
 4927: 
 4928: 
 4929: sub restore_bubble_lines {
 4930:     my $line = 0;
 4931:     %bubble_lines_per_response = ();
 4932:     while ($env{"form.scantron.bubblelines.$line"}) {
 4933: 	my $value = $env{"form.scantron.bubblelines.$line"};
 4934: 	$bubble_lines_per_response{$line} = $value;
 4935: 	$first_bubble_line{$line}  =
 4936: 	    $env{"form.scantron.first_bubble_line.$line"};
 4937:         $subdivided_bubble_lines{$line} =
 4938:             $env{"form.scantron.sub_bubblelines.$line"};
 4939:         $responsetype_per_response{$line} =
 4940:             $env{"form.scantron.responsetype.$line"};
 4941: 	$line++;
 4942:     }
 4943: }
 4944: 
 4945: #  Given the parsed scanline, get the response for 
 4946: #  'answer' number n:
 4947: 
 4948: sub get_response_bubbles {
 4949:     my ($parsed_line, $response)  = @_;
 4950: 
 4951:     my $bubble_line = $first_bubble_line{$response-1} +1;
 4952:     my $bubble_lines= $bubble_lines_per_response{$response-1};
 4953:     
 4954:     my $selected = "";
 4955: 
 4956:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
 4957: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
 4958: 	$bubble_line++;
 4959:     }
 4960:     return $selected;
 4961: }
 4962: 
 4963: =pod 
 4964: 
 4965: =item scantron_filenames
 4966: 
 4967:    Returns a list of the scantron files in the current course 
 4968: 
 4969: =cut
 4970: 
 4971: sub scantron_filenames {
 4972:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4973:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4974:     my $getpropath = 1;
 4975:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
 4976:                                        $getpropath);
 4977:     my @possiblenames;
 4978:     foreach my $filename (sort(@files)) {
 4979: 	($filename)=split(/&/,$filename);
 4980: 	if ($filename!~/^scantron_orig_/) { next ; }
 4981: 	$filename=~s/^scantron_orig_//;
 4982: 	push(@possiblenames,$filename);
 4983:     }
 4984:     return @possiblenames;
 4985: }
 4986: 
 4987: =pod 
 4988: 
 4989: =item scantron_uploads
 4990: 
 4991:    Returns  html drop-down list of scantron files in current course.
 4992: 
 4993:  Arguments:
 4994:    $file2grade - filename to set as selected in the dropdown
 4995: 
 4996: =cut
 4997: 
 4998: sub scantron_uploads {
 4999:     my ($file2grade) = @_;
 5000:     my $result=	'<select name="scantron_selectfile">';
 5001:     $result.="<option></option>";
 5002:     foreach my $filename (sort(&scantron_filenames())) {
 5003: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 5004:     }
 5005:     $result.="</select>";
 5006:     return $result;
 5007: }
 5008: 
 5009: =pod 
 5010: 
 5011: =item scantron_scantab
 5012: 
 5013:   Returns html drop down of the scantron formats in the scantronformat.tab
 5014:   file.
 5015: 
 5016: =cut
 5017: 
 5018: sub scantron_scantab {
 5019:     my $result='<select name="scantron_format">'."\n";
 5020:     $result.='<option></option>'."\n";
 5021:     my @lines = &get_scantronformat_file();
 5022:     if (@lines > 0) {
 5023:         foreach my $line (@lines) {
 5024:             next if (($line =~ /^\#/) || ($line eq ''));
 5025: 	    my ($name,$descrip)=split(/:/,$line);
 5026: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 5027:         }
 5028:     }
 5029:     $result.='</select>'."\n";
 5030:     return $result;
 5031: }
 5032: 
 5033: =pod
 5034: 
 5035: =item get_scantronformat_file
 5036: 
 5037:   Returns an array containing lines from the scantron format file for
 5038:   the domain of the course.
 5039: 
 5040:   If a url for a custom.tab file is listed in domain's configuration.db, 
 5041:   lines are from this file.
 5042: 
 5043:   Otherwise, if a default.tab has been published in RES space by the 
 5044:   domainconfig user, lines are from this file.
 5045: 
 5046:   Otherwise, fall back to getting lines from the legacy file on the
 5047:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 5048: 
 5049: =cut
 5050: 
 5051: sub get_scantronformat_file {
 5052:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5053:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 5054:     my $gottab = 0;
 5055:     my @lines;
 5056:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5057:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5058:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5059:             if ($formatfile ne '-1') {
 5060:                 @lines = split("\n",$formatfile,-1);
 5061:                 $gottab = 1;
 5062:             }
 5063:         }
 5064:     }
 5065:     if (!$gottab) {
 5066:         my $confname = $cdom.'-domainconfig';
 5067:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5068:         my $formatfile =  &Apache::lonnet::getfile($default);
 5069:         if ($formatfile ne '-1') {
 5070:             @lines = split("\n",$formatfile,-1);
 5071:             $gottab = 1;
 5072:         }
 5073:     }
 5074:     if (!$gottab) {
 5075:         my @domains = &Apache::lonnet::current_machine_domains();
 5076:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5077:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5078:             @lines = <$fh>;
 5079:             close($fh);
 5080:         } else {
 5081:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 5082:             @lines = <$fh>;
 5083:             close($fh);
 5084:         }
 5085:     }
 5086:     return @lines;
 5087: }
 5088: 
 5089: =pod 
 5090: 
 5091: =item scantron_CODElist
 5092: 
 5093:   Returns html drop down of the saved CODE lists from current course,
 5094:   generated from earlier printings.
 5095: 
 5096: =cut
 5097: 
 5098: sub scantron_CODElist {
 5099:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5100:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5101:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5102:     my $namechoice='<option></option>';
 5103:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5104: 	if ($name =~ /^error: 2 /) { next; }
 5105: 	if ($name =~ /^type\0/) { next; }
 5106: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5107:     }
 5108:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5109:     return $namechoice;
 5110: }
 5111: 
 5112: =pod 
 5113: 
 5114: =item scantron_CODEunique
 5115: 
 5116:   Returns the html for "Each CODE to be used once" radio.
 5117: 
 5118: =cut
 5119: 
 5120: sub scantron_CODEunique {
 5121:     my $result='<span class="LC_nobreak">
 5122:                  <label><input type="radio" name="scantron_CODEunique"
 5123:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5124:                 </span>
 5125:                 <span class="LC_nobreak">
 5126:                  <label><input type="radio" name="scantron_CODEunique"
 5127:                         value="no" />'.&mt('No').' </label>
 5128:                 </span>';
 5129:     return $result;
 5130: }
 5131: 
 5132: =pod 
 5133: 
 5134: =item scantron_selectphase
 5135: 
 5136:   Generates the initial screen to start the bubble sheet process.
 5137:   Allows for - starting a grading run.
 5138:              - downloading existing scan data (original, corrected
 5139:                                                 or skipped info)
 5140: 
 5141:              - uploading new scan data
 5142: 
 5143:  Arguments:
 5144:   $r          - The Apache request object
 5145:   $file2grade - name of the file that contain the scanned data to score
 5146: 
 5147: =cut
 5148: 
 5149: sub scantron_selectphase {
 5150:     my ($r,$file2grade,$symb) = @_;
 5151:     if (!$symb) {return '';}
 5152:     my $map_error;
 5153:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 5154:     if ($map_error) {
 5155:         $r->print('<br />'.&navmap_errormsg().'<br />');
 5156:         return;
 5157:     }
 5158:     my $default_form_data=&defaultFormData($symb);
 5159:     my $file_selector=&scantron_uploads($file2grade);
 5160:     my $format_selector=&scantron_scantab();
 5161:     my $CODE_selector=&scantron_CODElist();
 5162:     my $CODE_unique=&scantron_CODEunique();
 5163:     my $result;
 5164: 
 5165:     $ssi_error = 0;
 5166: 
 5167:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5168:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5169: 
 5170: 	# Chunk of form to prompt for a scantron file upload.
 5171: 
 5172:         $r->print('
 5173:     <br />
 5174:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5175:        '.&Apache::loncommon::start_data_table_header_row().'
 5176:             <th>
 5177:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 5178:             </th>
 5179:        '.&Apache::loncommon::end_data_table_header_row().'
 5180:        '.&Apache::loncommon::start_data_table_row().'
 5181:             <td>
 5182: ');
 5183:     my $default_form_data=&defaultFormData($symb);
 5184:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5185:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5186:     $r->print(&Apache::lonhtmlcommon::scripttag('
 5187:     function checkUpload(formname) {
 5188: 	if (formname.upfile.value == "") {
 5189: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 5190: 	    return false;
 5191: 	}
 5192: 	formname.submit();
 5193:     }'));
 5194:     $r->print('
 5195:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5196:                 '.$default_form_data.'
 5197:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5198:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5199:                 <input name="command" value="scantronupload_save" type="hidden" />
 5200:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5201:                 <br />
 5202:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 5203:               </form>
 5204: ');
 5205: 
 5206:         $r->print('
 5207:             </td>
 5208:        '.&Apache::loncommon::end_data_table_row().'
 5209:        '.&Apache::loncommon::end_data_table().'
 5210: ');
 5211:     }
 5212: 
 5213:     # Chunk of form to prompt for a file to grade and how:
 5214: 
 5215:     $result.= '
 5216:     <br />
 5217:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5218:     <input type="hidden" name="command" value="scantron_warning" />
 5219:     '.$default_form_data.'
 5220:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5221:        '.&Apache::loncommon::start_data_table_header_row().'
 5222:             <th colspan="2">
 5223:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5224:             </th>
 5225:        '.&Apache::loncommon::end_data_table_header_row().'
 5226:        '.&Apache::loncommon::start_data_table_row().'
 5227:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5228:        '.&Apache::loncommon::end_data_table_row().'
 5229:        '.&Apache::loncommon::start_data_table_row().'
 5230:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 5231:        '.&Apache::loncommon::end_data_table_row().'
 5232:        '.&Apache::loncommon::start_data_table_row().'
 5233:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 5234:        '.&Apache::loncommon::end_data_table_row().'
 5235:        '.&Apache::loncommon::start_data_table_row().'
 5236:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5237:        '.&Apache::loncommon::end_data_table_row().'
 5238:        '.&Apache::loncommon::start_data_table_row().'
 5239:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5240:        '.&Apache::loncommon::end_data_table_row().'
 5241:        '.&Apache::loncommon::start_data_table_row().'
 5242: 	    <td> '.&mt('Options:').' </td>
 5243:             <td>
 5244: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5245:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5246:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5247: 	    </td>
 5248:        '.&Apache::loncommon::end_data_table_row().'
 5249:        '.&Apache::loncommon::start_data_table_row().'
 5250:             <td colspan="2">
 5251:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 5252:             </td>
 5253:        '.&Apache::loncommon::end_data_table_row().'
 5254:     '.&Apache::loncommon::end_data_table().'
 5255:     </form>
 5256: ';
 5257:    
 5258:     $r->print($result);
 5259: 
 5260: 
 5261: 
 5262:     # Chunk of the form that prompts to view a scoring office file,
 5263:     # corrected file, skipped records in a file.
 5264: 
 5265:     $r->print('
 5266:    <br />
 5267:    <form action="/adm/grades" name="scantron_download">
 5268:      '.$default_form_data.'
 5269:      <input type="hidden" name="command" value="scantron_download" />
 5270:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5271:        '.&Apache::loncommon::start_data_table_header_row().'
 5272:               <th>
 5273:                 &nbsp;'.&mt('Download a scoring office file').'
 5274:               </th>
 5275:        '.&Apache::loncommon::end_data_table_header_row().'
 5276:        '.&Apache::loncommon::start_data_table_row().'
 5277:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5278:                 <br />
 5279:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5280:        '.&Apache::loncommon::end_data_table_row().'
 5281:      '.&Apache::loncommon::end_data_table().'
 5282:    </form>
 5283:    <br />
 5284: ');
 5285: 
 5286:     &Apache::lonpickcode::code_list($r,2);
 5287: 
 5288:     $r->print('<br /><form method="post" name="checkscantron">'.
 5289:              $default_form_data."\n".
 5290:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5291:              &Apache::loncommon::start_data_table_header_row()."\n".
 5292:              '<th colspan="2">
 5293:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 5294:              '</th>'."\n".
 5295:               &Apache::loncommon::end_data_table_header_row()."\n".
 5296:               &Apache::loncommon::start_data_table_row()."\n".
 5297:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5298:               '<td> '.$sequence_selector.' </td>'.
 5299:               &Apache::loncommon::end_data_table_row()."\n".
 5300:               &Apache::loncommon::start_data_table_row()."\n".
 5301:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5302:               '<td> '.$file_selector.' </td>'."\n".
 5303:               &Apache::loncommon::end_data_table_row()."\n".
 5304:               &Apache::loncommon::start_data_table_row()."\n".
 5305:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5306:               '<td> '.$format_selector.' </td>'."\n".
 5307:               &Apache::loncommon::end_data_table_row()."\n".
 5308:               &Apache::loncommon::start_data_table_row()."\n".
 5309:               '<td> '.&mt('Options').' </td>'."\n".
 5310:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 5311:               &Apache::loncommon::end_data_table_row()."\n".
 5312:               &Apache::loncommon::start_data_table_row()."\n".
 5313:               '<td colspan="2">'."\n".
 5314:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5315:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 5316:               '</td>'."\n".
 5317:               &Apache::loncommon::end_data_table_row()."\n".
 5318:               &Apache::loncommon::end_data_table()."\n".
 5319:               '</form><br />');
 5320:     return;
 5321: }
 5322: 
 5323: =pod
 5324: 
 5325: =item get_scantron_config
 5326: 
 5327:    Parse and return the scantron configuration line selected as a
 5328:    hash of configuration file fields.
 5329: 
 5330:  Arguments:
 5331:     which - the name of the configuration to parse from the file.
 5332: 
 5333: 
 5334:  Returns:
 5335:             If the named configuration is not in the file, an empty
 5336:             hash is returned.
 5337:     a hash with the fields
 5338:       name         - internal name for the this configuration setup
 5339:       description  - text to display to operator that describes this config
 5340:       CODElocation - if 0 or the string 'none'
 5341:                           - no CODE exists for this config
 5342:                      if -1 || the string 'letter'
 5343:                           - a CODE exists for this config and is
 5344:                             a string of letters
 5345:                      Unsupported value (but planned for future support)
 5346:                           if a positive integer
 5347:                                - The CODE exists as the first n items from
 5348:                                  the question section of the form
 5349:                           if the string 'number'
 5350:                                - The CODE exists for this config and is
 5351:                                  a string of numbers
 5352:       CODEstart   - (only matter if a CODE exists) column in the line where
 5353:                      the CODE starts
 5354:       CODElength  - length of the CODE
 5355:       IDstart     - column where the student/employee ID starts
 5356:       IDlength    - length of the student/employee ID info
 5357:       Qstart      - column where the information from the bubbled
 5358:                     'questions' start
 5359:       Qlength     - number of columns comprising a single bubble line from
 5360:                     the sheet. (usually either 1 or 10)
 5361:       Qon         - either a single character representing the character used
 5362:                     to signal a bubble was chosen in the positional setup, or
 5363:                     the string 'letter' if the letter of the chosen bubble is
 5364:                     in the final, or 'number' if a number representing the
 5365:                     chosen bubble is in the file (1->A 0->J)
 5366:       Qoff        - the character used to represent that a bubble was
 5367:                     left blank
 5368:       PaperID     - if the scanning process generates a unique number for each
 5369:                     sheet scanned the column that this ID number starts in
 5370:       PaperIDlength - number of columns that comprise the unique ID number
 5371:                       for the sheet of paper
 5372:       FirstName   - column that the first name starts in
 5373:       FirstNameLength - number of columns that the first name spans
 5374:  
 5375:       LastName    - column that the last name starts in
 5376:       LastNameLength - number of columns that the last name spans
 5377:       BubblesPerRow - number of bubbles available in each row used to 
 5378:                       bubble an answer. (If not specified, 10 assumed).
 5379: =cut
 5380: 
 5381: sub get_scantron_config {
 5382:     my ($which) = @_;
 5383:     my @lines = &get_scantronformat_file();
 5384:     my %config;
 5385:     #FIXME probably should move to XML it has already gotten a bit much now
 5386:     foreach my $line (@lines) {
 5387: 	my ($name,$descrip)=split(/:/,$line);
 5388: 	if ($name ne $which ) { next; }
 5389: 	chomp($line);
 5390: 	my @config=split(/:/,$line);
 5391: 	$config{'name'}=$config[0];
 5392: 	$config{'description'}=$config[1];
 5393: 	$config{'CODElocation'}=$config[2];
 5394: 	$config{'CODEstart'}=$config[3];
 5395: 	$config{'CODElength'}=$config[4];
 5396: 	$config{'IDstart'}=$config[5];
 5397: 	$config{'IDlength'}=$config[6];
 5398: 	$config{'Qstart'}=$config[7];
 5399:  	$config{'Qlength'}=$config[8];
 5400: 	$config{'Qoff'}=$config[9];
 5401: 	$config{'Qon'}=$config[10];
 5402: 	$config{'PaperID'}=$config[11];
 5403: 	$config{'PaperIDlength'}=$config[12];
 5404: 	$config{'FirstName'}=$config[13];
 5405: 	$config{'FirstNamelength'}=$config[14];
 5406: 	$config{'LastName'}=$config[15];
 5407: 	$config{'LastNamelength'}=$config[16];
 5408:         $config{'BubblesPerRow'}=$config[17];
 5409: 	last;
 5410:     }
 5411:     return %config;
 5412: }
 5413: 
 5414: =pod 
 5415: 
 5416: =item username_to_idmap
 5417: 
 5418:     creates a hash keyed by student/employee ID with values of the corresponding
 5419:     student username:domain.
 5420: 
 5421:   Arguments:
 5422: 
 5423:     $classlist - reference to the class list hash. This is a hash
 5424:                  keyed by student name:domain  whose elements are references
 5425:                  to arrays containing various chunks of information
 5426:                  about the student. (See loncoursedata for more info).
 5427: 
 5428:   Returns
 5429:     %idmap - the constructed hash
 5430: 
 5431: =cut
 5432: 
 5433: sub username_to_idmap {
 5434:     my ($classlist)= @_;
 5435:     my %idmap;
 5436:     foreach my $student (keys(%$classlist)) {
 5437: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5438: 	    $student;
 5439:     }
 5440:     return %idmap;
 5441: }
 5442: 
 5443: =pod
 5444: 
 5445: =item scantron_fixup_scanline
 5446: 
 5447:    Process a requested correction to a scanline.
 5448: 
 5449:   Arguments:
 5450:     $scantron_config   - hash from &get_scantron_config()
 5451:     $scan_data         - hash of correction information 
 5452:                           (see &scantron_getfile())
 5453:     $line              - existing scanline
 5454:     $whichline         - line number of the passed in scanline
 5455:     $field             - type of change to process 
 5456:                          (either 
 5457:                           'ID'     -> correct the student/employee ID
 5458:                           'CODE'   -> correct the CODE
 5459:                           'answer' -> fixup the submitted answers)
 5460:     
 5461:    $args               - hash of additional info,
 5462:                           - 'ID' 
 5463:                                'newid' -> studentID to use in replacement
 5464:                                           of existing one
 5465:                           - 'CODE' 
 5466:                                'CODE_ignore_dup' - set to true if duplicates
 5467:                                                    should be ignored.
 5468: 	                       'CODE' - is new code or 'use_unfound'
 5469:                                         if the existing unfound code should
 5470:                                         be used as is
 5471:                           - 'answer'
 5472:                                'response' - new answer or 'none' if blank
 5473:                                'question' - the bubble line to change
 5474:                                'questionnum' - the question identifier,
 5475:                                                may include subquestion. 
 5476: 
 5477:   Returns:
 5478:     $line - the modified scanline
 5479: 
 5480:   Side effects: 
 5481:     $scan_data - may be updated
 5482: 
 5483: =cut
 5484: 
 5485: 
 5486: sub scantron_fixup_scanline {
 5487:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5488:     if ($field eq 'ID') {
 5489: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5490: 	    return ($line,1,'New value too large');
 5491: 	}
 5492: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5493: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5494: 				     $args->{'newid'});
 5495: 	}
 5496: 	substr($line,$$scantron_config{'IDstart'}-1,
 5497: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5498: 	if ($args->{'newid'}=~/^\s*$/) {
 5499: 	    &scan_data($scan_data,"$whichline.user",
 5500: 		       $args->{'username'}.':'.$args->{'domain'});
 5501: 	}
 5502:     } elsif ($field eq 'CODE') {
 5503: 	if ($args->{'CODE_ignore_dup'}) {
 5504: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5505: 	}
 5506: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5507: 	if ($args->{'CODE'} ne 'use_unfound') {
 5508: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5509: 		return ($line,1,'New CODE value too large');
 5510: 	    }
 5511: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5512: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5513: 	    }
 5514: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5515: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5516: 	}
 5517:     } elsif ($field eq 'answer') {
 5518: 	my $length=$scantron_config->{'Qlength'};
 5519: 	my $off=$scantron_config->{'Qoff'};
 5520: 	my $on=$scantron_config->{'Qon'};
 5521: 	my $answer=${off}x$length;
 5522: 	if ($args->{'response'} eq 'none') {
 5523: 	    &scan_data($scan_data,
 5524: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5525: 	} else {
 5526: 	    if ($on eq 'letter') {
 5527: 		my @alphabet=('A'..'Z');
 5528: 		$answer=$alphabet[$args->{'response'}];
 5529: 	    } elsif ($on eq 'number') {
 5530: 		$answer=$args->{'response'}+1;
 5531: 		if ($answer == 10) { $answer = '0'; }
 5532: 	    } else {
 5533: 		substr($answer,$args->{'response'},1)=$on;
 5534: 	    }
 5535: 	    &scan_data($scan_data,
 5536: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5537: 	}
 5538: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5539: 	substr($line,$where-1,$length)=$answer;
 5540:     }
 5541:     return $line;
 5542: }
 5543: 
 5544: =pod
 5545: 
 5546: =item scan_data
 5547: 
 5548:     Edit or look up  an item in the scan_data hash.
 5549: 
 5550:   Arguments:
 5551:     $scan_data  - The hash (see scantron_getfile)
 5552:     $key        - shorthand of the key to edit (actual key is
 5553:                   scantronfilename_key).
 5554:     $data        - New value of the hash entry.
 5555:     $delete      - If true, the entry is removed from the hash.
 5556: 
 5557:   Returns:
 5558:     The new value of the hash table field (undefined if deleted).
 5559: 
 5560: =cut
 5561: 
 5562: 
 5563: sub scan_data {
 5564:     my ($scan_data,$key,$value,$delete)=@_;
 5565:     my $filename=$env{'form.scantron_selectfile'};
 5566:     if (defined($value)) {
 5567: 	$scan_data->{$filename.'_'.$key} = $value;
 5568:     }
 5569:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5570:     return $scan_data->{$filename.'_'.$key};
 5571: }
 5572: 
 5573: # ----- These first few routines are general use routines.----
 5574: 
 5575: # Return the number of occurences of a pattern in a string.
 5576: 
 5577: sub occurence_count {
 5578:     my ($string, $pattern) = @_;
 5579: 
 5580:     my @matches = ($string =~ /$pattern/g);
 5581: 
 5582:     return scalar(@matches);
 5583: }
 5584: 
 5585: 
 5586: # Take a string known to have digits and convert all the
 5587: # digits into letters in the range J,A..I.
 5588: 
 5589: sub digits_to_letters {
 5590:     my ($input) = @_;
 5591: 
 5592:     my @alphabet = ('J', 'A'..'I');
 5593: 
 5594:     my @input    = split(//, $input);
 5595:     my $output ='';
 5596:     for (my $i = 0; $i < scalar(@input); $i++) {
 5597: 	if ($input[$i] =~ /\d/) {
 5598: 	    $output .= $alphabet[$input[$i]];
 5599: 	} else {
 5600: 	    $output .= $input[$i];
 5601: 	}
 5602:     }
 5603:     return $output;
 5604: }
 5605: 
 5606: =pod 
 5607: 
 5608: =item scantron_parse_scanline
 5609: 
 5610:   Decodes a scanline from the selected scantron file
 5611: 
 5612:  Arguments:
 5613:     line             - The text of the scantron file line to process
 5614:     whichline        - Line number
 5615:     scantron_config  - Hash describing the format of the scantron lines.
 5616:     scan_data        - Hash of extra information about the scanline
 5617:                        (see scantron_getfile for more information)
 5618:     just_header      - True if should not process question answers but only
 5619:                        the stuff to the left of the answers.
 5620:  Returns:
 5621:    Hash containing the result of parsing the scanline
 5622: 
 5623:    Keys are all proceeded by the string 'scantron.'
 5624: 
 5625:        CODE    - the CODE in use for this scanline
 5626:        useCODE - 1 if the CODE is invalid but it usage has been forced
 5627:                  by the operator
 5628:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 5629:                             CODEs were selected, but the usage has been
 5630:                             forced by the operator
 5631:        ID  - student/employee ID
 5632:        PaperID - if used, the ID number printed on the sheet when the 
 5633:                  paper was scanned
 5634:        FirstName - first name from the sheet
 5635:        LastName  - last name from the sheet
 5636: 
 5637:      if just_header was not true these key may also exist
 5638: 
 5639:        missingerror - a list of bubble ranges that are considered to be answers
 5640:                       to a single question that don't have any bubbles filled in.
 5641:                       Of the form questionnumber:firstbubblenumber:count.
 5642:        doubleerror  - a list of bubble ranges that are considered to be answers
 5643:                       to a single question that have more than one bubble filled in.
 5644:                       Of the form questionnumber::firstbubblenumber:count
 5645:    
 5646:                 In the above, count is the number of bubble responses in the
 5647:                 input line needed to represent the possible answers to the question.
 5648:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 5649:                 per line would have count = 2.
 5650: 
 5651:        maxquest     - the number of the last bubble line that was parsed
 5652: 
 5653:        (<number> starts at 1)
 5654:        <number>.answer - zero or more letters representing the selected
 5655:                          letters from the scanline for the bubble line 
 5656:                          <number>.
 5657:                          if blank there was either no bubble or there where
 5658:                          multiple bubbles, (consult the keys missingerror and
 5659:                          doubleerror if this is an error condition)
 5660: 
 5661: =cut
 5662: 
 5663: sub scantron_parse_scanline {
 5664:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
 5665: 
 5666:     my %record;
 5667:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 5668:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 5669:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
 5670:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 5671: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 5672: 	if ($$scantron_config{'CODElocation'} < 0 ||
 5673: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 5674: 	    $$scantron_config{'CODElocation'} eq 'number') {
 5675: 	    $record{'scantron.CODE'}=substr($data,
 5676: 					    $$scantron_config{'CODEstart'}-1,
 5677: 					    $$scantron_config{'CODElength'});
 5678: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 5679: 		$record{'scantron.useCODE'}=1;
 5680: 	    }
 5681: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 5682: 		$record{'scantron.CODE_ignore_dup'}=1;
 5683: 	    }
 5684: 	} else {
 5685: 	    #FIXME interpret first N questions
 5686: 	}
 5687:     }
 5688:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 5689: 				  $$scantron_config{'IDlength'});
 5690:     $record{'scantron.PaperID'}=
 5691: 	substr($data,$$scantron_config{'PaperID'}-1,
 5692: 	       $$scantron_config{'PaperIDlength'});
 5693:     $record{'scantron.FirstName'}=
 5694: 	substr($data,$$scantron_config{'FirstName'}-1,
 5695: 	       $$scantron_config{'FirstNamelength'});
 5696:     $record{'scantron.LastName'}=
 5697: 	substr($data,$$scantron_config{'LastName'}-1,
 5698: 	       $$scantron_config{'LastNamelength'});
 5699:     if ($just_header) { return \%record; }
 5700: 
 5701:     my @alphabet=('A'..'Z');
 5702:     my $questnum=0;
 5703:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 5704: 
 5705:     chomp($questions);		# Get rid of any trailing \n.
 5706:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 5707:     while (length($questions)) {
 5708: 	my $answers_needed = $bubble_lines_per_response{$questnum};
 5709:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 5710:                              || 1;
 5711:         $questnum++;
 5712:         my $quest_id = $questnum;
 5713:         my $currentquest = substr($questions,0,$answer_length);
 5714:         $questions       = substr($questions,$answer_length);
 5715:         if (length($currentquest) < $answer_length) { next; }
 5716: 
 5717:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
 5718:             my $subquestnum = 1;
 5719:             my $subquestions = $currentquest;
 5720:             my @subanswers_needed = 
 5721:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
 5722:             foreach my $subans (@subanswers_needed) {
 5723:                 my $subans_length =
 5724:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 5725:                 my $currsubquest = substr($subquestions,0,$subans_length);
 5726:                 $subquestions   = substr($subquestions,$subans_length);
 5727:                 $quest_id = "$questnum.$subquestnum";
 5728:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 5729:                     ($$scantron_config{'Qon'} eq 'number')) {
 5730:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 5731:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 5732:                         \@alphabet,\%record,$scantron_config,$scan_data);
 5733:                 } else {
 5734:                     $ansnum = &scantron_validator_positional($ansnum,
 5735:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
 5736:                 }
 5737:                 $subquestnum ++;
 5738:             }
 5739:         } else {
 5740:             if (($$scantron_config{'Qon'} eq 'letter') ||
 5741:                 ($$scantron_config{'Qon'} eq 'number')) {
 5742:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 5743:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5744:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5745:             } else {
 5746:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 5747:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5748:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5749:             }
 5750:         }
 5751:     }
 5752:     $record{'scantron.maxquest'}=$questnum;
 5753:     return \%record;
 5754: }
 5755: 
 5756: sub scantron_validator_lettnum {
 5757:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 5758:         $alphabet,$record,$scantron_config,$scan_data) = @_;
 5759: 
 5760:     # Qon 'letter' implies for each slot in currquest we have:
 5761:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 5762:     #    about anything else (esp. a value of Qoff) for missing
 5763:     #    bubbles.
 5764:     #
 5765:     # Qon 'number' implies each slot gives a digit that indexes the
 5766:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 5767:     #    and * or ? for double bubbles on a single line.
 5768:     #
 5769: 
 5770:     my $matchon;
 5771:     if ($$scantron_config{'Qon'} eq 'letter') {
 5772:         $matchon = '[A-Z]';
 5773:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 5774:         $matchon = '\d';
 5775:     }
 5776:     my $occurrences = 0;
 5777:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5778:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5779:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5780:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5781:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5782:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5783:         my @singlelines = split('',$currquest);
 5784:         foreach my $entry (@singlelines) {
 5785:             $occurrences = &occurence_count($entry,$matchon);
 5786:             if ($occurrences > 1) {
 5787:                 last;
 5788:             }
 5789:         } 
 5790:     } else {
 5791:         $occurrences = &occurence_count($currquest,$matchon); 
 5792:     }
 5793:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 5794:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5795:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5796:             my $bubble = substr($currquest,$ans,1);
 5797:             if ($bubble =~ /$matchon/ ) {
 5798:                 if ($$scantron_config{'Qon'} eq 'number') {
 5799:                     if ($bubble == 0) {
 5800:                         $bubble = 10; 
 5801:                     }
 5802:                     $record->{"scantron.$ansnum.answer"} = 
 5803:                         $alphabet->[$bubble-1];
 5804:                 } else {
 5805:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 5806:                 }
 5807:             } else {
 5808:                 $record->{"scantron.$ansnum.answer"}='';
 5809:             }
 5810:             $ansnum++;
 5811:         }
 5812:     } elsif (!defined($currquest)
 5813:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 5814:             || (&occurence_count($currquest,$matchon) == 0)) {
 5815:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5816:             $record->{"scantron.$ansnum.answer"}='';
 5817:             $ansnum++;
 5818:         }
 5819:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5820:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 5821:         }
 5822:     } else {
 5823:         if ($$scantron_config{'Qon'} eq 'number') {
 5824:             $currquest = &digits_to_letters($currquest);            
 5825:         }
 5826:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5827:             my $bubble = substr($currquest,$ans,1);
 5828:             $record->{"scantron.$ansnum.answer"} = $bubble;
 5829:             $ansnum++;
 5830:         }
 5831:     }
 5832:     return $ansnum;
 5833: }
 5834: 
 5835: sub scantron_validator_positional {
 5836:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 5837:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
 5838: 
 5839:     # Otherwise there's a positional notation;
 5840:     # each bubble line requires Qlength items, and there are filled in
 5841:     # bubbles for each case where there 'Qon' characters.
 5842:     #
 5843: 
 5844:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 5845: 
 5846:     # If the split only gives us one element.. the full length of the
 5847:     # answer string, no bubbles are filled in:
 5848: 
 5849:     if ($answers_needed eq '') {
 5850:         return;
 5851:     }
 5852: 
 5853:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 5854:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5855:             $record->{"scantron.$ansnum.answer"}='';
 5856:             $ansnum++;
 5857:         }
 5858:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5859:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 5860:         }
 5861:     } elsif (scalar(@array) == 2) {
 5862:         my $location = length($array[0]);
 5863:         my $line_num = int($location / $$scantron_config{'Qlength'});
 5864:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 5865:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5866:             if ($ans eq $line_num) {
 5867:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 5868:             } else {
 5869:                 $record->{"scantron.$ansnum.answer"} = ' ';
 5870:             }
 5871:             $ansnum++;
 5872:          }
 5873:     } else {
 5874:         #  If there's more than one instance of a bubble character
 5875:         #  That's a double bubble; with positional notation we can
 5876:         #  record all the bubbles filled in as well as the
 5877:         #  fact this response consists of multiple bubbles.
 5878:         #
 5879:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5880:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5881:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5882:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5883:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5884:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5885:             my $doubleerror = 0;
 5886:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 5887:                    (!$doubleerror)) {
 5888:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 5889:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 5890:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 5891:                if (length(@currarray) > 2) {
 5892:                    $doubleerror = 1;
 5893:                } 
 5894:             }
 5895:             if ($doubleerror) {
 5896:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5897:             }
 5898:         } else {
 5899:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5900:         }
 5901:         my $item = $ansnum;
 5902:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5903:             $record->{"scantron.$item.answer"} = '';
 5904:             $item ++;
 5905:         }
 5906: 
 5907:         my @ans=@array;
 5908:         my $i=0;
 5909:         my $increment = 0;
 5910:         while ($#ans) {
 5911:             $i+=length($ans[0]) + $increment;
 5912:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 5913:             my $bubble = $i%$$scantron_config{'Qlength'};
 5914:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 5915:             shift(@ans);
 5916:             $increment = 1;
 5917:         }
 5918:         $ansnum += $answers_needed;
 5919:     }
 5920:     return $ansnum;
 5921: }
 5922: 
 5923: =pod
 5924: 
 5925: =item scantron_add_delay
 5926: 
 5927:    Adds an error message that occurred during the grading phase to a
 5928:    queue of messages to be shown after grading pass is complete
 5929: 
 5930:  Arguments:
 5931:    $delayqueue  - arrary ref of hash ref of error messages
 5932:    $scanline    - the scanline that caused the error
 5933:    $errormesage - the error message
 5934:    $errorcode   - a numeric code for the error
 5935: 
 5936:  Side Effects:
 5937:    updates the $delayqueue to have a new hash ref of the error
 5938: 
 5939: =cut
 5940: 
 5941: sub scantron_add_delay {
 5942:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 5943:     push(@$delayqueue,
 5944: 	 {'line' => $scanline, 'emsg' => $errormessage,
 5945: 	  'ecode' => $errorcode }
 5946: 	 );
 5947: }
 5948: 
 5949: =pod
 5950: 
 5951: =item scantron_find_student
 5952: 
 5953:    Finds the username for the current scanline
 5954: 
 5955:   Arguments:
 5956:    $scantron_record - hash result from scantron_parse_scanline
 5957:    $scan_data       - hash of correction information 
 5958:                       (see &scantron_getfile() form more information)
 5959:    $idmap           - hash from &username_to_idmap()
 5960:    $line            - number of current scanline
 5961:  
 5962:   Returns:
 5963:    Either 'username:domain' or undef if unknown
 5964: 
 5965: =cut
 5966: 
 5967: sub scantron_find_student {
 5968:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 5969:     my $scanID=$$scantron_record{'scantron.ID'};
 5970:     if ($scanID =~ /^\s*$/) {
 5971:  	return &scan_data($scan_data,"$line.user");
 5972:     }
 5973:     foreach my $id (keys(%$idmap)) {
 5974:  	if (lc($id) eq lc($scanID)) {
 5975:  	    return $$idmap{$id};
 5976:  	}
 5977:     }
 5978:     return undef;
 5979: }
 5980: 
 5981: =pod
 5982: 
 5983: =item scantron_filter
 5984: 
 5985:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 5986:    hidden resources was selected
 5987: 
 5988: =cut
 5989: 
 5990: sub scantron_filter {
 5991:     my ($curres)=@_;
 5992: 
 5993:     if (ref($curres) && $curres->is_problem()) {
 5994: 	# if the user has asked to not have either hidden
 5995: 	# or 'randomout' controlled resources to be graded
 5996: 	# don't include them
 5997: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 5998: 	    && $curres->randomout) {
 5999: 	    return 0;
 6000: 	}
 6001: 	return 1;
 6002:     }
 6003:     return 0;
 6004: }
 6005: 
 6006: =pod
 6007: 
 6008: =item scantron_process_corrections
 6009: 
 6010:    Gets correction information out of submitted form data and corrects
 6011:    the scanline
 6012: 
 6013: =cut
 6014: 
 6015: sub scantron_process_corrections {
 6016:     my ($r) = @_;
 6017:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6018:     my ($scanlines,$scan_data)=&scantron_getfile();
 6019:     my $classlist=&Apache::loncoursedata::get_classlist();
 6020:     my $which=$env{'form.scantron_line'};
 6021:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 6022:     my ($skip,$err,$errmsg);
 6023:     if ($env{'form.scantron_skip_record'}) {
 6024: 	$skip=1;
 6025:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 6026: 	my $newstudent=$env{'form.scantron_username'}.':'.
 6027: 	    $env{'form.scantron_domain'};
 6028: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 6029: 	($line,$err,$errmsg)=
 6030: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6031: 				     'ID',{'newid'=>$newid,
 6032: 				    'username'=>$env{'form.scantron_username'},
 6033: 				    'domain'=>$env{'form.scantron_domain'}});
 6034:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 6035: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 6036: 	my $newCODE;
 6037: 	my %args;
 6038: 	if      ($resolution eq 'use_unfound') {
 6039: 	    $newCODE='use_unfound';
 6040: 	} elsif ($resolution eq 'use_found') {
 6041: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6042: 	} elsif ($resolution eq 'use_typed') {
 6043: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6044: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6045: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6046: 	}
 6047: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6048: 	    $args{'CODE_ignore_dup'}=1;
 6049: 	}
 6050: 	$args{'CODE'}=$newCODE;
 6051: 	($line,$err,$errmsg)=
 6052: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6053: 				     'CODE',\%args);
 6054:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6055: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6056: 	    ($line,$err,$errmsg)=
 6057: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6058: 					 $which,'answer',
 6059: 					 { 'question'=>$question,
 6060: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6061:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6062: 	    if ($err) { last; }
 6063: 	}
 6064:     }
 6065:     if ($err) {
 6066: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
 6067:     } else {
 6068: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 6069: 	&scantron_putfile($scanlines,$scan_data);
 6070:     }
 6071: }
 6072: 
 6073: =pod
 6074: 
 6075: =item reset_skipping_status
 6076: 
 6077:    Forgets the current set of remember skipped scanlines (and thus
 6078:    reverts back to considering all lines in the
 6079:    scantron_skipped_<filename> file)
 6080: 
 6081: =cut
 6082: 
 6083: sub reset_skipping_status {
 6084:     my ($scanlines,$scan_data)=&scantron_getfile();
 6085:     &scan_data($scan_data,'remember_skipping',undef,1);
 6086:     &scantron_putfile(undef,$scan_data);
 6087: }
 6088: 
 6089: =pod
 6090: 
 6091: =item start_skipping
 6092: 
 6093:    Marks a scanline to be skipped. 
 6094: 
 6095: =cut
 6096: 
 6097: sub start_skipping {
 6098:     my ($scan_data,$i)=@_;
 6099:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6100:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6101: 	$remembered{$i}=2;
 6102:     } else {
 6103: 	$remembered{$i}=1;
 6104:     }
 6105:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6106: }
 6107: 
 6108: =pod
 6109: 
 6110: =item should_be_skipped
 6111: 
 6112:    Checks whether a scanline should be skipped.
 6113: 
 6114: =cut
 6115: 
 6116: sub should_be_skipped {
 6117:     my ($scanlines,$scan_data,$i)=@_;
 6118:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6119: 	# not redoing old skips
 6120: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6121: 	return 0;
 6122:     }
 6123:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6124: 
 6125:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6126: 	return 0;
 6127:     }
 6128:     return 1;
 6129: }
 6130: 
 6131: =pod
 6132: 
 6133: =item remember_current_skipped
 6134: 
 6135:    Discovers what scanlines are in the scantron_skipped_<filename>
 6136:    file and remembers them into scan_data for later use.
 6137: 
 6138: =cut
 6139: 
 6140: sub remember_current_skipped {
 6141:     my ($scanlines,$scan_data)=&scantron_getfile();
 6142:     my %to_remember;
 6143:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6144: 	if ($scanlines->{'skipped'}[$i]) {
 6145: 	    $to_remember{$i}=1;
 6146: 	}
 6147:     }
 6148: 
 6149:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6150:     &scantron_putfile(undef,$scan_data);
 6151: }
 6152: 
 6153: =pod
 6154: 
 6155: =item check_for_error
 6156: 
 6157:     Checks if there was an error when attempting to remove a specific
 6158:     scantron_.. bubble sheet data file. Prints out an error if
 6159:     something went wrong.
 6160: 
 6161: =cut
 6162: 
 6163: sub check_for_error {
 6164:     my ($r,$result)=@_;
 6165:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6166: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6167:     }
 6168: }
 6169: 
 6170: =pod
 6171: 
 6172: =item scantron_warning_screen
 6173: 
 6174:    Interstitial screen to make sure the operator has selected the
 6175:    correct options before we start the validation phase.
 6176: 
 6177: =cut
 6178: 
 6179: sub scantron_warning_screen {
 6180:     my ($button_text,$symb)=@_;
 6181:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6182:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6183:     my $CODElist;
 6184:     if ($scantron_config{'CODElocation'} &&
 6185: 	$scantron_config{'CODEstart'} &&
 6186: 	$scantron_config{'CODElength'}) {
 6187: 	$CODElist=$env{'form.scantron_CODElist'};
 6188: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
 6189: 	$CODElist=
 6190: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6191: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6192:     }
 6193:     return ('
 6194: <p>
 6195: <span class="LC_warning">
 6196: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
 6197: </p>
 6198: <table>
 6199: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6200: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6201: '.$CODElist.'
 6202: </table>
 6203: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'<br />
 6204: '.&mt('If something is incorrect, please return to [_1]Grade/Manage/Review Bubblesheets[_2] to start over.','<a href="/adm/grades?symb='.$symb.'&command=scantron_selectphase" class="LC_info">','</a>').'</p>
 6205: 
 6206: <br />
 6207: ');
 6208: }
 6209: 
 6210: =pod
 6211: 
 6212: =item scantron_do_warning
 6213: 
 6214:    Check if the operator has picked something for all required
 6215:    fields. Error out if something is missing.
 6216: 
 6217: =cut
 6218: 
 6219: sub scantron_do_warning {
 6220:     my ($r,$symb)=@_;
 6221:     if (!$symb) {return '';}
 6222:     my $default_form_data=&defaultFormData($symb);
 6223:     $r->print(&scantron_form_start().$default_form_data);
 6224:     if ( $env{'form.selectpage'} eq '' ||
 6225: 	 $env{'form.scantron_selectfile'} eq '' ||
 6226: 	 $env{'form.scantron_format'} eq '' ) {
 6227: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
 6228: 	if ( $env{'form.selectpage'} eq '') {
 6229: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6230: 	} 
 6231: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6232: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
 6233: 	} 
 6234: 	if ( $env{'form.scantron_format'} eq '') {
 6235: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
 6236: 	} 
 6237:     } else {
 6238: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
 6239: 	$r->print('
 6240: '.$warning.'
 6241: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6242: <input type="hidden" name="command" value="scantron_validate" />
 6243: ');
 6244:     }
 6245:     $r->print("</form><br />");
 6246:     return '';
 6247: }
 6248: 
 6249: =pod
 6250: 
 6251: =item scantron_form_start
 6252: 
 6253:     html hidden input for remembering all selected grading options
 6254: 
 6255: =cut
 6256: 
 6257: sub scantron_form_start {
 6258:     my ($max_bubble)=@_;
 6259:     my $result= <<SCANTRONFORM;
 6260: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6261:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6262:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6263:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6264:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6265:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6266:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6267:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6268:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6269:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6270: SCANTRONFORM
 6271: 
 6272:   my $line = 0;
 6273:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6274:        my $chunk =
 6275: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6276:        $chunk .=
 6277: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6278:        $chunk .= 
 6279:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6280:        $chunk .=
 6281:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6282:        $result .= $chunk;
 6283:        $line++;
 6284:    }
 6285:     return $result;
 6286: }
 6287: 
 6288: =pod
 6289: 
 6290: =item scantron_validate_file
 6291: 
 6292:     Dispatch routine for doing validation of a bubble sheet data file.
 6293: 
 6294:     Also processes any necessary information resets that need to
 6295:     occur before validation begins (ignore previous corrections,
 6296:     restarting the skipped records processing)
 6297: 
 6298: =cut
 6299: 
 6300: sub scantron_validate_file {
 6301:     my ($r,$symb) = @_;
 6302:     if (!$symb) {return '';}
 6303:     my $default_form_data=&defaultFormData($symb);
 6304:     
 6305:     # do the detection of only doing skipped records first befroe we delete
 6306:     # them when doing the corrections reset
 6307:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6308: 	&reset_skipping_status();
 6309:     }
 6310:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6311: 	&remember_current_skipped();
 6312: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6313:     }
 6314: 
 6315:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6316: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6317: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6318: 	&check_for_error($r,&scantron_remove_scan_data());
 6319: 	$env{'form.scantron_options_ignore'}='done';
 6320:     }
 6321: 
 6322:     if ($env{'form.scantron_corrections'}) {
 6323: 	&scantron_process_corrections($r);
 6324:     }
 6325:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6326:     #get the student pick code ready
 6327:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6328:     my $nav_error;
 6329:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6330:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 6331:     if ($nav_error) {
 6332:         $r->print(&navmap_errormsg());
 6333:         return '';
 6334:     }
 6335:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6336:     $r->print($result);
 6337:     
 6338:     my @validate_phases=( 'sequence',
 6339: 			  'ID',
 6340: 			  'CODE',
 6341: 			  'doublebubble',
 6342: 			  'missingbubbles');
 6343:     if (!$env{'form.validatepass'}) {
 6344: 	$env{'form.validatepass'} = 0;
 6345:     }
 6346:     my $currentphase=$env{'form.validatepass'};
 6347: 
 6348: 
 6349:     my $stop=0;
 6350:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6351: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6352: 	$r->rflush();
 6353: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6354: 	{
 6355: 	    no strict 'refs';
 6356: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6357: 	}
 6358:     }
 6359:     if (!$stop) {
 6360: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
 6361: 	$r->print(&mt('Validation process complete.').'<br />'.
 6362:                   $warning.
 6363:                   &mt('Perform verification for each student after storage of submissions?').
 6364:                   '&nbsp;<span class="LC_nobreak"><label>'.
 6365:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 6366:                   ('&nbsp;'x3).'<label>'.
 6367:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 6368:                   '</label></span><br />'.
 6369:                   &mt('Grading will take longer if you use verification.').'<br />'.
 6370:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
 6371:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 6372:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 6373:     } else {
 6374: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6375: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6376:     }
 6377:     if ($stop) {
 6378: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6379: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 6380: 	    $r->print(' '.&mt('this error').' <br />');
 6381: 
 6382: 	    $r->print('<p>'.&mt('Or return to [_1]Grade/Manage/Review Bubblesheets[_2] to start over.','<a href="/adm/grades?symb='.$symb.'&command=scantron_selectphase" class="LC_info">','</a>').'</p>');
 6383: 	} else {
 6384:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6385: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 6386:             } else {
 6387:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 6388:             }
 6389: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6390: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6391: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6392: 	}
 6393:     }
 6394:     $r->print(" </form><br />");
 6395:     return '';
 6396: }
 6397: 
 6398: 
 6399: =pod
 6400: 
 6401: =item scantron_remove_file
 6402: 
 6403:    Removes the requested bubble sheet data file, makes sure that
 6404:    scantron_original_<filename> is never removed
 6405: 
 6406: 
 6407: =cut
 6408: 
 6409: sub scantron_remove_file {
 6410:     my ($which)=@_;
 6411:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6412:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6413:     my $file='scantron_';
 6414:     if ($which eq 'corrected' || $which eq 'skipped') {
 6415: 	$file.=$which.'_';
 6416:     } else {
 6417: 	return 'refused';
 6418:     }
 6419:     $file.=$env{'form.scantron_selectfile'};
 6420:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6421: }
 6422: 
 6423: 
 6424: =pod
 6425: 
 6426: =item scantron_remove_scan_data
 6427: 
 6428:    Removes all scan_data correction for the requested bubble sheet
 6429:    data file.  (In the case that both the are doing skipped records we need
 6430:    to remember the old skipped lines for the time being so that element
 6431:    persists for a while.)
 6432: 
 6433: =cut
 6434: 
 6435: sub scantron_remove_scan_data {
 6436:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6437:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6438:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6439:     my @todelete;
 6440:     my $filename=$env{'form.scantron_selectfile'};
 6441:     foreach my $key (@keys) {
 6442: 	if ($key=~/^\Q$filename\E_/) {
 6443: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6444: 		$key=~/remember_skipping/) {
 6445: 		next;
 6446: 	    }
 6447: 	    push(@todelete,$key);
 6448: 	}
 6449:     }
 6450:     my $result;
 6451:     if (@todelete) {
 6452: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6453: 				       \@todelete,$cdom,$cname);
 6454:     } else {
 6455: 	$result = 'ok';
 6456:     }
 6457:     return $result;
 6458: }
 6459: 
 6460: 
 6461: =pod
 6462: 
 6463: =item scantron_getfile
 6464: 
 6465:     Fetches the requested bubble sheet data file (all 3 versions), and
 6466:     the scan_data hash
 6467:   
 6468:   Arguments:
 6469:     None
 6470: 
 6471:   Returns:
 6472:     2 hash references
 6473: 
 6474:      - first one has 
 6475:          orig      -
 6476:          corrected -
 6477:          skipped   -  each of which points to an array ref of the specified
 6478:                       file broken up into individual lines
 6479:          count     - number of scanlines
 6480:  
 6481:      - second is the scan_data hash possible keys are
 6482:        ($number refers to scanline numbered $number and thus the key affects
 6483:         only that scanline
 6484:         $bubline refers to the specific bubble line element and the aspects
 6485:         refers to that specific bubble line element)
 6486: 
 6487:        $number.user - username:domain to use
 6488:        $number.CODE_ignore_dup 
 6489:                     - ignore the duplicate CODE error 
 6490:        $number.useCODE
 6491:                     - use the CODE in the scanline as is
 6492:        $number.no_bubble.$bubline
 6493:                     - it is valid that there is no bubbled in bubble
 6494:                       at $number $bubline
 6495:        remember_skipping
 6496:                     - a frozen hash containing keys of $number and values
 6497:                       of either 
 6498:                         1 - we are on a 'do skipped records pass' and plan
 6499:                             on processing this line
 6500:                         2 - we are on a 'do skipped records pass' and this
 6501:                             scanline has been marked to skip yet again
 6502: 
 6503: =cut
 6504: 
 6505: sub scantron_getfile {
 6506:     #FIXME really would prefer a scantron directory
 6507:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6508:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6509:     my $lines;
 6510:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6511: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 6512:     my %scanlines;
 6513:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 6514:     my $temp=$scanlines{'orig'};
 6515:     $scanlines{'count'}=$#$temp;
 6516: 
 6517:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6518: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 6519:     if ($lines eq '-1') {
 6520: 	$scanlines{'corrected'}=[];
 6521:     } else {
 6522: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 6523:     }
 6524:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6525: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 6526:     if ($lines eq '-1') {
 6527: 	$scanlines{'skipped'}=[];
 6528:     } else {
 6529: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 6530:     }
 6531:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 6532:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 6533:     my %scan_data = @tmp;
 6534:     return (\%scanlines,\%scan_data);
 6535: }
 6536: 
 6537: =pod
 6538: 
 6539: =item lonnet_putfile
 6540: 
 6541:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 6542: 
 6543:  Arguments:
 6544:    $contents - data to store
 6545:    $filename - filename to store $contents into
 6546: 
 6547:  Returns:
 6548:    result value from &Apache::lonnet::finishuserfileupload
 6549: 
 6550: =cut
 6551: 
 6552: sub lonnet_putfile {
 6553:     my ($contents,$filename)=@_;
 6554:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6555:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6556:     $env{'form.sillywaytopassafilearound'}=$contents;
 6557:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 6558: 
 6559: }
 6560: 
 6561: =pod
 6562: 
 6563: =item scantron_putfile
 6564: 
 6565:     Stores the current version of the bubble sheet data files, and the
 6566:     scan_data hash. (Does not modify the original version only the
 6567:     corrected and skipped versions.
 6568: 
 6569:  Arguments:
 6570:     $scanlines - hash ref that looks like the first return value from
 6571:                  &scantron_getfile()
 6572:     $scan_data - hash ref that looks like the second return value from
 6573:                  &scantron_getfile()
 6574: 
 6575: =cut
 6576: 
 6577: sub scantron_putfile {
 6578:     my ($scanlines,$scan_data) = @_;
 6579:     #FIXME really would prefer a scantron directory
 6580:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6581:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6582:     if ($scanlines) {
 6583: 	my $prefix='scantron_';
 6584: # no need to update orig, shouldn't change
 6585: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 6586: #		    $env{'form.scantron_selectfile'});
 6587: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 6588: 			$prefix.'corrected_'.
 6589: 			$env{'form.scantron_selectfile'});
 6590: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 6591: 			$prefix.'skipped_'.
 6592: 			$env{'form.scantron_selectfile'});
 6593:     }
 6594:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 6595: }
 6596: 
 6597: =pod
 6598: 
 6599: =item scantron_get_line
 6600: 
 6601:    Returns the correct version of the scanline
 6602: 
 6603:  Arguments:
 6604:     $scanlines - hash ref that looks like the first return value from
 6605:                  &scantron_getfile()
 6606:     $scan_data - hash ref that looks like the second return value from
 6607:                  &scantron_getfile()
 6608:     $i         - number of the requested line (starts at 0)
 6609: 
 6610:  Returns:
 6611:    A scanline, (either the original or the corrected one if it
 6612:    exists), or undef if the requested scanline should be
 6613:    skipped. (Either because it's an skipped scanline, or it's an
 6614:    unskipped scanline and we are not doing a 'do skipped scanlines'
 6615:    pass.
 6616: 
 6617: =cut
 6618: 
 6619: sub scantron_get_line {
 6620:     my ($scanlines,$scan_data,$i)=@_;
 6621:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 6622:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 6623:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 6624:     return $scanlines->{'orig'}[$i]; 
 6625: }
 6626: 
 6627: =pod
 6628: 
 6629: =item scantron_todo_count
 6630: 
 6631:     Counts the number of scanlines that need processing.
 6632: 
 6633:  Arguments:
 6634:     $scanlines - hash ref that looks like the first return value from
 6635:                  &scantron_getfile()
 6636:     $scan_data - hash ref that looks like the second return value from
 6637:                  &scantron_getfile()
 6638: 
 6639:  Returns:
 6640:     $count - number of scanlines to process
 6641: 
 6642: =cut
 6643: 
 6644: sub get_todo_count {
 6645:     my ($scanlines,$scan_data)=@_;
 6646:     my $count=0;
 6647:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6648: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6649: 	if ($line=~/^[\s\cz]*$/) { next; }
 6650: 	$count++;
 6651:     }
 6652:     return $count;
 6653: }
 6654: 
 6655: =pod
 6656: 
 6657: =item scantron_put_line
 6658: 
 6659:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
 6660:     data file.
 6661: 
 6662:  Arguments:
 6663:     $scanlines - hash ref that looks like the first return value from
 6664:                  &scantron_getfile()
 6665:     $scan_data - hash ref that looks like the second return value from
 6666:                  &scantron_getfile()
 6667:     $i         - line number to update
 6668:     $newline   - contents of the updated scanline
 6669:     $skip      - if true make the line for skipping and update the
 6670:                  'skipped' file
 6671: 
 6672: =cut
 6673: 
 6674: sub scantron_put_line {
 6675:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 6676:     if ($skip) {
 6677: 	$scanlines->{'skipped'}[$i]=$newline;
 6678: 	&start_skipping($scan_data,$i);
 6679: 	return;
 6680:     }
 6681:     $scanlines->{'corrected'}[$i]=$newline;
 6682: }
 6683: 
 6684: =pod
 6685: 
 6686: =item scantron_clear_skip
 6687: 
 6688:    Remove a line from the 'skipped' file
 6689: 
 6690:  Arguments:
 6691:     $scanlines - hash ref that looks like the first return value from
 6692:                  &scantron_getfile()
 6693:     $scan_data - hash ref that looks like the second return value from
 6694:                  &scantron_getfile()
 6695:     $i         - line number to update
 6696: 
 6697: =cut
 6698: 
 6699: sub scantron_clear_skip {
 6700:     my ($scanlines,$scan_data,$i)=@_;
 6701:     if (exists($scanlines->{'skipped'}[$i])) {
 6702: 	undef($scanlines->{'skipped'}[$i]);
 6703: 	return 1;
 6704:     }
 6705:     return 0;
 6706: }
 6707: 
 6708: =pod
 6709: 
 6710: =item scantron_filter_not_exam
 6711: 
 6712:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 6713:    filter out resources that are not marked as 'exam' mode
 6714: 
 6715: =cut
 6716: 
 6717: sub scantron_filter_not_exam {
 6718:     my ($curres)=@_;
 6719:     
 6720:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 6721: 	# if the user has asked to not have either hidden
 6722: 	# or 'randomout' controlled resources to be graded
 6723: 	# don't include them
 6724: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6725: 	    && $curres->randomout) {
 6726: 	    return 0;
 6727: 	}
 6728: 	return 1;
 6729:     }
 6730:     return 0;
 6731: }
 6732: 
 6733: =pod
 6734: 
 6735: =item scantron_validate_sequence
 6736: 
 6737:     Validates the selected sequence, checking for resource that are
 6738:     not set to exam mode.
 6739: 
 6740: =cut
 6741: 
 6742: sub scantron_validate_sequence {
 6743:     my ($r,$currentphase) = @_;
 6744: 
 6745:     my $navmap=Apache::lonnavmaps::navmap->new();
 6746:     unless (ref($navmap)) {
 6747:         $r->print(&navmap_errormsg());
 6748:         return (1,$currentphase);
 6749:     }
 6750:     my (undef,undef,$sequence)=
 6751: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6752: 
 6753:     my $map=$navmap->getResourceByUrl($sequence);
 6754: 
 6755:     $r->print('<input type="hidden" name="validate_sequence_exam"
 6756:                                     value="ignore" />');
 6757:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 6758: 	my @resources=
 6759: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 6760: 	if (@resources) {
 6761: 	    $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>");
 6762: 	    return (1,$currentphase);
 6763: 	}
 6764:     }
 6765: 
 6766:     return (0,$currentphase+1);
 6767: }
 6768: 
 6769: 
 6770: 
 6771: sub scantron_validate_ID {
 6772:     my ($r,$currentphase) = @_;
 6773:     
 6774:     #get student info
 6775:     my $classlist=&Apache::loncoursedata::get_classlist();
 6776:     my %idmap=&username_to_idmap($classlist);
 6777: 
 6778:     #get scantron line setup
 6779:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6780:     my ($scanlines,$scan_data)=&scantron_getfile();
 6781: 
 6782:     my $nav_error;
 6783:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
 6784:     if ($nav_error) {
 6785:         $r->print(&navmap_errormsg());
 6786:         return(1,$currentphase);
 6787:     }
 6788: 
 6789:     my %found=('ids'=>{},'usernames'=>{});
 6790:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6791: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6792: 	if ($line=~/^[\s\cz]*$/) { next; }
 6793: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6794: 						 $scan_data);
 6795: 	my $id=$$scan_record{'scantron.ID'};
 6796: 	my $found;
 6797: 	foreach my $checkid (keys(%idmap)) {
 6798: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 6799: 	}
 6800: 	if ($found) {
 6801: 	    my $username=$idmap{$found};
 6802: 	    if ($found{'ids'}{$found}) {
 6803: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6804: 					 $line,'duplicateID',$found);
 6805: 		return(1,$currentphase);
 6806: 	    } elsif ($found{'usernames'}{$username}) {
 6807: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6808: 					 $line,'duplicateID',$username);
 6809: 		return(1,$currentphase);
 6810: 	    }
 6811: 	    #FIXME store away line we previously saw the ID on to use above
 6812: 	    $found{'ids'}{$found}++;
 6813: 	    $found{'usernames'}{$username}++;
 6814: 	} else {
 6815: 	    if ($id =~ /^\s*$/) {
 6816: 		my $username=&scan_data($scan_data,"$i.user");
 6817: 		if (defined($username) && $found{'usernames'}{$username}) {
 6818: 		    &scantron_get_correction($r,$i,$scan_record,
 6819: 					     \%scantron_config,
 6820: 					     $line,'duplicateID',$username);
 6821: 		    return(1,$currentphase);
 6822: 		} elsif (!defined($username)) {
 6823: 		    &scantron_get_correction($r,$i,$scan_record,
 6824: 					     \%scantron_config,
 6825: 					     $line,'incorrectID');
 6826: 		    return(1,$currentphase);
 6827: 		}
 6828: 		$found{'usernames'}{$username}++;
 6829: 	    } else {
 6830: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6831: 					 $line,'incorrectID');
 6832: 		return(1,$currentphase);
 6833: 	    }
 6834: 	}
 6835:     }
 6836: 
 6837:     return (0,$currentphase+1);
 6838: }
 6839: 
 6840: 
 6841: sub scantron_get_correction {
 6842:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
 6843: #FIXME in the case of a duplicated ID the previous line, probably need
 6844: #to show both the current line and the previous one and allow skipping
 6845: #the previous one or the current one
 6846: 
 6847:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 6848: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6849: 			    " for PaperID <tt>[_1]</tt>",
 6850: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
 6851:     } else {
 6852: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6853: 			    " in scanline [_1] <pre>[_2]</pre>",
 6854: 			    $i,$line)."</p> \n");
 6855:     }
 6856:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
 6857: 			  "The name on the paper is [_2],[_3]",
 6858: 			  $$scan_record{'scantron.ID'},
 6859: 			  $$scan_record{'scantron.LastName'},
 6860: 			  $$scan_record{'scantron.FirstName'})."</p>";
 6861: 
 6862:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 6863:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 6864:                            # Array populated for doublebubble or
 6865:     my @lines_to_correct;  # missingbubble errors to build javascript
 6866:                            # to validate radio button checking   
 6867: 
 6868:     if ($error =~ /ID$/) {
 6869: 	if ($error eq 'incorrectID') {
 6870: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
 6871: 		      "</p>\n");
 6872: 	} elsif ($error eq 'duplicateID') {
 6873: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 6874: 	}
 6875: 	$r->print($message);
 6876: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6877: 	$r->print("\n<ul><li> ");
 6878: 	#FIXME it would be nice if this sent back the user ID and
 6879: 	#could do partial userID matches
 6880: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 6881: 				       'scantron_username','scantron_domain'));
 6882: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 6883: 	$r->print("\n@".
 6884: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 6885: 
 6886: 	$r->print('</li>');
 6887:     } elsif ($error =~ /CODE$/) {
 6888: 	if ($error eq 'incorrectCODE') {
 6889: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 6890: 	} elsif ($error eq 'duplicateCODE') {
 6891: 	    $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");
 6892: 	}
 6893: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
 6894: 			    $$scan_record{'scantron.CODE'})."<br />\n");
 6895: 	$r->print($message);
 6896: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6897: 	$r->print("\n<br /> ");
 6898: 	my $i=0;
 6899: 	if ($error eq 'incorrectCODE' 
 6900: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 6901: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 6902: 	    if ($closest > 0) {
 6903: 		foreach my $testcode (@{$closest}) {
 6904: 		    my $checked='';
 6905: 		    if (!$i) { $checked=' checked="checked"'; }
 6906: 		    $r->print("
 6907:    <label>
 6908:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 6909:        ".&mt("Use the similar CODE [_1] instead.",
 6910: 	    "<b><tt>".$testcode."</tt></b>")."
 6911:     </label>
 6912:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 6913: 		    $r->print("\n<br />");
 6914: 		    $i++;
 6915: 		}
 6916: 	    }
 6917: 	}
 6918: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 6919: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 6920: 	    $r->print("
 6921:     <label>
 6922:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 6923:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
 6924: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 6925:     </label>");
 6926: 	    $r->print("\n<br />");
 6927: 	}
 6928: 
 6929: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
 6930: function change_radio(field) {
 6931:     var slct=document.scantronupload.scantron_CODE_resolution;
 6932:     var i;
 6933:     for (i=0;i<slct.length;i++) {
 6934:         if (slct[i].value==field) { slct[i].checked=true; }
 6935:     }
 6936: }
 6937: ENDSCRIPT
 6938: 	my $href="/adm/pickcode?".
 6939: 	   "form=".&escape("scantronupload").
 6940: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 6941: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 6942: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 6943: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 6944: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 6945: 	    $r->print("
 6946:     <label>
 6947:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 6948:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 6949: 	     "<a target='_blank' href='$href'>","</a>")."
 6950:     </label> 
 6951:     ".&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\')" />'));
 6952: 	    $r->print("\n<br />");
 6953: 	}
 6954: 	$r->print("
 6955:     <label>
 6956:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 6957:        ".&mt("Use [_1] as the CODE.",
 6958: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 6959: 	$r->print("\n<br /><br />");
 6960:     } elsif ($error eq 'doublebubble') {
 6961: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 6962: 
 6963: 	# The form field scantron_questions is acutally a list of line numbers.
 6964: 	# represented by this form so:
 6965: 
 6966: 	my $line_list = &questions_to_line_list($arg);
 6967: 
 6968: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6969: 		  $line_list.'" />');
 6970: 	$r->print($message);
 6971: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 6972: 	foreach my $question (@{$arg}) {
 6973: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6974:                                                    $scan_record, $error);
 6975:             push(@lines_to_correct,@linenums);
 6976: 	}
 6977:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6978:     } elsif ($error eq 'missingbubble') {
 6979: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
 6980: 	$r->print($message);
 6981: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 6982: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 6983: 
 6984: 	# The form field scantron_questions is actually a list of line numbers not
 6985: 	# a list of question numbers. Therefore:
 6986: 	#
 6987: 	
 6988: 	my $line_list = &questions_to_line_list($arg);
 6989: 
 6990: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6991: 		  $line_list.'" />');
 6992: 	foreach my $question (@{$arg}) {
 6993: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6994:                                                    $scan_record, $error);
 6995:             push(@lines_to_correct,@linenums);
 6996: 	}
 6997:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6998:     } else {
 6999: 	$r->print("\n<ul>");
 7000:     }
 7001:     $r->print("\n</li></ul>");
 7002: }
 7003: 
 7004: sub verify_bubbles_checked {
 7005:     my (@ansnums) = @_;
 7006:     my $ansnumstr = join('","',@ansnums);
 7007:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 7008:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
 7009: function verify_bubble_radio(form) {
 7010:     var ansnumArray = new Array ("$ansnumstr");
 7011:     var need_bubble_count = 0;
 7012:     for (var i=0; i<ansnumArray.length; i++) {
 7013:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 7014:             var bubble_picked = 0; 
 7015:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 7016:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 7017:                     bubble_picked = 1;
 7018:                 }
 7019:             }
 7020:             if (bubble_picked == 0) {
 7021:                 need_bubble_count ++;
 7022:             }
 7023:         }
 7024:     }
 7025:     if (need_bubble_count) {
 7026:         alert("$warning");
 7027:         return;
 7028:     }
 7029:     form.submit(); 
 7030: }
 7031: ENDSCRIPT
 7032:     return $output;
 7033: }
 7034: 
 7035: =pod
 7036: 
 7037: =item  questions_to_line_list
 7038: 
 7039: Converts a list of questions into a string of comma separated
 7040: line numbers in the answer sheet used by the questions.  This is
 7041: used to fill in the scantron_questions form field.
 7042: 
 7043:   Arguments:
 7044:      questions    - Reference to an array of questions.
 7045: 
 7046: =cut
 7047: 
 7048: 
 7049: sub questions_to_line_list {
 7050:     my ($questions) = @_;
 7051:     my @lines;
 7052: 
 7053:     foreach my $item (@{$questions}) {
 7054:         my $question = $item;
 7055:         my ($first,$count,$last);
 7056:         if ($item =~ /^(\d+)\.(\d+)$/) {
 7057:             $question = $1;
 7058:             my $subquestion = $2;
 7059:             $first = $first_bubble_line{$question-1} + 1;
 7060:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7061:             my $subcount = 1;
 7062:             while ($subcount<$subquestion) {
 7063:                 $first += $subans[$subcount-1];
 7064:                 $subcount ++;
 7065:             }
 7066:             $count = $subans[$subquestion-1];
 7067:         } else {
 7068: 	    $first   = $first_bubble_line{$question-1} + 1;
 7069: 	    $count   = $bubble_lines_per_response{$question-1};
 7070:         }
 7071:         $last = $first+$count-1;
 7072:         push(@lines, ($first..$last));
 7073:     }
 7074:     return join(',', @lines);
 7075: }
 7076: 
 7077: =pod 
 7078: 
 7079: =item prompt_for_corrections
 7080: 
 7081: Prompts for a potentially multiline correction to the
 7082: user's bubbling (factors out common code from scantron_get_correction
 7083: for multi and missing bubble cases).
 7084: 
 7085:  Arguments:
 7086:    $r           - Apache request object.
 7087:    $question    - The question number to prompt for.
 7088:    $scan_config - The scantron file configuration hash.
 7089:    $scan_record - Reference to the hash that has the the parsed scanlines.
 7090:    $error       - Type of error
 7091: 
 7092:  Implicit inputs:
 7093:    %bubble_lines_per_response   - Starting line numbers for each question.
 7094:                                   Numbered from 0 (but question numbers are from
 7095:                                   1.
 7096:    %first_bubble_line           - Starting bubble line for each question.
 7097:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 7098:                                   type problems render as separate sub-questions, 
 7099:                                   in exam mode. This hash contains a 
 7100:                                   comma-separated list of the lines per 
 7101:                                   sub-question.
 7102:    %responsetype_per_response   - essayresponse, formularesponse,
 7103:                                   stringresponse, imageresponse, reactionresponse,
 7104:                                   and organicresponse type problem parts can have
 7105:                                   multiple lines per response if the weight
 7106:                                   assigned exceeds 10.  In this case, only
 7107:                                   one bubble per line is permitted, but more 
 7108:                                   than one line might contain bubbles, e.g.
 7109:                                   bubbling of: line 1 - J, line 2 - J, 
 7110:                                   line 3 - B would assign 22 points.  
 7111: 
 7112: =cut
 7113: 
 7114: sub prompt_for_corrections {
 7115:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
 7116:     my ($current_line,$lines);
 7117:     my @linenums;
 7118:     my $questionnum = $question;
 7119:     if ($question =~ /^(\d+)\.(\d+)$/) {
 7120:         $question = $1;
 7121:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7122:         my $subquestion = $2;
 7123:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7124:         my $subcount = 1;
 7125:         while ($subcount<$subquestion) {
 7126:             $current_line += $subans[$subcount-1];
 7127:             $subcount ++;
 7128:         }
 7129:         $lines = $subans[$subquestion-1];
 7130:     } else {
 7131:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7132:         $lines        = $bubble_lines_per_response{$question-1};
 7133:     }
 7134:     if ($lines > 1) {
 7135:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7136:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
 7137:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
 7138:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
 7139:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
 7140:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
 7141:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
 7142:             $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 />');
 7143:         } else {
 7144:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7145:         }
 7146:     }
 7147:     for (my $i =0; $i < $lines; $i++) {
 7148:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7149: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
 7150: 	        		  $questionnum,$error,split('', $selected));
 7151:         push(@linenums,$current_line);
 7152: 	$current_line++;
 7153:     }
 7154:     if ($lines > 1) {
 7155: 	$r->print("<hr /><br />");
 7156:     }
 7157:     return @linenums;
 7158: }
 7159: 
 7160: =pod
 7161: 
 7162: =item scantron_bubble_selector
 7163:   
 7164:    Generates the html radiobuttons to correct a single bubble line
 7165:    possibly showing the existing the selected bubbles if known
 7166: 
 7167:  Arguments:
 7168:     $r           - Apache request object
 7169:     $scan_config - hash from &get_scantron_config()
 7170:     $line        - Number of the line being displayed.
 7171:     $questionnum - Question number (may include subquestion)
 7172:     $error       - Type of error.
 7173:     @selected    - Array of bubbles picked on this line.
 7174: 
 7175: =cut
 7176: 
 7177: sub scantron_bubble_selector {
 7178:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7179:     my $max=$$scan_config{'Qlength'};
 7180: 
 7181:     my $scmode=$$scan_config{'Qon'};
 7182:     if ($scmode eq 'number' || $scmode eq 'letter') { 
 7183:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
 7184:             ($$scan_config{'BubblesPerRow'} > 0)) {
 7185:             $max=$$scan_config{'BubblesPerRow'};
 7186:             if (($scmode eq 'number') && ($max > 10)) {
 7187:                 $max = 10;
 7188:             } elsif (($scmode eq 'letter') && $max > 26) {
 7189:                 $max = 26;
 7190:             }
 7191:         } else {
 7192:             $max = 10;
 7193:         }
 7194:     }
 7195: 
 7196:     my @alphabet=('A'..'Z');
 7197:     $r->print(&Apache::loncommon::start_data_table().
 7198:               &Apache::loncommon::start_data_table_row());
 7199:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7200:     for (my $i=0;$i<$max+1;$i++) {
 7201: 	$r->print("\n".'<td align="center">');
 7202: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7203: 	else { $r->print('&nbsp;'); }
 7204: 	$r->print('</td>');
 7205:     }
 7206:     $r->print(&Apache::loncommon::end_data_table_row().
 7207:               &Apache::loncommon::start_data_table_row());
 7208:     for (my $i=0;$i<$max;$i++) {
 7209: 	$r->print("\n".
 7210: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7211: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7212:     }
 7213:     my $nobub_checked = ' ';
 7214:     if ($error eq 'missingbubble') {
 7215:         $nobub_checked = ' checked = "checked" ';
 7216:     }
 7217:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7218: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7219:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7220:               $line.'" value="'.$questionnum.'" /></td>');
 7221:     $r->print(&Apache::loncommon::end_data_table_row().
 7222:               &Apache::loncommon::end_data_table());
 7223: }
 7224: 
 7225: =pod
 7226: 
 7227: =item num_matches
 7228: 
 7229:    Counts the number of characters that are the same between the two arguments.
 7230: 
 7231:  Arguments:
 7232:    $orig - CODE from the scanline
 7233:    $code - CODE to match against
 7234: 
 7235:  Returns:
 7236:    $count - integer count of the number of same characters between the
 7237:             two arguments
 7238: 
 7239: =cut
 7240: 
 7241: sub num_matches {
 7242:     my ($orig,$code) = @_;
 7243:     my @code=split(//,$code);
 7244:     my @orig=split(//,$orig);
 7245:     my $same=0;
 7246:     for (my $i=0;$i<scalar(@code);$i++) {
 7247: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7248:     }
 7249:     return $same;
 7250: }
 7251: 
 7252: =pod
 7253: 
 7254: =item scantron_get_closely_matching_CODEs
 7255: 
 7256:    Cycles through all CODEs and finds the set that has the greatest
 7257:    number of same characters as the provided CODE
 7258: 
 7259:  Arguments:
 7260:    $allcodes - hash ref returned by &get_codes()
 7261:    $CODE     - CODE from the current scanline
 7262: 
 7263:  Returns:
 7264:    2 element list
 7265:     - first elements is number of how closely matching the best fit is 
 7266:       (5 means best set has 5 matching characters)
 7267:     - second element is an arrary ref containing the set of valid CODEs
 7268:       that best fit the passed in CODE
 7269: 
 7270: =cut
 7271: 
 7272: sub scantron_get_closely_matching_CODEs {
 7273:     my ($allcodes,$CODE)=@_;
 7274:     my @CODEs;
 7275:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7276: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7277:     }
 7278: 
 7279:     return ($#CODEs,$CODEs[-1]);
 7280: }
 7281: 
 7282: =pod
 7283: 
 7284: =item get_codes
 7285: 
 7286:    Builds a hash which has keys of all of the valid CODEs from the selected
 7287:    set of remembered CODEs.
 7288: 
 7289:  Arguments:
 7290:   $old_name - name of the set of remembered CODEs
 7291:   $cdom     - domain of the course
 7292:   $cnum     - internal course name
 7293: 
 7294:  Returns:
 7295:   %allcodes - keys are the valid CODEs, values are all 1
 7296: 
 7297: =cut
 7298: 
 7299: sub get_codes {
 7300:     my ($old_name, $cdom, $cnum) = @_;
 7301:     if (!$old_name) {
 7302: 	$old_name=$env{'form.scantron_CODElist'};
 7303:     }
 7304:     if (!$cdom) {
 7305: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7306:     }
 7307:     if (!$cnum) {
 7308: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7309:     }
 7310:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7311: 				    $cdom,$cnum);
 7312:     my %allcodes;
 7313:     if ($result{"type\0$old_name"} eq 'number') {
 7314: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7315:     } else {
 7316: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7317:     }
 7318:     return %allcodes;
 7319: }
 7320: 
 7321: =pod
 7322: 
 7323: =item scantron_validate_CODE
 7324: 
 7325:    Validates all scanlines in the selected file to not have any
 7326:    invalid or underspecified CODEs and that none of the codes are
 7327:    duplicated if this was requested.
 7328: 
 7329: =cut
 7330: 
 7331: sub scantron_validate_CODE {
 7332:     my ($r,$currentphase) = @_;
 7333:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7334:     if ($scantron_config{'CODElocation'} &&
 7335: 	$scantron_config{'CODEstart'} &&
 7336: 	$scantron_config{'CODElength'}) {
 7337: 	if (!defined($env{'form.scantron_CODElist'})) {
 7338: 	    &FIXME_blow_up()
 7339: 	}
 7340:     } else {
 7341: 	return (0,$currentphase+1);
 7342:     }
 7343:     
 7344:     my %usedCODEs;
 7345: 
 7346:     my %allcodes=&get_codes();
 7347: 
 7348:     my $nav_error;
 7349:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
 7350:     if ($nav_error) {
 7351:         $r->print(&navmap_errormsg());
 7352:         return(1,$currentphase);
 7353:     }
 7354: 
 7355:     my ($scanlines,$scan_data)=&scantron_getfile();
 7356:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7357: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7358: 	if ($line=~/^[\s\cz]*$/) { next; }
 7359: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7360: 						 $scan_data);
 7361: 	my $CODE=$$scan_record{'scantron.CODE'};
 7362: 	my $error=0;
 7363: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7364: 	    &scantron_get_correction($r,$i,$scan_record,
 7365: 				     \%scantron_config,
 7366: 				     $line,'incorrectCODE',\%allcodes);
 7367: 	    return(1,$currentphase);
 7368: 	}
 7369: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7370: 	    && !$$scan_record{'scantron.useCODE'}) {
 7371: 	    &scantron_get_correction($r,$i,$scan_record,
 7372: 				     \%scantron_config,
 7373: 				     $line,'incorrectCODE',\%allcodes);
 7374: 	    return(1,$currentphase);
 7375: 	}
 7376: 	if (exists($usedCODEs{$CODE}) 
 7377: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 7378: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 7379: 	    &scantron_get_correction($r,$i,$scan_record,
 7380: 				     \%scantron_config,
 7381: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 7382: 	    return(1,$currentphase);
 7383: 	}
 7384: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 7385:     }
 7386:     return (0,$currentphase+1);
 7387: }
 7388: 
 7389: =pod
 7390: 
 7391: =item scantron_validate_doublebubble
 7392: 
 7393:    Validates all scanlines in the selected file to not have any
 7394:    bubble lines with multiple bubbles marked.
 7395: 
 7396: =cut
 7397: 
 7398: sub scantron_validate_doublebubble {
 7399:     my ($r,$currentphase) = @_;
 7400:     #get student info
 7401:     my $classlist=&Apache::loncoursedata::get_classlist();
 7402:     my %idmap=&username_to_idmap($classlist);
 7403: 
 7404:     #get scantron line setup
 7405:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7406:     my ($scanlines,$scan_data)=&scantron_getfile();
 7407:     my $nav_error;
 7408:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
 7409:     if ($nav_error) {
 7410:         $r->print(&navmap_errormsg());
 7411:         return(1,$currentphase);
 7412:     }
 7413: 
 7414:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7415: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7416: 	if ($line=~/^[\s\cz]*$/) { next; }
 7417: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7418: 						 $scan_data);
 7419: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 7420: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 7421: 				 'doublebubble',
 7422: 				 $$scan_record{'scantron.doubleerror'});
 7423:     	return (1,$currentphase);
 7424:     }
 7425:     return (0,$currentphase+1);
 7426: }
 7427: 
 7428: 
 7429: sub scantron_get_maxbubble {
 7430:     my ($nav_error,$scantron_config) = @_;
 7431:     if (defined($env{'form.scantron_maxbubble'}) &&
 7432: 	$env{'form.scantron_maxbubble'}) {
 7433: 	&restore_bubble_lines();
 7434: 	return $env{'form.scantron_maxbubble'};
 7435:     }
 7436: 
 7437:     my (undef, undef, $sequence) =
 7438: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7439: 
 7440:     my $navmap=Apache::lonnavmaps::navmap->new();
 7441:     unless (ref($navmap)) {
 7442:         if (ref($nav_error)) {
 7443:             $$nav_error = 1;
 7444:         }
 7445:         return;
 7446:     }
 7447:     my $map=$navmap->getResourceByUrl($sequence);
 7448:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7449:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
 7450: 
 7451:     &Apache::lonxml::clear_problem_counter();
 7452: 
 7453:     my $uname       = $env{'user.name'};
 7454:     my $udom        = $env{'user.domain'};
 7455:     my $cid         = $env{'request.course.id'};
 7456:     my $total_lines = 0;
 7457:     %bubble_lines_per_response = ();
 7458:     %first_bubble_line         = ();
 7459:     %subdivided_bubble_lines   = ();
 7460:     %responsetype_per_response = ();
 7461: 
 7462:     my $response_number = 0;
 7463:     my $bubble_line     = 0;
 7464:     foreach my $resource (@resources) {
 7465:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom,undef,$bubbles_per_row);
 7466:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 7467: 	    foreach my $part_id (@{$parts}) {
 7468:                 my $lines;
 7469: 
 7470: 	        # TODO - make this a persistent hash not an array.
 7471: 
 7472:                 # optionresponse, matchresponse and rankresponse type items 
 7473:                 # render as separate sub-questions in exam mode.
 7474:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 7475:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 7476:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 7477:                     my ($numbub,$numshown);
 7478:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 7479:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 7480:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 7481:                         }
 7482:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 7483:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 7484:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 7485:                         }
 7486:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 7487:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 7488:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 7489:                         }
 7490:                     }
 7491:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 7492:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 7493:                     }
 7494:                     my $bubbles_per_row =
 7495:                         &bubblesheet_bubbles_per_row($scantron_config);
 7496:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
 7497:                     if (($numbub % $bubbles_per_row) != 0) {
 7498:                         $inner_bubble_lines++;
 7499:                     }
 7500:                     for (my $i=0; $i<$numshown; $i++) {
 7501:                         $subdivided_bubble_lines{$response_number} .= 
 7502:                             $inner_bubble_lines.',';
 7503:                     }
 7504:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 7505:                     $lines = $numshown * $inner_bubble_lines;
 7506:                 } else {
 7507:                     $lines = $analysis->{"$part_id.bubble_lines"};
 7508:                 }
 7509: 
 7510:                 $first_bubble_line{$response_number} = $bubble_line;
 7511: 	        $bubble_lines_per_response{$response_number} = $lines;
 7512:                 $responsetype_per_response{$response_number} = 
 7513:                     $analysis->{$part_id.'.type'};
 7514: 	        $response_number++;
 7515: 
 7516: 	        $bubble_line +=  $lines;
 7517: 	        $total_lines +=  $lines;
 7518: 	    }
 7519:         }
 7520:     }
 7521:     &Apache::lonnet::delenv('scantron.');
 7522: 
 7523:     &save_bubble_lines();
 7524:     $env{'form.scantron_maxbubble'} =
 7525: 	$total_lines;
 7526:     return $env{'form.scantron_maxbubble'};
 7527: }
 7528: 
 7529: sub bubblesheet_bubbles_per_row {
 7530:     my ($scantron_config) = @_;
 7531:     my $bubbles_per_row;
 7532:     if (ref($scantron_config) eq 'HASH') {
 7533:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
 7534:     }
 7535:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
 7536:         $bubbles_per_row = 10;
 7537:     }
 7538:     return $bubbles_per_row;
 7539: }
 7540: 
 7541: sub scantron_validate_missingbubbles {
 7542:     my ($r,$currentphase) = @_;
 7543:     #get student info
 7544:     my $classlist=&Apache::loncoursedata::get_classlist();
 7545:     my %idmap=&username_to_idmap($classlist);
 7546: 
 7547:     #get scantron line setup
 7548:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7549:     my ($scanlines,$scan_data)=&scantron_getfile();
 7550:     my $nav_error;
 7551:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 7552:     if ($nav_error) {
 7553:         return(1,$currentphase);
 7554:     }
 7555:     if (!$max_bubble) { $max_bubble=2**31; }
 7556:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7557: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7558: 	if ($line=~/^[\s\cz]*$/) { next; }
 7559: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7560: 						 $scan_data);
 7561: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 7562: 	my @to_correct;
 7563: 	
 7564: 	# Probably here's where the error is...
 7565: 
 7566: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 7567:             my $lastbubble;
 7568:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 7569:                my $question = $1;
 7570:                my $subquestion = $2;
 7571:                if (!defined($first_bubble_line{$question -1})) { next; }
 7572:                my $first = $first_bubble_line{$question-1};
 7573:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7574:                my $subcount = 1;
 7575:                while ($subcount<$subquestion) {
 7576:                    $first += $subans[$subcount-1];
 7577:                    $subcount ++;
 7578:                }
 7579:                my $count = $subans[$subquestion-1];
 7580:                $lastbubble = $first + $count;
 7581:             } else {
 7582:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
 7583:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
 7584:             }
 7585:             if ($lastbubble > $max_bubble) { next; }
 7586: 	    push(@to_correct,$missing);
 7587: 	}
 7588: 	if (@to_correct) {
 7589: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7590: 				     $line,'missingbubble',\@to_correct);
 7591: 	    return (1,$currentphase);
 7592: 	}
 7593: 
 7594:     }
 7595:     return (0,$currentphase+1);
 7596: }
 7597: 
 7598: 
 7599: sub scantron_process_students {
 7600:     my ($r,$symb) = @_;
 7601: 
 7602:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7603:     if (!$symb) {
 7604: 	return '';
 7605:     }
 7606:     my $default_form_data=&defaultFormData($symb);
 7607: 
 7608:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7609:     my $bubbles_per_row =
 7610:         &bubblesheet_bubbles_per_row(\%scantron_config);
 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,$bubbles_per_row);
 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,$bubbles_per_row);
 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,\%scantron_config); # 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:         &Apache::lonnet::remove_lock($lock);
 7686: 	return '';		# Dunno why the other returns return '' rather than just returning.
 7687:     }
 7688: 
 7689:     my %lettdig = &letter_to_digits();
 7690:     my $numletts = scalar(keys(%lettdig));
 7691: 
 7692:     while ($i<$scanlines->{'count'}) {
 7693:  	($uname,$udom)=('','');
 7694:  	$i++;
 7695:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7696:  	if ($line=~/^[\s\cz]*$/) { next; }
 7697: 	if ($started) {
 7698: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 7699: 						     'last student');
 7700: 	}
 7701: 	$started=1;
 7702:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7703:  						 $scan_data);
 7704:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 7705:  					      \%idmap,$i)) {
 7706:   	    &scantron_add_delay(\@delayqueue,$line,
 7707:  				'Unable to find a student that matches',1);
 7708:  	    next;
 7709:   	}
 7710:  	if (exists $completedstudents{$uname}) {
 7711:  	    &scantron_add_delay(\@delayqueue,$line,
 7712:  				'Student '.$uname.' has multiple sheets',2);
 7713:  	    next;
 7714:  	}
 7715:   	($uname,$udom)=split(/:/,$uname);
 7716: 
 7717:         my (%partids_by_symb,$res_error);
 7718:         foreach my $resource (@resources) {
 7719:             my $ressymb;
 7720:             if (ref($resource)) {
 7721:                 $ressymb = $resource->symb();
 7722:             } else {
 7723:                 $res_error = 1;
 7724:                 last;
 7725:             }
 7726:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 7727:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 7728:                 my ($analysis,$parts) =
 7729:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom,undef,$bubbles_per_row);
 7730:                 $partids_by_symb{$ressymb} = $parts;
 7731:             } else {
 7732:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 7733:             }
 7734:         }
 7735: 
 7736:         if ($res_error) {
 7737:             &scantron_add_delay(\@delayqueue,$line,
 7738:                                 'An error occurred while grading student '.$uname,2);
 7739:             next;
 7740:         }
 7741: 
 7742: 	&Apache::lonxml::clear_problem_counter();
 7743:   	&Apache::lonnet::appenv($scan_record);
 7744: 
 7745: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 7746: 	    &scantron_putfile($scanlines,$scan_data);
 7747: 	}
 7748: 	
 7749:         my $scancode;
 7750:         if ((exists($scan_record->{'scantron.CODE'})) &&
 7751:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 7752:             $scancode = $scan_record->{'scantron.CODE'};
 7753:         } else {
 7754:             $scancode = '';
 7755:         }
 7756: 
 7757:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7758:                                    \@resources,\%partids_by_symb,
 7759:                                    $bubbles_per_row) 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:             &Apache::lonnet::remove_lock($lock);
 7764:             return '';      # Why return ''?  Beats me.
 7765:         }
 7766: 
 7767: 	$completedstudents{$uname}={'line'=>$line};
 7768:         if ($env{'form.verifyrecord'}) {
 7769:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 7770:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 7771:             chomp($studentdata);
 7772:             $studentdata =~ s/\r$//;
 7773:             my $studentrecord = '';
 7774:             my $counter = -1;
 7775:             foreach my $resource (@resources) {
 7776:                 my $ressymb = $resource->symb();
 7777:                 ($counter,my $recording) =
 7778:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7779:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 7780:                                              \%scantron_config,\%lettdig,$numletts);
 7781:                 $studentrecord .= $recording;
 7782:             }
 7783:             if ($studentrecord ne $studentdata) {
 7784:                 &Apache::lonxml::clear_problem_counter();
 7785:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7786:                                            \@resources,\%partids_by_symb,
 7787:                                            $bubbles_per_row) 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:                     &Apache::lonnet::remove_lock($lock);
 7792:                     delete($completedstudents{$uname});
 7793:                     return '';
 7794:                 }
 7795:                 $counter = -1;
 7796:                 $studentrecord = '';
 7797:                 foreach my $resource (@resources) {
 7798:                     my $ressymb = $resource->symb();
 7799:                     ($counter,my $recording) =
 7800:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7801:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 7802:                                                  \%scantron_config,\%lettdig,$numletts);
 7803:                     $studentrecord .= $recording;
 7804:                 }
 7805:                 if ($studentrecord ne $studentdata) {
 7806:                     $r->print('<p><span class="LC_error">');
 7807:                     if ($scancode eq '') {
 7808:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
 7809:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 7810:                     } else {
 7811:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
 7812:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 7813:                     }
 7814:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 7815:                               &Apache::loncommon::start_data_table_header_row()."\n".
 7816:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 7817:                               &Apache::loncommon::end_data_table_header_row()."\n".
 7818:                               &Apache::loncommon::start_data_table_row().
 7819:                               '<td>'.&mt('Bubble Sheet').'</td>'.
 7820:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
 7821:                               &Apache::loncommon::end_data_table_row().
 7822:                               &Apache::loncommon::start_data_table_row().
 7823:                               '<td>Stored submissions</td>'.
 7824:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
 7825:                               &Apache::loncommon::end_data_table_row().
 7826:                               &Apache::loncommon::end_data_table().'</p>');
 7827:                 } else {
 7828:                     $r->print('<br /><span class="LC_warning">'.
 7829:                              &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 />'.
 7830:                              &mt("As a consequence, this user's submission history records two tries.").
 7831:                                  '</span><br />');
 7832:                 }
 7833:             }
 7834:         }
 7835:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 7836:     } continue {
 7837: 	&Apache::lonxml::clear_problem_counter();
 7838: 	&Apache::lonnet::delenv('scantron.');
 7839:     }
 7840:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 7841:     &Apache::lonnet::remove_lock($lock);
 7842: #    my $lasttime = &Time::HiRes::time()-$start;
 7843: #    $r->print("<p>took $lasttime</p>");
 7844: 
 7845:     $r->print("</form>");
 7846:     return '';
 7847: }
 7848: 
 7849: sub graders_resources_pass {
 7850:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
 7851:         $bubbles_per_row) = @_;
 7852:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 7853:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 7854:         foreach my $resource (@{$resources}) {
 7855:             my $ressymb = $resource->symb();
 7856:             my ($analysis,$parts) =
 7857:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 7858:                                           $env{'user.name'},$env{'user.domain'},1,$bubbles_per_row);
 7859:             $grader_partids_by_symb->{$ressymb} = $parts;
 7860:             if (ref($analysis) eq 'HASH') {
 7861:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7862:                     $grader_randomlists_by_symb->{$ressymb} =
 7863:                         $analysis->{'parts_withrandomlist'};
 7864:                 }
 7865:             }
 7866:         }
 7867:     }
 7868:     return;
 7869: }
 7870: 
 7871: sub grade_student_bubbles {
 7872:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row) = @_;
 7873: # Walk folder as student here to get resources in order student sees.
 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 ($bubbles_per_row ne '') {
 7887:                 $form{'bubbles_per_row'} = $bubbles_per_row;
 7888:             }
 7889:             if (ref($parts) eq 'HASH') {
 7890:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 7891:                     foreach my $part (@{$parts->{$ressymb}}) {
 7892:                         $form{'scantron_questnum_start.'.$part} =
 7893:                             1+$env{'form.scantron.first_bubble_line.'.$count};
 7894:                         $count++;
 7895:                     }
 7896:                 }
 7897:             }
 7898:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 7899:             return 'ssi_error' if ($ssi_error);
 7900:             last if (&Apache::loncommon::connection_aborted($r));
 7901:         }
 7902:     }
 7903:     return;
 7904: }
 7905: 
 7906: sub scantron_upload_scantron_data {
 7907:     my ($r,$symb)=@_;
 7908:     my $dom = $env{'request.role.domain'};
 7909:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 7910:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 7911:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 7912: 							  'domainid',
 7913: 							  'coursename',$dom);
 7914:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 7915:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
 7916:     my $default_form_data=&defaultFormData($symb);
 7917:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 7918:     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.");
 7919:     $r->print(&Apache::lonhtmlcommon::scripttag('
 7920:     function checkUpload(formname) {
 7921: 	if (formname.upfile.value == "") {
 7922: 	    alert("'.$nofile_alert.'");
 7923: 	    return false;
 7924: 	}
 7925:         if (formname.courseid.value == "") {
 7926:             alert("'.$nocourseid_alert.'");
 7927:             return false;
 7928:         }
 7929: 	formname.submit();
 7930:     }
 7931: 
 7932:     function ToSyllabus() {
 7933:         var cdom = '."'$dom'".';
 7934:         var cnum = document.rules.courseid.value;
 7935:         if (cdom == "" || cdom == null) {
 7936:             return;
 7937:         }
 7938:         if (cnum == "" || cnum == null) {
 7939:            return;
 7940:         }
 7941:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 7942:                             "height=350,width=350,scrollbars=yes,menubar=no");
 7943:         return;
 7944:     }
 7945: 
 7946: '));
 7947:     $r->print('
 7948: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
 7949: 
 7950: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 7951: '.$default_form_data.
 7952:   &Apache::lonhtmlcommon::start_pick_box().
 7953:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 7954:   '<input name="courseid" type="text" size="30" />'.$select_link.
 7955:   &Apache::lonhtmlcommon::row_closure().
 7956:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 7957:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 7958:   &Apache::lonhtmlcommon::row_closure().
 7959:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 7960:   '<input name="domainid" type="hidden" />'.$domdesc.
 7961:   &Apache::lonhtmlcommon::row_closure().
 7962:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 7963:   '<input type="file" name="upfile" size="50" />'.
 7964:   &Apache::lonhtmlcommon::row_closure(1).
 7965:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 7966: 
 7967: <input name="command" value="scantronupload_save" type="hidden" />
 7968: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 7969: </form>
 7970: ');
 7971:     return '';
 7972: }
 7973: 
 7974: 
 7975: sub scantron_upload_scantron_data_save {
 7976:     my($r,$symb)=@_;
 7977:     my $doanotherupload=
 7978: 	'<br /><form action="/adm/grades" method="post">'."\n".
 7979: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 7980: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 7981: 	'</form>'."\n";
 7982:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 7983: 	!&Apache::lonnet::allowed('usc',
 7984: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 7985: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 7986: 	unless ($symb) {
 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,$symb));
 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,$symb)=@_;
 8117:     my $default_form_data=&defaultFormData($symb);
 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: 	return;
 8128:     }
 8129:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 8130:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 8131:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 8132:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 8133:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 8134:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 8135:     $r->print('
 8136:     <p>
 8137: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
 8138: 	      '<a href="'.$orig.'">','</a>').'
 8139:     </p>
 8140:     <p>
 8141: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 8142: 	      '<a href="'.$corrected.'">','</a>').'
 8143:     </p>
 8144:     <p>
 8145: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 8146: 	      '<a href="'.$skipped.'">','</a>').'
 8147:     </p>
 8148: ');
 8149:     return '';
 8150: }
 8151: 
 8152: sub checkscantron_results {
 8153:     my ($r,$symb) = @_;
 8154:     if (!$symb) {return '';}
 8155:     my $cid = $env{'request.course.id'};
 8156:     my %lettdig = &letter_to_digits();
 8157:     my $numletts = scalar(keys(%lettdig));
 8158:     my $cnum = $env{'course.'.$cid.'.num'};
 8159:     my $cdom = $env{'course.'.$cid.'.domain'};
 8160:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8161:     my %record;
 8162:     my %scantron_config =
 8163:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 8164:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8165:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 8166:     my $classlist=&Apache::loncoursedata::get_classlist();
 8167:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 8168:     my $navmap=Apache::lonnavmaps::navmap->new();
 8169:     unless (ref($navmap)) {
 8170:         $r->print(&navmap_errormsg());
 8171:         return '';
 8172:     }
 8173:     my $map=$navmap->getResourceByUrl($sequence);
 8174:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8175:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 8176:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
 8177: 
 8178:     my ($uname,$udom);
 8179:     my (%scandata,%lastname,%bylast);
 8180:     $r->print('
 8181: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 8182: 
 8183:     my @delayqueue;
 8184:     my %completedstudents;
 8185: 
 8186:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
 8187:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
 8188:                                     'Progress of Bubblesheet Data/Submission Records Comparison',$count,
 8189:                                     'inline',undef,'checkscantron');
 8190:     my ($username,$domain,$started);
 8191:     my $nav_error;
 8192:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 8193:     if ($nav_error) {
 8194:         $r->print(&navmap_errormsg());
 8195:         return '';
 8196:     }
 8197: 
 8198:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 8199:                                           'Processing first student');
 8200:     my $start=&Time::HiRes::time();
 8201:     my $i=-1;
 8202: 
 8203:     while ($i<$scanlines->{'count'}) {
 8204:         ($username,$domain,$uname)=('','','');
 8205:         $i++;
 8206:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 8207:         if ($line=~/^[\s\cz]*$/) { next; }
 8208:         if ($started) {
 8209:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 8210:                                                      'last student');
 8211:         }
 8212:         $started=1;
 8213:         my $scan_record=
 8214:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 8215:                                                      $scan_data);
 8216:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
 8217:                                                               \%idmap,$i)) {
 8218:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8219:                                 'Unable to find a student that matches',1);
 8220:             next;
 8221:         }
 8222:         if (exists $completedstudents{$uname}) {
 8223:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8224:                                 'Student '.$uname.' has multiple sheets',2);
 8225:             next;
 8226:         }
 8227:         my $pid = $scan_record->{'scantron.ID'};
 8228:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 8229:         push(@{$bylast{$lastname{$pid}}},$pid);
 8230:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8231:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8232:         chomp($scandata{$pid});
 8233:         $scandata{$pid} =~ s/\r$//;
 8234:         ($username,$domain)=split(/:/,$uname);
 8235:         my $counter = -1;
 8236:         foreach my $resource (@resources) {
 8237:             my $parts;
 8238:             my $ressymb = $resource->symb();
 8239:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8240:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8241:                 (my $analysis,$parts) =
 8242:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain,undef,$bubbles_per_row);
 8243:             } else {
 8244:                 $parts = $grader_partids_by_symb{$ressymb};
 8245:             }
 8246:             ($counter,my $recording) =
 8247:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 8248:                                          $scandata{$pid},$parts,
 8249:                                          \%scantron_config,\%lettdig,$numletts);
 8250:             $record{$pid} .= $recording;
 8251:         }
 8252:     }
 8253:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8254:     $r->print('<br />');
 8255:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 8256:     $passed = 0;
 8257:     $failed = 0;
 8258:     $numstudents = 0;
 8259:     foreach my $last (sort(keys(%bylast))) {
 8260:         if (ref($bylast{$last}) eq 'ARRAY') {
 8261:             foreach my $pid (sort(@{$bylast{$last}})) {
 8262:                 my $showscandata = $scandata{$pid};
 8263:                 my $showrecord = $record{$pid};
 8264:                 $showscandata =~ s/\s/&nbsp;/g;
 8265:                 $showrecord =~ s/\s/&nbsp;/g;
 8266:                 if ($scandata{$pid} eq $record{$pid}) {
 8267:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 8268:                     $okstudents .= '<tr class="'.$css_class.'">'.
 8269: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 8270: '</tr>'."\n".
 8271: '<tr class="'.$css_class.'">'."\n".
 8272: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
 8273:                     $passed ++;
 8274:                 } else {
 8275:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 8276:                     $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".
 8277: '</tr>'."\n".
 8278: '<tr class="'.$css_class.'">'."\n".
 8279: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 8280: '</tr>'."\n";
 8281:                     $failed ++;
 8282:                 }
 8283:                 $numstudents ++;
 8284:             }
 8285:         }
 8286:     }
 8287:     $r->print(
 8288:         '<p>'
 8289:        .&mt('Comparison of bubblesheet data (including corrections) with corresponding submission records (most recent submission) for [_1][quant,_2,student][_3] ([quant,_4,bubblesheet line] per student).',
 8290:             '<b>',
 8291:             $numstudents,
 8292:             '</b>',
 8293:             $env{'form.scantron_maxbubble'})
 8294:        .'</p>'
 8295:     );
 8296:     $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>');
 8297:     if ($passed) {
 8298:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 8299:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8300:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8301:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8302:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8303:                  $okstudents."\n".
 8304:                  &Apache::loncommon::end_data_table().'<br />');
 8305:     }
 8306:     if ($failed) {
 8307:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 8308:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8309:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8310:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8311:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8312:                  $badstudents."\n".
 8313:                  &Apache::loncommon::end_data_table()).'<br />'.
 8314:                  &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.');  
 8315:     }
 8316:     $r->print('</form><br />');
 8317:     return;
 8318: }
 8319: 
 8320: sub verify_scantron_grading {
 8321:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 8322:         $scantron_config,$lettdig,$numletts) = @_;
 8323:     my ($record,%expected,%startpos);
 8324:     return ($counter,$record) if (!ref($resource));
 8325:     return ($counter,$record) if (!$resource->is_problem());
 8326:     my $symb = $resource->symb();
 8327:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 8328:     foreach my $part_id (@{$partids}) {
 8329:         $counter ++;
 8330:         $expected{$part_id} = 0;
 8331:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
 8332:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
 8333:             foreach my $item (@sub_lines) {
 8334:                 $expected{$part_id} += $item;
 8335:             }
 8336:         } else {
 8337:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
 8338:         }
 8339:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 8340:     }
 8341:     if ($symb) {
 8342:         my %recorded;
 8343:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 8344:         if ($returnhash{'version'}) {
 8345:             my %lasthash=();
 8346:             my $version;
 8347:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 8348:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 8349:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 8350:                 }
 8351:             }
 8352:             foreach my $key (keys(%lasthash)) {
 8353:                 if ($key =~ /\.scantron$/) {
 8354:                     my $value = &unescape($lasthash{$key});
 8355:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 8356:                     if ($value eq '') {
 8357:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 8358:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 8359:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8360:                             }
 8361:                         }
 8362:                     } else {
 8363:                         my @tocheck;
 8364:                         my @items = split(//,$value);
 8365:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 8366:                             ($scantron_config->{'Qon'} eq 'number')) {
 8367:                             if (@items < $expected{$part_id}) {
 8368:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 8369:                                 my @singles = split(//,$fragment);
 8370:                                 foreach my $pos (@singles) {
 8371:                                     if ($pos eq ' ') {
 8372:                                         push(@tocheck,$pos);
 8373:                                     } else {
 8374:                                         my $next = shift(@items);
 8375:                                         push(@tocheck,$next);
 8376:                                     }
 8377:                                 }
 8378:                             } else {
 8379:                                 @tocheck = @items;
 8380:                             }
 8381:                             foreach my $letter (@tocheck) {
 8382:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 8383:                                     if ($letter !~ /^[A-J]$/) {
 8384:                                         $letter = $scantron_config->{'Qoff'};
 8385:                                     }
 8386:                                     $recorded{$part_id} .= $letter;
 8387:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 8388:                                     my $digit;
 8389:                                     if ($letter !~ /^[A-J]$/) {
 8390:                                         $digit = $scantron_config->{'Qoff'};
 8391:                                     } else {
 8392:                                         $digit = $lettdig->{$letter};
 8393:                                     }
 8394:                                     $recorded{$part_id} .= $digit;
 8395:                                 }
 8396:                             }
 8397:                         } else {
 8398:                             @tocheck = @items;
 8399:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 8400:                                 my $curr_sub = shift(@tocheck);
 8401:                                 my $digit;
 8402:                                 if ($curr_sub =~ /^[A-J]$/) {
 8403:                                     $digit = $lettdig->{$curr_sub}-1;
 8404:                                 }
 8405:                                 if ($curr_sub eq 'J') {
 8406:                                     $digit += scalar($numletts);
 8407:                                 }
 8408:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8409:                                     if ($j == $digit) {
 8410:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 8411:                                     } else {
 8412:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8413:                                     }
 8414:                                 }
 8415:                             }
 8416:                         }
 8417:                     }
 8418:                 }
 8419:             }
 8420:         }
 8421:         foreach my $part_id (@{$partids}) {
 8422:             if ($recorded{$part_id} eq '') {
 8423:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 8424:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8425:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8426:                     }
 8427:                 }
 8428:             }
 8429:             $record .= $recorded{$part_id};
 8430:         }
 8431:     }
 8432:     return ($counter,$record);
 8433: }
 8434: 
 8435: sub letter_to_digits { 
 8436:     my %lettdig = (
 8437:                     A => 1,
 8438:                     B => 2,
 8439:                     C => 3,
 8440:                     D => 4,
 8441:                     E => 5,
 8442:                     F => 6,
 8443:                     G => 7,
 8444:                     H => 8,
 8445:                     I => 9,
 8446:                     J => 0,
 8447:                   );
 8448:     return %lettdig;
 8449: }
 8450: 
 8451: 
 8452: #-------- end of section for handling grading scantron forms -------
 8453: #
 8454: #-------------------------------------------------------------------
 8455: 
 8456: #-------------------------- Menu interface -------------------------
 8457: #
 8458: #--- Href with symb and command ---
 8459: 
 8460: sub href_symb_cmd {
 8461:     my ($symb,$cmd)=@_;
 8462:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&command='.$cmd;
 8463: }
 8464: 
 8465: sub grading_menu {
 8466:     my ($request,$symb) = @_;
 8467:     if (!$symb) {return '';}
 8468: 
 8469:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 8470:                   'command'=>'individual');
 8471:     
 8472:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8473: 
 8474:     $fields{'command'}='ungraded';
 8475:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8476: 
 8477:     $fields{'command'}='table';
 8478:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8479: 
 8480:     $fields{'command'}='all_for_one';
 8481:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8482: 
 8483:     $fields{'command'}='downloadfilesselect';
 8484:     my $url1e=&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 => 'grade_students.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 => 'ungrade_sub.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 => 'grading_table.png',
 8517:                                 linktitle => 'Grade current resource for all students.'
 8518:                         },
 8519:                         {       linktext => 'Grade page/folder for one student',
 8520:                                 url => $url1d,
 8521:                                 permission => 'F',
 8522:                                 icon => 'grade_PageFolder.png',
 8523:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
 8524:                         },
 8525:                         {       linktext => 'Download submissions',
 8526:                                 url => $url1e,
 8527:                                 permission => 'F',
 8528:                                 icon => 'download_sub.png',
 8529:                                 linktitle => 'Download all students submissions.'
 8530:                         }]},
 8531:                          { categorytitle=>'Automated Grading',
 8532:                items =>[
 8533: 
 8534:                 	    {	linktext => 'Upload Scores',
 8535:                     		url => $url2,
 8536:                     		permission => 'F',
 8537:                     		icon => 'uploadscores.png',
 8538:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 8539:                 	    },
 8540:                 	    {	linktext => 'Process Clicker',
 8541:                     		url => $url3,
 8542:                     		permission => 'F',
 8543:                     		icon => 'addClickerInfoFile.png',
 8544:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 8545:                 	    },
 8546:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
 8547:                     		url => $url4,
 8548:                     		permission => 'F',
 8549:                     		icon => 'bubblesheet.png',
 8550:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
 8551:                 	    },
 8552:                             {   linktext => 'Verify Receipt Number',
 8553:                                 url => $url5,
 8554:                                 permission => 'F',
 8555:                                 icon => 'receipt_number.png',
 8556:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
 8557:                             }
 8558: 
 8559:                     ]
 8560:             });
 8561: 
 8562:     # Create the menu
 8563:     my $Str;
 8564:     $Str .= '<form method="post" action="" name="gradingMenu">';
 8565:     $Str .= '<input type="hidden" name="command" value="" />'.
 8566:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8567: 
 8568:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
 8569:     return $Str;    
 8570: }
 8571: 
 8572: 
 8573: sub ungraded {
 8574:     my ($request)=@_;
 8575:     &submit_options($request);
 8576: }
 8577: 
 8578: sub submit_options_sequence {
 8579:     my ($request,$symb) = @_;
 8580:     if (!$symb) {return '';}
 8581:     &commonJSfunctions($request);
 8582:     my $result;
 8583: 
 8584:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8585:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8586:     $result.=&selectfield(0).
 8587:             '<input type="hidden" name="command" value="pickStudentPage" />
 8588:             <div>
 8589:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 8590:             </div>
 8591:         </div>
 8592:   </form>';
 8593:     return $result;
 8594: }
 8595: 
 8596: sub submit_options_table {
 8597:     my ($request,$symb) = @_;
 8598:     if (!$symb) {return '';}
 8599:     &commonJSfunctions($request);
 8600:     my $result;
 8601: 
 8602:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8603:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8604: 
 8605:     $result.=&selectfield(0).
 8606:             '<input type="hidden" name="command" value="viewgrades" />
 8607:             <div>
 8608:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 8609:             </div>
 8610:         </div>
 8611:   </form>';
 8612:     return $result;
 8613: }
 8614: 
 8615: sub submit_options_download {
 8616:     my ($request,$symb) = @_;
 8617:     if (!$symb) {return '';}
 8618: 
 8619:     &commonJSfunctions($request);
 8620: 
 8621:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8622:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8623:     $result.='
 8624: <h2>
 8625:   '.&mt('Select Students for Which to Download Submissions').'
 8626: </h2>'.&selectfield(1).'
 8627:                 <input type="hidden" name="command" value="downloadfileslink" /> 
 8628:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 8629:             </div>
 8630:           </div>
 8631: 
 8632: 
 8633:   </form>';
 8634:     return $result;
 8635: }
 8636: 
 8637: #--- Displays the submissions first page -------
 8638: sub submit_options {
 8639:     my ($request,$symb) = @_;
 8640:     if (!$symb) {return '';}
 8641: 
 8642:     &commonJSfunctions($request);
 8643:     my $result;
 8644: 
 8645:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8646: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8647:     $result.=&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:     return $result;
 8656: }
 8657: 
 8658: sub selectfield {
 8659:    my ($full)=@_;
 8660:    my %options = 
 8661:           (&Apache::lonlocal::texthash(
 8662:              'yes'       => 'with submissions',
 8663:              'queued'    => 'in grading queue',
 8664:              'graded'    => 'with ungraded submissions',
 8665:              'incorrect' => 'with incorrect submissions',
 8666:              'all'       => 'with any status'),
 8667:              'select_form_order' => ['yes','queued','graded','incorrect','all']);
 8668:    my $result='<div class="LC_columnSection">
 8669:   
 8670:     <fieldset>
 8671:       <legend>
 8672:        '.&mt('Sections').'
 8673:       </legend>
 8674:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
 8675:     </fieldset>
 8676:   
 8677:     <fieldset>
 8678:       <legend>
 8679:         '.&mt('Groups').'
 8680:       </legend>
 8681:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 8682:     </fieldset>
 8683:   
 8684:     <fieldset>
 8685:       <legend>
 8686:         '.&mt('Access Status').'
 8687:       </legend>
 8688:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
 8689:     </fieldset>';
 8690:     if ($full) {
 8691:        $result.='
 8692:     <fieldset>
 8693:       <legend>
 8694:         '.&mt('Submission Status').'
 8695:       </legend>'.
 8696:        &Apache::loncommon::select_form('all','submitonly',\%options).
 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,$symb)=@_;
 8788:     if (!$symb) {return '';}
 8789:     my $result=&checkforfile_js();
 8790:     $result.=&Apache::loncommon::start_data_table().
 8791:              &Apache::loncommon::start_data_table_header_row().
 8792:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
 8793:              &Apache::loncommon::end_data_table_header_row().
 8794:              &Apache::loncommon::start_data_table_row()."<td>\n";
 8795: # Attempt to restore parameters from last session, set defaults if not present
 8796:     my %Saveable_Parameters=&clicker_grading_parameters();
 8797:     &Apache::loncommon::restore_course_settings('grades_clicker',
 8798:                                                  \%Saveable_Parameters);
 8799:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 8800:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 8801:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 8802:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 8803: 
 8804:     my %checked;
 8805:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 8806:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 8807:           $checked{$gradingmechanism}=' checked="checked"';
 8808:        }
 8809:     }
 8810: 
 8811:     my $upload=&mt("Evaluate File");
 8812:     my $type=&mt("Type");
 8813:     my $attendance=&mt("Award points just for participation");
 8814:     my $personnel=&mt("Correctness determined from response by course personnel");
 8815:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 8816:     my $given=&mt("Correctness determined from given list of answers").' '.
 8817:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 8818:     my $pcorrect=&mt("Percentage points for correct solution");
 8819:     my $pincorrect=&mt("Percentage points for incorrect solution");
 8820:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 8821: 						   {'iclicker' => 'i>clicker',
 8822:                                                     'interwrite' => 'interwrite PRS'});
 8823:     $symb = &Apache::lonenc::check_encrypt($symb);
 8824:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
 8825: function sanitycheck() {
 8826: // Accept only integer percentages
 8827:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 8828:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 8829: // Find out grading choice
 8830:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8831:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 8832:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 8833:       }
 8834:    }
 8835: // By default, new choice equals user selection
 8836:    newgradingchoice=gradingchoice;
 8837: // Not good to give more points for false answers than correct ones
 8838:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 8839:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 8840:    }
 8841: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 8842:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 8843:       document.forms.gradesupload.pcorrect.value=100;
 8844:       document.forms.gradesupload.pincorrect.value=100;
 8845:    }
 8846: // If the values are different, cannot be attendance only
 8847:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 8848:        (gradingchoice=='attendance')) {
 8849:        newgradingchoice='personnel';
 8850:    }
 8851: // Change grading choice to new one
 8852:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8853:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 8854:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 8855:       } else {
 8856:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 8857:       }
 8858:    }
 8859: // Remember the old state
 8860:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 8861: }
 8862: ENDUPFORM
 8863:     $result.= <<ENDUPFORM;
 8864: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 8865: <input type="hidden" name="symb" value="$symb" />
 8866: <input type="hidden" name="command" value="processclickerfile" />
 8867: <input type="file" name="upfile" size="50" />
 8868: <br /><label>$type: $selectform</label>
 8869: ENDUPFORM
 8870:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
 8871:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
 8872:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
 8873: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
 8874: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
 8875: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 8876: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
 8877: <br />&nbsp;&nbsp;&nbsp;
 8878: <input type="text" name="givenanswer" size="50" />
 8879: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 8880: ENDGRADINGFORM
 8881:          $result.='</td>'.&Apache::loncommon::end_data_table_row().
 8882:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
 8883:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
 8884: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
 8885: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 8886: </form>'
 8887: ENDPERCFORM
 8888:     $result.='</td>'.
 8889:              &Apache::loncommon::end_data_table_row().
 8890:              &Apache::loncommon::end_data_table();
 8891:     return $result;
 8892: }
 8893: 
 8894: sub process_clicker_file {
 8895:     my ($r,$symb)=@_;
 8896:     if (!$symb) {return '';}
 8897: 
 8898:     my %Saveable_Parameters=&clicker_grading_parameters();
 8899:     &Apache::loncommon::store_course_settings('grades_clicker',
 8900:                                               \%Saveable_Parameters);
 8901:     my $result='';
 8902:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 8903: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 8904: 	return $result;
 8905:     }
 8906:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 8907:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 8908:         return $result;
 8909:     }
 8910:     my $foundgiven=0;
 8911:     if ($env{'form.gradingmechanism'} eq 'given') {
 8912:         $env{'form.givenanswer'}=~s/^\s*//gs;
 8913:         $env{'form.givenanswer'}=~s/\s*$//gs;
 8914:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
 8915:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 8916:         my @answers=split(/\,/,$env{'form.givenanswer'});
 8917:         $foundgiven=$#answers+1;
 8918:     }
 8919:     my %clicker_ids=&gather_clicker_ids();
 8920:     my %correct_ids;
 8921:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 8922: 	%correct_ids=&gather_adv_clicker_ids();
 8923:     }
 8924:     if ($env{'form.gradingmechanism'} eq 'specific') {
 8925: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 8926: 	   $correct_id=~tr/a-z/A-Z/;
 8927: 	   $correct_id=~s/\s//gs;
 8928: 	   $correct_id=~s/^[\#0]+//;
 8929:            $correct_id=~s/[\-\:]//g;
 8930:            if ($correct_id) {
 8931: 	      $correct_ids{$correct_id}='specified';
 8932:            }
 8933:         }
 8934:     }
 8935:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 8936: 	$result.=&mt('Score based on attendance only');
 8937:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
 8938:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
 8939:     } else {
 8940: 	my $number=0;
 8941: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 8942: 	foreach my $id (sort(keys(%correct_ids))) {
 8943: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 8944: 	    if ($correct_ids{$id} eq 'specified') {
 8945: 		$result.=&mt('specified');
 8946: 	    } else {
 8947: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 8948: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 8949: 	    }
 8950: 	    $number++;
 8951: 	}
 8952:         $result.="</p>\n";
 8953: 	if ($number==0) {
 8954: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
 8955: 	    return $result;
 8956: 	}
 8957:     }
 8958:     if (length($env{'form.upfile'}) < 2) {
 8959:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
 8960: 		     '<span class="LC_error">',
 8961: 		     '</span>',
 8962: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
 8963:         return $result;
 8964:     }
 8965: 
 8966: # Were able to get all the info needed, now analyze the file
 8967: 
 8968:     $result.=&Apache::loncommon::studentbrowser_javascript();
 8969:     $symb = &Apache::lonenc::check_encrypt($symb);
 8970:     $result.=&Apache::loncommon::start_data_table().
 8971:              &Apache::loncommon::start_data_table_header_row().
 8972:              '<th>'.&mt('Evaluate clicker file').'</th>'.
 8973:              &Apache::loncommon::end_data_table_header_row().
 8974:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
 8975: <td>
 8976: <form method="post" action="/adm/grades" name="clickeranalysis">
 8977: <input type="hidden" name="symb" value="$symb" />
 8978: <input type="hidden" name="command" value="assignclickergrades" />
 8979: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 8980: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 8981: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 8982: ENDHEADER
 8983:     if ($env{'form.gradingmechanism'} eq 'given') {
 8984:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
 8985:     } 
 8986:     my %responses;
 8987:     my @questiontitles;
 8988:     my $errormsg='';
 8989:     my $number=0;
 8990:     if ($env{'form.upfiletype'} eq 'iclicker') {
 8991: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 8992:     }
 8993:     if ($env{'form.upfiletype'} eq 'interwrite') {
 8994:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 8995:     }
 8996:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 8997:              '<input type="hidden" name="number" value="'.$number.'" />'.
 8998:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 8999:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 9000:              '<br />';
 9001:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
 9002:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
 9003:        return $result;
 9004:     } 
 9005: # Remember Question Titles
 9006: # FIXME: Possibly need delimiter other than ":"
 9007:     for (my $i=0;$i<$number;$i++) {
 9008:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 9009:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 9010:     }
 9011:     my $correct_count=0;
 9012:     my $student_count=0;
 9013:     my $unknown_count=0;
 9014: # Match answers with usernames
 9015: # FIXME: Possibly need delimiter other than ":"
 9016:     foreach my $id (keys(%responses)) {
 9017:        if ($correct_ids{$id}) {
 9018:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 9019:           $correct_count++;
 9020:        } elsif ($clicker_ids{$id}) {
 9021:           if ($clicker_ids{$id}=~/\,/) {
 9022: # More than one user with the same clicker!
 9023:              $result.="</td>".&Apache::loncommon::end_data_table_row().
 9024:                            &Apache::loncommon::start_data_table_row()."<td>".
 9025:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 9026:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9027:                            "<select name='multi".$id."'>";
 9028:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 9029:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 9030:              }
 9031:              $result.='</select>';
 9032:              $unknown_count++;
 9033:           } else {
 9034: # Good: found one and only one user with the right clicker
 9035:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 9036:              $student_count++;
 9037:           }
 9038:        } else {
 9039:           $result.="</td>".&Apache::loncommon::end_data_table_row().
 9040:                            &Apache::loncommon::start_data_table_row()."<td>".
 9041:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 9042:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9043:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 9044:                    "\n".&mt("Domain").": ".
 9045:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 9046:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
 9047:           $unknown_count++;
 9048:        }
 9049:     }
 9050:     $result.='<hr />'.
 9051:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 9052:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
 9053:        if ($correct_count==0) {
 9054:           $errormsg.="Found no correct answers answers for grading!";
 9055:        } elsif ($correct_count>1) {
 9056:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 9057:        }
 9058:     }
 9059:     if ($number<1) {
 9060:        $errormsg.="Found no questions.";
 9061:     }
 9062:     if ($errormsg) {
 9063:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 9064:     } else {
 9065:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 9066:     }
 9067:     $result.='</form></td>'.
 9068:              &Apache::loncommon::end_data_table_row().
 9069:              &Apache::loncommon::end_data_table();
 9070:     return $result;
 9071: }
 9072: 
 9073: sub iclicker_eval {
 9074:     my ($questiontitles,$responses)=@_;
 9075:     my $number=0;
 9076:     my $errormsg='';
 9077:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9078:         my %components=&Apache::loncommon::record_sep($line);
 9079:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9080: 	if ($entries[0] eq 'Question') {
 9081: 	    for (my $i=3;$i<$#entries;$i+=6) {
 9082: 		$$questiontitles[$number]=$entries[$i];
 9083: 		$number++;
 9084: 	    }
 9085: 	}
 9086: 	if ($entries[0]=~/^\#/) {
 9087: 	    my $id=$entries[0];
 9088: 	    my @idresponses;
 9089: 	    $id=~s/^[\#0]+//;
 9090: 	    for (my $i=0;$i<$number;$i++) {
 9091: 		my $idx=3+$i*6;
 9092:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
 9093: 		push(@idresponses,$entries[$idx]);
 9094: 	    }
 9095: 	    $$responses{$id}=join(',',@idresponses);
 9096: 	}
 9097:     }
 9098:     return ($errormsg,$number);
 9099: }
 9100: 
 9101: sub interwrite_eval {
 9102:     my ($questiontitles,$responses)=@_;
 9103:     my $number=0;
 9104:     my $errormsg='';
 9105:     my $skipline=1;
 9106:     my $questionnumber=0;
 9107:     my %idresponses=();
 9108:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9109:         my %components=&Apache::loncommon::record_sep($line);
 9110:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9111:         if ($entries[1] eq 'Time') { $skipline=0; next; }
 9112:         if ($entries[1] eq 'Response') { $skipline=1; }
 9113:         next if $skipline;
 9114:         if ($entries[0]!=$questionnumber) {
 9115:            $questionnumber=$entries[0];
 9116:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
 9117:            $number++;
 9118:         }
 9119:         my $id=$entries[4];
 9120:         $id=~s/^[\#0]+//;
 9121:         $id=~s/^v\d*\://i;
 9122:         $id=~s/[\-\:]//g;
 9123:         $idresponses{$id}[$number]=$entries[6];
 9124:     }
 9125:     foreach my $id (keys(%idresponses)) {
 9126:        $$responses{$id}=join(',',@{$idresponses{$id}});
 9127:        $$responses{$id}=~s/^\s*\,//;
 9128:     }
 9129:     return ($errormsg,$number);
 9130: }
 9131: 
 9132: sub assign_clicker_grades {
 9133:     my ($r,$symb)=@_;
 9134:     if (!$symb) {return '';}
 9135: # See which part we are saving to
 9136:     my $res_error;
 9137:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 9138:     if ($res_error) {
 9139:         return &navmap_errormsg();
 9140:     }
 9141: # FIXME: This should probably look for the first handgradeable part
 9142:     my $part=$$partlist[0];
 9143: # Start screen output
 9144:     my $result=&Apache::loncommon::start_data_table().
 9145:              &Apache::loncommon::start_data_table_header_row().
 9146:              '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
 9147:              &Apache::loncommon::end_data_table_header_row().
 9148:              &Apache::loncommon::start_data_table_row().'<td>';
 9149: # Get correct result
 9150: # FIXME: Possibly need delimiter other than ":"
 9151:     my @correct=();
 9152:     my $gradingmechanism=$env{'form.gradingmechanism'};
 9153:     my $number=$env{'form.number'};
 9154:     if ($gradingmechanism ne 'attendance') {
 9155:        foreach my $key (keys(%env)) {
 9156:           if ($key=~/^form\.correct\:/) {
 9157:              my @input=split(/\,/,$env{$key});
 9158:              for (my $i=0;$i<=$#input;$i++) {
 9159:                  if (($correct[$i]) && ($input[$i]) &&
 9160:                      ($correct[$i] ne $input[$i])) {
 9161:                     $result.='<br /><span class="LC_warning">'.
 9162:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
 9163:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
 9164:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
 9165:                     $correct[$i]=$input[$i];
 9166:                  }
 9167:              }
 9168:           }
 9169:        }
 9170:        for (my $i=0;$i<$number;$i++) {
 9171:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
 9172:              $result.='<br /><span class="LC_error">'.
 9173:                       &mt('No correct result given for question "[_1]"!',
 9174:                           $env{'form.question:'.$i}).'</span>';
 9175:           }
 9176:        }
 9177:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
 9178:     }
 9179: # Start grading
 9180:     my $pcorrect=$env{'form.pcorrect'};
 9181:     my $pincorrect=$env{'form.pincorrect'};
 9182:     my $storecount=0;
 9183:     my %users=();
 9184:     foreach my $key (keys(%env)) {
 9185:        my $user='';
 9186:        if ($key=~/^form\.student\:(.*)$/) {
 9187:           $user=$1;
 9188:        }
 9189:        if ($key=~/^form\.unknown\:(.*)$/) {
 9190:           my $id=$1;
 9191:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
 9192:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
 9193:           } elsif ($env{'form.multi'.$id}) {
 9194:              $user=$env{'form.multi'.$id};
 9195:           }
 9196:        }
 9197:        if ($user) {
 9198:           if ($users{$user}) {
 9199:              $result.='<br /><span class="LC_warning">'.
 9200:                       &mt("More than one entry found for <tt>[_1]</tt>!",$user).
 9201:                       '</span><br />';
 9202:           }
 9203:           $users{$user}=1; 
 9204:           my @answer=split(/\,/,$env{$key});
 9205:           my $sum=0;
 9206:           my $realnumber=$number;
 9207:           for (my $i=0;$i<$number;$i++) {
 9208:              if  ($correct[$i] eq '-') {
 9209:                 $realnumber--;
 9210:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/))  {
 9211:                 if ($gradingmechanism eq 'attendance') {
 9212:                    $sum+=$pcorrect;
 9213:                 } elsif ($correct[$i] eq '*') {
 9214:                    $sum+=$pcorrect;
 9215:                 } else {
 9216: # We actually grade if correct or not
 9217:                    my $increment=$pincorrect;
 9218: # Special case: numerical answer "0"
 9219:                    if ($correct[$i] eq '0') {
 9220:                       if ($answer[$i]=~/^[0\.]+$/) {
 9221:                          $increment=$pcorrect;
 9222:                       }
 9223: # General numerical answer, both evaluate to something non-zero
 9224:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
 9225:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
 9226:                          $increment=$pcorrect;
 9227:                       }
 9228: # Must be just alphanumeric
 9229:                    } elsif ($answer[$i] eq $correct[$i]) {
 9230:                       $increment=$pcorrect;
 9231:                    }
 9232:                    $sum+=$increment;
 9233:                 }
 9234:              }
 9235:           }
 9236:           my $ave=$sum/(100*$realnumber);
 9237: # Store
 9238:           my ($username,$domain)=split(/\:/,$user);
 9239:           my %grades=();
 9240:           $grades{"resource.$part.solved"}='correct_by_override';
 9241:           $grades{"resource.$part.awarded"}=$ave;
 9242:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 9243:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
 9244:                                                  $env{'request.course.id'},
 9245:                                                  $domain,$username);
 9246:           if ($returncode ne 'ok') {
 9247:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
 9248:           } else {
 9249:              $storecount++;
 9250:           }
 9251:        }
 9252:     }
 9253: # We are done
 9254:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
 9255:              '</td>'.
 9256:              &Apache::loncommon::end_data_table_row().
 9257:              &Apache::loncommon::end_data_table();
 9258:     return $result;
 9259: }
 9260: 
 9261: sub navmap_errormsg {
 9262:     return '<div class="LC_error">'.
 9263:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
 9264:            &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>').
 9265:            '</div>';
 9266: }
 9267: 
 9268: sub startpage {
 9269:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag) = @_;
 9270:     unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
 9271:     $r->print(&Apache::loncommon::start_page('Grading',undef,
 9272:                                           {'bread_crumbs' => $crumbs}));
 9273:     &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
 9274:     unless ($nodisplayflag) {
 9275:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag));
 9276:     }
 9277: }
 9278: 
 9279: sub select_problem {
 9280:     my ($r)=@_;
 9281:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
 9282:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1));
 9283:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
 9284:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
 9285: }
 9286: 
 9287: sub handler {
 9288:     my $request=$_[0];
 9289:     &reset_caches();
 9290:     if ($request->header_only) {
 9291:         &Apache::loncommon::content_type($request,'text/html');
 9292:         $request->send_http_header;
 9293:         return OK;
 9294:     }
 9295:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
 9296: 
 9297:     &init_perm();
 9298:     if (!$env{'request.course.id'}) {
 9299:         # Not in a course.
 9300:         $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
 9301:         return HTTP_NOT_ACCEPTABLE;
 9302:     } elsif (!%perm) {
 9303:         $request->internal_redirect('/adm/quickgrades');
 9304:     }
 9305:     &Apache::loncommon::content_type($request,'text/html');
 9306:     $request->send_http_header;
 9307: 
 9308: 
 9309: # see what command we need to execute
 9310: 
 9311:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
 9312:     my $command=$commands[0];
 9313: 
 9314:     if ($#commands > 0) {
 9315: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
 9316:     }
 9317: 
 9318: # see what the symb is
 9319: 
 9320:     my $symb=$env{'form.symb'};
 9321:     unless ($symb) {
 9322:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
 9323:        $symb=&Apache::lonnet::symbread($url);
 9324:     }
 9325:     &Apache::lonenc::check_decrypt(\$symb);
 9326: 
 9327:     $ssi_error = 0;
 9328:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
 9329: #
 9330: # Not called from a resource, but inside a course
 9331: #    
 9332:         &startpage($request,undef,[],1,1);
 9333:         &select_problem($request);
 9334:     } else {
 9335: 	if ($command eq 'submission' && $perm{'vgr'}) {
 9336:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}]);
 9337: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
 9338: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
 9339:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
 9340:                                        {href=>'',text=>'Select student'}],1,1);
 9341: 	    &pickStudentPage($request,$symb);
 9342: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
 9343:             &startpage($request,$symb,
 9344:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
 9345:                                        {href=>'',text=>'Select student'},
 9346:                                        {href=>'',text=>'Grade student'}],1,1);
 9347: 	    &displayPage($request,$symb);
 9348: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
 9349:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
 9350:                                        {href=>'',text=>'Select student'},
 9351:                                        {href=>'',text=>'Grade student'},
 9352:                                        {href=>'',text=>'Store grades'}],1,1);
 9353: 	    &updateGradeByPage($request,$symb);
 9354: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
 9355:             &startpage($request,$symb,[{href=>'',text=>'...'},
 9356:                                        {href=>'',text=>'Modify grades'}]);
 9357: 	    &processGroup($request,$symb);
 9358: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
 9359:             &startpage($request,$symb);
 9360: 	    $request->print(&grading_menu($request,$symb));
 9361: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
 9362:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
 9363: 	    $request->print(&submit_options($request,$symb));
 9364:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
 9365:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
 9366:             $request->print(&listStudents($request,$symb,'graded'));
 9367:         } elsif ($command eq 'table' && $perm{'vgr'}) {
 9368:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
 9369:             $request->print(&submit_options_table($request,$symb));
 9370:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
 9371:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
 9372:             $request->print(&submit_options_sequence($request,$symb));
 9373: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
 9374:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
 9375: 	    $request->print(&viewgrades($request,$symb));
 9376: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
 9377:             &startpage($request,$symb,[{href=>'',text=>'...'},
 9378:                                        {href=>'',text=>'Store grades'}]);
 9379: 	    $request->print(&processHandGrade($request,$symb));
 9380: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
 9381:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
 9382:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
 9383:                                                                              text=>"Modify grades"},
 9384:                                        {href=>'', text=>"Store grades"}]);
 9385: 	    $request->print(&editgrades($request,$symb));
 9386:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
 9387:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
 9388:             $request->print(&initialverifyreceipt($request,$symb));
 9389: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
 9390:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
 9391:                                        {href=>'',text=>'Verification Result'}]);
 9392: 	    $request->print(&verifyreceipt($request,$symb));
 9393:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
 9394:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
 9395:             $request->print(&process_clicker($request,$symb));
 9396:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
 9397:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
 9398:                                        {href=>'', text=>'Process clicker file'}]);
 9399:             $request->print(&process_clicker_file($request,$symb));
 9400:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
 9401:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
 9402:                                        {href=>'', text=>'Process clicker file'},
 9403:                                        {href=>'', text=>'Store grades'}]);
 9404:             $request->print(&assign_clicker_grades($request,$symb));
 9405: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
 9406:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
 9407: 	    $request->print(&upcsvScores_form($request,$symb));
 9408: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
 9409:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
 9410: 	    $request->print(&csvupload($request,$symb));
 9411: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
 9412:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
 9413: 	    $request->print(&csvuploadmap($request,$symb));
 9414: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
 9415: 	    if ($env{'form.associate'} ne 'Reverse Association') {
 9416:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
 9417: 		$request->print(&csvuploadoptions($request,$symb));
 9418: 	    } else {
 9419: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
 9420: 		    $env{'form.upfile_associate'} = 'reverse';
 9421: 		} else {
 9422: 		    $env{'form.upfile_associate'} = 'forward';
 9423: 		}
 9424:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
 9425: 		$request->print(&csvuploadmap($request,$symb));
 9426: 	    }
 9427: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
 9428:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
 9429: 	    $request->print(&csvuploadassign($request,$symb));
 9430: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
 9431:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9432: 	    $request->print(&scantron_selectphase($request,undef,$symb));
 9433:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
 9434:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9435:  	    $request->print(&scantron_do_warning($request,$symb));
 9436: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
 9437:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9438: 	    $request->print(&scantron_validate_file($request,$symb));
 9439: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
 9440:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9441: 	    $request->print(&scantron_process_students($request,$symb));
 9442:  	} elsif ($command eq 'scantronupload' && 
 9443:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9444: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9445:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9446:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
 9447:  	} elsif ($command eq 'scantronupload_save' &&
 9448:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9449: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9450:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9451:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
 9452:  	} elsif ($command eq 'scantron_download' &&
 9453: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 9454:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9455:  	    $request->print(&scantron_download_scantron_data($request,$symb));
 9456:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
 9457:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9458:             $request->print(&checkscantron_results($request,$symb));
 9459:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
 9460:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
 9461:             $request->print(&submit_options_download($request,$symb));
 9462:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
 9463:             &startpage($request,$symb,
 9464:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
 9465:     {href=>'', text=>'Download submissions'}]);
 9466:             &submit_download_link($request,$symb);
 9467: 	} elsif ($command) {
 9468:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
 9469: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
 9470: 	}
 9471:     }
 9472:     if ($ssi_error) {
 9473: 	&ssi_print_error($request);
 9474:     }
 9475:     &Apache::lonquickgrades::endGradeScreen($request);
 9476:     $request->print(&Apache::loncommon::end_page());
 9477:     &reset_caches();
 9478:     return OK;
 9479: }
 9480: 
 9481: 1;
 9482: 
 9483: __END__;
 9484: 
 9485: 
 9486: =head1 NAME
 9487: 
 9488: Apache::grades
 9489: 
 9490: =head1 SYNOPSIS
 9491: 
 9492: Handles the viewing of grades.
 9493: 
 9494: This is part of the LearningOnline Network with CAPA project
 9495: described at http://www.lon-capa.org.
 9496: 
 9497: =head1 OVERVIEW
 9498: 
 9499: Do an ssi with retries:
 9500: While I'd love to factor out this with the vesrion in lonprintout,
 9501: 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
 9502: I'm not quite ready to invent (e.g. an ssi_with_retry object).
 9503: 
 9504: At least the logic that drives this has been pulled out into loncommon.
 9505: 
 9506: 
 9507: 
 9508: ssi_with_retries - Does the server side include of a resource.
 9509:                      if the ssi call returns an error we'll retry it up to
 9510:                      the number of times requested by the caller.
 9511:                      If we still have a proble, no text is appended to the
 9512:                      output and we set some global variables.
 9513:                      to indicate to the caller an SSI error occurred.  
 9514:                      All of this is supposed to deal with the issues described
 9515:                      in LonCAPA BZ 5631 see:
 9516:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
 9517:                      by informing the user that this happened.
 9518: 
 9519: Parameters:
 9520:   resource   - The resource to include.  This is passed directly, without
 9521:                interpretation to lonnet::ssi.
 9522:   form       - The form hash parameters that guide the interpretation of the resource
 9523:                
 9524:   retries    - Number of retries allowed before giving up completely.
 9525: Returns:
 9526:   On success, returns the rendered resource identified by the resource parameter.
 9527: Side Effects:
 9528:   The following global variables can be set:
 9529:    ssi_error                - If an unrecoverable error occurred this becomes true.
 9530:                               It is up to the caller to initialize this to false
 9531:                               if desired.
 9532:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
 9533:                               of the resource that could not be rendered by the ssi
 9534:                               call.
 9535:    ssi_error_message   - The error string fetched from the ssi response
 9536:                               in the event of an error.
 9537: 
 9538: 
 9539: =head1 HANDLER SUBROUTINE
 9540: 
 9541: ssi_with_retries()
 9542: 
 9543: =head1 SUBROUTINES
 9544: 
 9545: =over
 9546: 
 9547: =item scantron_get_correction() : 
 9548: 
 9549:    Builds the interface screen to interact with the operator to fix a
 9550:    specific error condition in a specific scanline
 9551: 
 9552:  Arguments:
 9553:     $r           - Apache request object
 9554:     $i           - number of the current scanline
 9555:     $scan_record - hash ref as returned from &scantron_parse_scanline()
 9556:     $scan_config - hash ref as returned from &get_scantron_config()
 9557:     $line        - full contents of the current scanline
 9558:     $error       - error condition, valid values are
 9559:                    'incorrectCODE', 'duplicateCODE',
 9560:                    'doublebubble', 'missingbubble',
 9561:                    'duplicateID', 'incorrectID'
 9562:     $arg         - extra information needed
 9563:        For errors:
 9564:          - duplicateID   - paper number that this studentID was seen before on
 9565:          - duplicateCODE - array ref of the paper numbers this CODE was
 9566:                            seen on before
 9567:          - incorrectCODE - current incorrect CODE 
 9568:          - doublebubble  - array ref of the bubble lines that have double
 9569:                            bubble errors
 9570:          - missingbubble - array ref of the bubble lines that have missing
 9571:                            bubble errors
 9572: 
 9573: =item  scantron_get_maxbubble() : 
 9574: 
 9575:    Arguments:
 9576:        $nav_error  - Reference to scalar which is a flag to indicate a
 9577:                       failure to retrieve a navmap object.
 9578:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
 9579:        calling routine should trap the error condition and display the warning
 9580:        found in &navmap_errormsg().
 9581: 
 9582:        $scantron_config - Reference to bubblesheet format configuration hash.
 9583: 
 9584:    Returns the maximum number of bubble lines that are expected to
 9585:    occur. Does this by walking the selected sequence rendering the
 9586:    resource and then checking &Apache::lonxml::get_problem_counter()
 9587:    for what the current value of the problem counter is.
 9588: 
 9589:    Caches the results to $env{'form.scantron_maxbubble'},
 9590:    $env{'form.scantron.bubble_lines.n'}, 
 9591:    $env{'form.scantron.first_bubble_line.n'} and
 9592:    $env{"form.scantron.sub_bubblelines.n"}
 9593:    which are the total number of bubble, lines, the number of bubble
 9594:    lines for response n and number of the first bubble line for response n,
 9595:    and a comma separated list of numbers of bubble lines for sub-questions
 9596:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
 9597: 
 9598: 
 9599: =item  scantron_validate_missingbubbles() : 
 9600: 
 9601:    Validates all scanlines in the selected file to not have any
 9602:     answers that don't have bubbles that have not been verified
 9603:     to be bubble free.
 9604: 
 9605: =item  scantron_process_students() : 
 9606: 
 9607:    Routine that does the actual grading of the bubble sheet information.
 9608: 
 9609:    The parsed scanline hash is added to %env 
 9610: 
 9611:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
 9612:    foreach resource , with the form data of
 9613: 
 9614: 	'submitted'     =>'scantron' 
 9615: 	'grade_target'  =>'grade',
 9616: 	'grade_username'=> username of student
 9617: 	'grade_domain'  => domain of student
 9618: 	'grade_courseid'=> of course
 9619: 	'grade_symb'    => symb of resource to grade
 9620: 
 9621:     This triggers a grading pass. The problem grading code takes care
 9622:     of converting the bubbled letter information (now in %env) into a
 9623:     valid submission.
 9624: 
 9625: =item  scantron_upload_scantron_data() :
 9626: 
 9627:     Creates the screen for adding a new bubble sheet data file to a course.
 9628: 
 9629: =item  scantron_upload_scantron_data_save() : 
 9630: 
 9631:    Adds a provided bubble information data file to the course if user
 9632:    has the correct privileges to do so. 
 9633: 
 9634: =item  valid_file() :
 9635: 
 9636:    Validates that the requested bubble data file exists in the course.
 9637: 
 9638: =item  scantron_download_scantron_data() : 
 9639: 
 9640:    Shows a list of the three internal files (original, corrected,
 9641:    skipped) for a specific bubble sheet data file that exists in the
 9642:    course.
 9643: 
 9644: =item  scantron_validate_ID() : 
 9645: 
 9646:    Validates all scanlines in the selected file to not have any
 9647:    invalid or underspecified student/employee IDs
 9648: 
 9649: =item navmap_errormsg() :
 9650: 
 9651:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
 9652:    Should be called whenever the request to instantiate a navmap object fails.  
 9653: 
 9654: =back
 9655: 
 9656: =cut

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