File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.617: download - view: text, annotated - select for diffs
Tue Apr 13 16:12:54 2010 UTC (14 years, 1 month ago) by www
Branches: MAIN
CVS tags: HEAD
More breadcrumbs and "ungraded" mode

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.617 2010/04/13 16:12:54 www Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: 
   30: 
   31: package Apache::grades;
   32: use strict;
   33: use Apache::style;
   34: use Apache::lonxml;
   35: use Apache::lonnet;
   36: use Apache::loncommon;
   37: use Apache::lonhtmlcommon;
   38: use Apache::lonnavmaps;
   39: use Apache::lonhomework;
   40: use Apache::lonpickcode;
   41: use Apache::loncoursedata;
   42: use Apache::lonmsg();
   43: use Apache::Constants qw(:common);
   44: use Apache::lonlocal;
   45: use Apache::lonenc;
   46: use String::Similarity;
   47: use LONCAPA;
   48: 
   49: use POSIX qw(floor);
   50: 
   51: 
   52: 
   53: my %perm=();
   54: 
   55: #  These variables are used to recover from ssi errors
   56: 
   57: my $ssi_retries = 5;
   58: my $ssi_error;
   59: my $ssi_error_resource;
   60: my $ssi_error_message;
   61: 
   62: 
   63: sub ssi_with_retries {
   64:     my ($resource, $retries, %form) = @_;
   65:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
   66:     if ($response->is_error) {
   67: 	$ssi_error          = 1;
   68: 	$ssi_error_resource = $resource;
   69: 	$ssi_error_message  = $response->code . " " . $response->message;
   70:     }
   71: 
   72:     return $content;
   73: 
   74: }
   75: #
   76: #  Prodcuces an ssi retry failure error message to the user:
   77: #
   78: 
   79: sub ssi_print_error {
   80:     my ($r) = @_;
   81:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
   82:     $r->print('
   83: <br />
   84: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
   85: <p>
   86: '.&mt('Unable to retrieve a resource from a server:').'<br />
   87: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
   88: '.&mt('Error:').' '.$ssi_error_message.'
   89: </p>
   90: <p>'.
   91: &mt('It is recommended that you try again later, as this error may mean the server was just temporarily unavailable, or is down for maintenance.').'<br />'.
   92: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
   93: '</p>');
   94:     return;
   95: }
   96: 
   97: #
   98: # --- Retrieve the parts from the metadata file.---
   99: # Returns an array of everything that the resources stores away
  100: #
  101: 
  102: sub getpartlist {
  103:     my ($symb,$errorref) = @_;
  104: 
  105:     my $navmap   = Apache::lonnavmaps::navmap->new();
  106:     unless (ref($navmap)) {
  107:         if (ref($errorref)) { 
  108:             $$errorref = 'navmap';
  109:             return;
  110:         }
  111:     }
  112:     my $res      = $navmap->getBySymb($symb);
  113:     my $partlist = $res->parts();
  114:     my $url      = $res->src();
  115:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
  116: 
  117:     my @stores;
  118:     foreach my $part (@{ $partlist }) {
  119: 	foreach my $key (@metakeys) {
  120: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
  121: 	}
  122:     }
  123:     return @stores;
  124: }
  125: 
  126: #--- Format fullname, username:domain if different for display
  127: #--- Use anywhere where the student names are listed
  128: sub nameUserString {
  129:     my ($type,$fullname,$uname,$udom) = @_;
  130:     if ($type eq 'header') {
  131: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
  132:     } else {
  133: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
  134: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
  135:     }
  136: }
  137: 
  138: #--- Get the partlist and the response type for a given problem. ---
  139: #--- Indicate if a response type is coded handgraded or not. ---
  140: sub response_type {
  141:     my ($symb,$response_error) = @_;
  142: 
  143:     my $navmap = Apache::lonnavmaps::navmap->new();
  144:     unless (ref($navmap)) {
  145:         if (ref($response_error)) {
  146:             $$response_error = 1;
  147:         }
  148:         return;
  149:     }
  150:     my $res = $navmap->getBySymb($symb);
  151:     unless (ref($res)) {
  152:         $$response_error = 1;
  153:         return;
  154:     }
  155:     my $partlist = $res->parts();
  156:     my %vPart = 
  157: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
  158:     my (%response_types,%handgrade);
  159:     foreach my $part (@{ $partlist }) {
  160: 	next if (%vPart && !exists($vPart{$part}));
  161: 
  162: 	my @types = $res->responseType($part);
  163: 	my @ids = $res->responseIds($part);
  164: 	for (my $i=0; $i < scalar(@ids); $i++) {
  165: 	    $response_types{$part}{$ids[$i]} = $types[$i];
  166: 	    $handgrade{$part.'_'.$ids[$i]} = 
  167: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
  168: 				     '.handgrade',$symb);
  169: 	}
  170:     }
  171:     return ($partlist,\%handgrade,\%response_types);
  172: }
  173: 
  174: sub flatten_responseType {
  175:     my ($responseType) = @_;
  176:     my @part_response_id =
  177: 	map { 
  178: 	    my $part = $_;
  179: 	    map {
  180: 		[$part,$_]
  181: 		} sort(keys(%{ $responseType->{$part} }));
  182: 	} sort(keys(%$responseType));
  183:     return @part_response_id;
  184: }
  185: 
  186: sub get_display_part {
  187:     my ($partID,$symb)=@_;
  188:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
  189:     if (defined($display) and $display ne '') {
  190:         $display.= ' (<span class="LC_internal_info">'
  191:                   .&mt('Part ID: [_1]',$partID).'</span>)';
  192:     } else {
  193: 	$display=$partID;
  194:     }
  195:     return $display;
  196: }
  197: 
  198: sub reset_caches {
  199:     &reset_analyze_cache();
  200:     &reset_perm();
  201: }
  202: 
  203: {
  204:     my %analyze_cache;
  205:     my %analyze_cache_formkeys;
  206: 
  207:     sub reset_analyze_cache {
  208: 	undef(%analyze_cache);
  209:         undef(%analyze_cache_formkeys);
  210:     }
  211: 
  212:     sub get_analyze {
  213: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash)=@_;
  214: 	my $key = "$symb\0$uname\0$udom";
  215: 	if (exists($analyze_cache{$key})) {
  216:             my $getupdate = 0;
  217:             if (ref($add_to_hash) eq 'HASH') {
  218:                 foreach my $item (keys(%{$add_to_hash})) {
  219:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
  220:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
  221:                             $getupdate = 1;
  222:                             last;
  223:                         }
  224:                     } else {
  225:                         $getupdate = 1;
  226:                     }
  227:                 }
  228:             }
  229:             if (!$getupdate) {
  230:                 return $analyze_cache{$key};
  231:             }
  232:         }
  233: 
  234: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  235: 	$url=&Apache::lonnet::clutter($url);
  236:         my %form = ('grade_target'      => 'analyze',
  237:                     'grade_domain'      => $udom,
  238:                     'grade_symb'        => $symb,
  239:                     'grade_courseid'    =>  $env{'request.course.id'},
  240:                     'grade_username'    => $uname,
  241:                     'grade_noincrement' => $no_increment);
  242:         if (ref($add_to_hash)) {
  243:             %form = (%form,%{$add_to_hash});
  244:         } 
  245: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
  246: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  247: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  248:         if (ref($add_to_hash) eq 'HASH') {
  249:             $analyze_cache_formkeys{$key} = $add_to_hash;
  250:         } else {
  251:             $analyze_cache_formkeys{$key} = {};
  252:         }
  253: 	return $analyze_cache{$key} = \%analyze;
  254:     }
  255: 
  256:     sub get_order {
  257: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment)=@_;
  258: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment);
  259: 	return $analyze->{"$partid.$respid.shown"};
  260:     }
  261: 
  262:     sub get_radiobutton_correct_foil {
  263: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
  264: 	my $analyze = &get_analyze($symb,$uname,$udom);
  265:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom);
  266:         if (ref($foils) eq 'ARRAY') {
  267: 	    foreach my $foil (@{$foils}) {
  268: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  269: 		    return $foil;
  270: 	        }
  271: 	    }
  272: 	}
  273:     }
  274: 
  275:     sub scantron_partids_tograde {
  276:         my ($resource,$cid,$uname,$udom,$check_for_randomlist) = @_;
  277:         my (%analysis,@parts);
  278:         if (ref($resource)) {
  279:             my $symb = $resource->symb();
  280:             my $add_to_form;
  281:             if ($check_for_randomlist) {
  282:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
  283:             }
  284:             my $analyze = &get_analyze($symb,$uname,$udom,undef,$add_to_form);
  285:             if (ref($analyze) eq 'HASH') {
  286:                 %analysis = %{$analyze};
  287:             }
  288:             if (ref($analysis{'parts'}) eq 'ARRAY') {
  289:                 foreach my $part (@{$analysis{'parts'}}) {
  290:                     my ($id,$respid) = split(/\./,$part);
  291:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
  292:                         push(@parts,$part);
  293:                     }
  294:                 }
  295:             }
  296:         }
  297:         return (\%analysis,\@parts);
  298:     }
  299: 
  300: }
  301: 
  302: #--- Clean response type for display
  303: #--- Currently filters option/rank/radiobutton/match/essay/Task
  304: #        response types only.
  305: sub cleanRecord {
  306:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  307: 	$uname,$udom) = @_;
  308:     my $grayFont = '<span class="LC_internal_info">';
  309:     if ($response =~ /^(option|rank)$/) {
  310: 	my %answer=&Apache::lonnet::str2hash($answer);
  311: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  312: 	my ($toprow,$bottomrow);
  313: 	foreach my $foil (@$order) {
  314: 	    if ($grading{$foil} == 1) {
  315: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  316: 	    } else {
  317: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  318: 	    }
  319: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  320: 	}
  321: 	return '<blockquote><table border="1">'.
  322: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  323: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  324: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
  325:     } elsif ($response eq 'match') {
  326: 	my %answer=&Apache::lonnet::str2hash($answer);
  327: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  328: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  329: 	my ($toprow,$middlerow,$bottomrow);
  330: 	foreach my $foil (@$order) {
  331: 	    my $item=shift(@items);
  332: 	    if ($grading{$foil} == 1) {
  333: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  334: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  335: 	    } else {
  336: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  337: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  338: 	    }
  339: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  340: 	}
  341: 	return '<blockquote><table border="1">'.
  342: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  343: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  344: 	    $middlerow.'</tr>'.
  345: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  346: 	    $bottomrow.'</tr>'.'</table></blockquote>';
  347:     } elsif ($response eq 'radiobutton') {
  348: 	my %answer=&Apache::lonnet::str2hash($answer);
  349: 	my ($toprow,$bottomrow);
  350: 	my $correct = 
  351: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
  352: 	foreach my $foil (@$order) {
  353: 	    if (exists($answer{$foil})) {
  354: 		if ($foil eq $correct) {
  355: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  356: 		} else {
  357: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  358: 		}
  359: 	    } else {
  360: 		$toprow.='<td>'.&mt('false').'</td>';
  361: 	    }
  362: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  363: 	}
  364: 	return '<blockquote><table border="1">'.
  365: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  366: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  367: 	    $bottomrow.'</tr>'.'</table></blockquote>';
  368:     } elsif ($response eq 'essay') {
  369: 	if (! exists ($env{'form.'.$symb})) {
  370: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  371: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  372: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  373: 
  374: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  375: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  376: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  377: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  378: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  379: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  380: 	}
  381: 	$answer =~ s-\n-<br />-g;
  382: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  383:     } elsif ( $response eq 'organic') {
  384: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
  385: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  386: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  387: 	return $result;
  388:     } elsif ( $response eq 'Task') {
  389: 	if ( $answer eq 'SUBMITTED') {
  390: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  391: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  392: 	    return $result;
  393: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  394: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  395: 			       keys(%{$record}));
  396: 	    return join('<br />',($version,@matches));
  397: 			       
  398: 			       
  399: 	} else {
  400: 	    my $result =
  401: 		'<p>'
  402: 		.&mt('Overall result: [_1]',
  403: 		     $record->{$version."resource.$respid.$partid.status"})
  404: 		.'</p>';
  405: 	    
  406: 	    $result .= '<ul>';
  407: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  408: 			     keys(%{$record}));
  409: 	    foreach my $grade (sort(@grade)) {
  410: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  411: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  412: 				     $dim, $record->{$grade}).
  413: 			  '</li>';
  414: 	    }
  415: 	    $result.='</ul>';
  416: 	    return $result;
  417: 	}
  418:     } elsif ( $response =~ m/(?:numerical|formula)/) {
  419: 	$answer = 
  420: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  421: 							      $answer);
  422:     }
  423:     return $answer;
  424: }
  425: 
  426: #-- A couple of common js functions
  427: sub commonJSfunctions {
  428:     my $request = shift;
  429:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
  430:     function radioSelection(radioButton) {
  431: 	var selection=null;
  432: 	if (radioButton.length > 1) {
  433: 	    for (var i=0; i<radioButton.length; i++) {
  434: 		if (radioButton[i].checked) {
  435: 		    return radioButton[i].value;
  436: 		}
  437: 	    }
  438: 	} else {
  439: 	    if (radioButton.checked) return radioButton.value;
  440: 	}
  441: 	return selection;
  442:     }
  443: 
  444:     function pullDownSelection(selectOne) {
  445: 	var selection="";
  446: 	if (selectOne.length > 1) {
  447: 	    for (var i=0; i<selectOne.length; i++) {
  448: 		if (selectOne[i].selected) {
  449: 		    return selectOne[i].value;
  450: 		}
  451: 	    }
  452: 	} else {
  453:             // only one value it must be the selected one
  454: 	    return selectOne.value;
  455: 	}
  456:     }
  457: COMMONJSFUNCTIONS
  458: }
  459: 
  460: #--- Dumps the class list with usernames,list of sections,
  461: #--- section, ids and fullnames for each user.
  462: sub getclasslist {
  463:     my ($getsec,$filterlist,$getgroup) = @_;
  464:     my @getsec;
  465:     my @getgroup;
  466:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  467:     if (!ref($getsec)) {
  468: 	if ($getsec ne '' && $getsec ne 'all') {
  469: 	    @getsec=($getsec);
  470: 	}
  471:     } else {
  472: 	@getsec=@{$getsec};
  473:     }
  474:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  475:     if (!ref($getgroup)) {
  476: 	if ($getgroup ne '' && $getgroup ne 'all') {
  477: 	    @getgroup=($getgroup);
  478: 	}
  479:     } else {
  480: 	@getgroup=@{$getgroup};
  481:     }
  482:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  483: 
  484:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  485:     # Bail out if we were unable to get the classlist
  486:     return if (! defined($classlist));
  487:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  488:     #
  489:     my %sections;
  490:     my %fullnames;
  491:     foreach my $student (keys(%$classlist)) {
  492:         my $end      = 
  493:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  494:         my $start    = 
  495:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  496:         my $id       = 
  497:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  498:         my $section  = 
  499:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  500:         my $fullname = 
  501:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  502:         my $status   = 
  503:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  504:         my $group   = 
  505:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  506: 	# filter students according to status selected
  507: 	if ($filterlist && (!($stu_status =~ /Any/))) {
  508: 	    if (!($stu_status =~ $status)) {
  509: 		delete($classlist->{$student});
  510: 		next;
  511: 	    }
  512: 	}
  513: 	# filter students according to groups selected
  514: 	my @stu_groups = split(/,/,$group);
  515: 	if (@getgroup) {
  516: 	    my $exclude = 1;
  517: 	    foreach my $grp (@getgroup) {
  518: 	        foreach my $stu_group (@stu_groups) {
  519: 	            if ($stu_group eq $grp) {
  520: 	                $exclude = 0;
  521:     	            } 
  522: 	        }
  523:     	        if (($grp eq 'none') && !$group) {
  524:         	        $exclude = 0;
  525:         	}
  526: 	    }
  527: 	    if ($exclude) {
  528: 	        delete($classlist->{$student});
  529: 	    }
  530: 	}
  531: 	$section = ($section ne '' ? $section : 'none');
  532: 	if (&canview($section)) {
  533: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  534: 		$sections{$section}++;
  535: 		if ($classlist->{$student}) {
  536: 		    $fullnames{$student}=$fullname;
  537: 		}
  538: 	    } else {
  539: 		delete($classlist->{$student});
  540: 	    }
  541: 	} else {
  542: 	    delete($classlist->{$student});
  543: 	}
  544:     }
  545:     my %seen = ();
  546:     my @sections = sort(keys(%sections));
  547:     return ($classlist,\@sections,\%fullnames);
  548: }
  549: 
  550: sub canmodify {
  551:     my ($sec)=@_;
  552:     if ($perm{'mgr'}) {
  553: 	if (!defined($perm{'mgr_section'})) {
  554: 	    # can modify whole class
  555: 	    return 1;
  556: 	} else {
  557: 	    if ($sec eq $perm{'mgr_section'}) {
  558: 		#can modify the requested section
  559: 		return 1;
  560: 	    } else {
  561: 		# can't modify the request section
  562: 		return 0;
  563: 	    }
  564: 	}
  565:     }
  566:     #can't modify
  567:     return 0;
  568: }
  569: 
  570: sub canview {
  571:     my ($sec)=@_;
  572:     if ($perm{'vgr'}) {
  573: 	if (!defined($perm{'vgr_section'})) {
  574: 	    # can modify whole class
  575: 	    return 1;
  576: 	} else {
  577: 	    if ($sec eq $perm{'vgr_section'}) {
  578: 		#can modify the requested section
  579: 		return 1;
  580: 	    } else {
  581: 		# can't modify the request section
  582: 		return 0;
  583: 	    }
  584: 	}
  585:     }
  586:     #can't modify
  587:     return 0;
  588: }
  589: 
  590: #--- Retrieve the grade status of a student for all the parts
  591: sub student_gradeStatus {
  592:     my ($symb,$udom,$uname,$partlist) = @_;
  593:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  594:     my %partstatus = ();
  595:     foreach (@$partlist) {
  596: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  597: 	$status              = 'nothing' if ($status eq '');
  598: 	$partstatus{$_}      = $status;
  599: 	my $subkey           = "resource.$_.submitted_by";
  600: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  601:     }
  602:     return %partstatus;
  603: }
  604: 
  605: # hidden form and javascript that calls the form
  606: # Use by verifyscript and viewgrades
  607: # Shows a student's view of problem and submission
  608: sub jscriptNform {
  609:     my ($symb) = @_;
  610:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  611:     my $jscript= &Apache::lonhtmlcommon::scripttag(
  612: 	'    function viewOneStudent(user,domain) {'."\n".
  613: 	'	document.onestudent.student.value = user;'."\n".
  614: 	'	document.onestudent.userdom.value = domain;'."\n".
  615: 	'	document.onestudent.submit();'."\n".
  616: 	'    }'."\n".
  617: 	"\n");
  618:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  619: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  620: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  621: 	'<input type="hidden" name="command" value="submission" />'."\n".
  622: 	'<input type="hidden" name="student" value="" />'."\n".
  623: 	'<input type="hidden" name="userdom" value="" />'."\n".
  624: 	'</form>'."\n";
  625:     return $jscript;
  626: }
  627: 
  628: 
  629: 
  630: # Given the score (as a number [0-1] and the weight) what is the final
  631: # point value? This function will round to the nearest tenth, third,
  632: # or quarter if one of those is within the tolerance of .00001.
  633: sub compute_points {
  634:     my ($score, $weight) = @_;
  635:     
  636:     my $tolerance = .00001;
  637:     my $points = $score * $weight;
  638: 
  639:     # Check for nearness to 1/x.
  640:     my $check_for_nearness = sub {
  641:         my ($factor) = @_;
  642:         my $num = ($points * $factor) + $tolerance;
  643:         my $floored_num = floor($num);
  644:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  645:             return $floored_num / $factor;
  646:         }
  647:         return $points;
  648:     };
  649: 
  650:     $points = $check_for_nearness->(10);
  651:     $points = $check_for_nearness->(3);
  652:     $points = $check_for_nearness->(4);
  653:     
  654:     return $points;
  655: }
  656: 
  657: #------------------ End of general use routines --------------------
  658: 
  659: #
  660: # Find most similar essay
  661: #
  662: 
  663: sub most_similar {
  664:     my ($uname,$udom,$uessay,$old_essays)=@_;
  665: 
  666: # ignore spaces and punctuation
  667: 
  668:     $uessay=~s/\W+/ /gs;
  669: 
  670: # ignore empty submissions (occuring when only files are sent)
  671: 
  672:     unless ($uessay=~/\w+/s) { return ''; }
  673: 
  674: # these will be returned. Do not care if not at least 50 percent similar
  675:     my $limit=0.6;
  676:     my $sname='';
  677:     my $sdom='';
  678:     my $scrsid='';
  679:     my $sessay='';
  680: # go through all essays ...
  681:     foreach my $tkey (keys(%$old_essays)) {
  682: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  683: # ... except the same student
  684:         next if (($tname eq $uname) && ($tdom eq $udom));
  685: 	my $tessay=$old_essays->{$tkey};
  686: 	$tessay=~s/\W+/ /gs;
  687: # String similarity gives up if not even limit
  688: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  689: # Found one
  690: 	if ($tsimilar>$limit) {
  691: 	    $limit=$tsimilar;
  692: 	    $sname=$tname;
  693: 	    $sdom=$tdom;
  694: 	    $scrsid=$tcrsid;
  695: 	    $sessay=$old_essays->{$tkey};
  696: 	}
  697:     }
  698:     if ($limit>0.6) {
  699:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  700:     } else {
  701:        return ('','','','',0);
  702:     }
  703: }
  704: 
  705: #-------------------------------------------------------------------
  706: 
  707: #------------------------------------ Receipt Verification Routines
  708: #
  709: 
  710: sub initialverifyreceipt {
  711:    my ($request,$symb) = @_;
  712:    &commonJSfunctions($request);
  713:    return '<form name="gradingMenu"><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
  714:         &Apache::lonnet::recprefix($env{'request.course.id'}).
  715:         '-<input type="text" name="receipt" size="4" />'.
  716:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  717:         '<input type="hidden" name="command" value="verify" />'.
  718:         "</form>\n";
  719: }
  720: 
  721: #--- Check whether a receipt number is valid.---
  722: sub verifyreceipt {
  723:     my ($request,$symb)  = @_;
  724: 
  725:     my $courseid = $env{'request.course.id'};
  726:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  727: 	$env{'form.receipt'};
  728:     $receipt     =~ s/[^\-\d]//g;
  729: 
  730:     my $title.=
  731: 	'<h3><span class="LC_info">'.
  732: 	&mt('Verifying Receipt Number [_1]',$receipt).
  733: 	'</span></h3>'."\n";
  734: 
  735:     my ($string,$contents,$matches) = ('','',0);
  736:     my (undef,undef,$fullname) = &getclasslist('all','0');
  737:     
  738:     my $receiptparts=0;
  739:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  740: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  741:     my $parts=['0'];
  742:     if ($receiptparts) {
  743:         my $res_error; 
  744:         ($parts)=&response_type($symb,\$res_error);
  745:         if ($res_error) {
  746:             return &navmap_errormsg();
  747:         } 
  748:     }
  749:     
  750:     my $header = 
  751: 	&Apache::loncommon::start_data_table().
  752: 	&Apache::loncommon::start_data_table_header_row().
  753: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  754: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  755: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  756:     if ($receiptparts) {
  757: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  758:     }
  759:     $header.=
  760: 	&Apache::loncommon::end_data_table_header_row();
  761: 
  762:     foreach (sort 
  763: 	     {
  764: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  765: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  766: 		 }
  767: 		 return $a cmp $b;
  768: 	     } (keys(%$fullname))) {
  769: 	my ($uname,$udom)=split(/\:/);
  770: 	foreach my $part (@$parts) {
  771: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  772: 		$contents.=
  773: 		    &Apache::loncommon::start_data_table_row().
  774: 		    '<td>&nbsp;'."\n".
  775: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  776: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  777: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  778: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  779: 		if ($receiptparts) {
  780: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  781: 		}
  782: 		$contents.= 
  783: 		    &Apache::loncommon::end_data_table_row()."\n";
  784: 		
  785: 		$matches++;
  786: 	    }
  787: 	}
  788:     }
  789:     if ($matches == 0) {
  790:         $string = $title
  791:                  .'<p class="LC_warning">'
  792:                  .&mt('No match found for the above receipt number.')
  793:                  .'</p>';
  794:     } else {
  795: 	$string = &jscriptNform($symb).$title.
  796: 	    '<p>'.
  797: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
  798: 	    '</p>'.
  799: 	    $header.
  800: 	    $contents.
  801: 	    &Apache::loncommon::end_data_table()."\n";
  802:     }
  803:     return $string;
  804: }
  805: 
  806: #--- This is called by a number of programs.
  807: #--- Called from the Grading Menu - View/Grade an individual student
  808: #--- Also called directly when one clicks on the subm button 
  809: #    on the problem page.
  810: sub listStudents {
  811:     my ($request,$symb,$submitonly) = @_;
  812: 
  813:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  814:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  815:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  816:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  817:     unless ($submitonly) {
  818:        $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  819:     }
  820:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
  821: 
  822:     my $result='<h3><span class="LC_info">&nbsp;'
  823: 	.&mt("$viewgrade Submissions for a Student or a Group of Students")
  824: 	.'</span></h3>';
  825: 
  826:     my ($partlist,$handgrade,$responseType) = &response_type($symb
  827: #,$res_error
  828:     );
  829: 
  830:     my %lt = &Apache::lonlocal::texthash (
  831: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
  832: 		'single'   => 'Please select the student before clicking on the Next button.',
  833: 	     );
  834:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
  835:     function checkSelect(checkBox) {
  836: 	var ctr=0;
  837: 	var sense="";
  838: 	if (checkBox.length > 1) {
  839: 	    for (var i=0; i<checkBox.length; i++) {
  840: 		if (checkBox[i].checked) {
  841: 		    ctr++;
  842: 		}
  843: 	    }
  844: 	    sense = '$lt{'multiple'}';
  845: 	} else {
  846: 	    if (checkBox.checked) {
  847: 		ctr = 1;
  848: 	    }
  849: 	    sense = '$lt{'single'}';
  850: 	}
  851: 	if (ctr == 0) {
  852: 	    alert(sense);
  853: 	    return false;
  854: 	}
  855: 	document.gradesub.submit();
  856:     }
  857: 
  858:     function reLoadList(formname) {
  859: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  860: 	formname.command.value = 'submission';
  861: 	formname.submit();
  862:     }
  863: LISTJAVASCRIPT
  864: 
  865:     &commonJSfunctions($request);
  866:     $request->print($result);
  867: 
  868:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
  869:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
  870:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  871: 	"\n";
  872: 	
  873:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
  874:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
  875:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
  876:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
  877:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
  878:                   .&Apache::lonhtmlcommon::row_closure();
  879:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
  880:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
  881:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
  882:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
  883:                   .&Apache::lonhtmlcommon::row_closure();
  884: 
  885:     my $submission_options;
  886:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
  887: 	$submission_options.=
  888: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
  889:     }
  890:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  891:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  892:     $env{'form.Status'} = $saveStatus;
  893:     $submission_options.=
  894:         '<span class="LC_nobreak">'.
  895:         '<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.
  896:         &mt('last submission only').' </label></span>'."\n".
  897:         '<span class="LC_nobreak">'.
  898:         '<label><input type="radio" name="lastSub" value="last" /> '.
  899:         &mt('last submission &amp; parts info').' </label></span>'."\n".
  900:         '<span class="LC_nobreak">'.
  901:         '<label><input type="radio" name="lastSub" value="datesub" /> '.
  902:         &mt('by dates and submissions').'</label></span>'."\n".
  903:         '<span class="LC_nobreak">'.
  904:         '<label><input type="radio" name="lastSub" value="all" /> '.
  905:         &mt('all details').'</label></span>';
  906:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
  907:                   .$submission_options
  908:                   .&Apache::lonhtmlcommon::row_closure();
  909: 
  910:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
  911:                   .'<select name="increment">'
  912:                   .'<option value="1">'.&mt('Whole Points').'</option>'
  913:                   .'<option value=".5">'.&mt('Half Points').'</option>'
  914:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
  915:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
  916:                   .'</select>'
  917:                   .&Apache::lonhtmlcommon::row_closure();
  918: 
  919:     $gradeTable .= 
  920:         &build_section_inputs().
  921: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
  922: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
  923: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
  924: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  925: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
  926: 
  927:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
  928: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
  929:     } else {
  930:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
  931:                       .&Apache::lonhtmlcommon::StatusOptions(
  932:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
  933:                       .&Apache::lonhtmlcommon::row_closure();
  934:     }
  935: 
  936:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
  937:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
  938:                   .&Apache::lonhtmlcommon::row_closure(1)
  939:                   .&Apache::lonhtmlcommon::end_pick_box();
  940: 
  941:     $gradeTable .= '<p>'
  942:                   .&mt('To '.lc($viewgrade)." a submission or a group of submissions, click on the check box(es) next to the student's name(s). Then click on the Next button.")."\n"
  943:                   .'<input type="hidden" name="command" value="processGroup" />'
  944:                   .'</p>';
  945: 
  946: # checkall buttons
  947:     $gradeTable.=&check_script('gradesub', 'stuinfo');
  948:     $gradeTable.='<input type="button" '."\n".
  949:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
  950:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
  951:     $gradeTable.=&check_buttons();
  952:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
  953:     $gradeTable.= &Apache::loncommon::start_data_table().
  954: 	&Apache::loncommon::start_data_table_header_row();
  955:     my $loop = 0;
  956:     while ($loop < 2) {
  957: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
  958: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
  959: 	if ($env{'form.showgrading'} eq 'yes' 
  960: 	    && $submitonly ne 'queued'
  961: 	    && $submitonly ne 'all') {
  962: 	    foreach my $part (sort(@$partlist)) {
  963: 		my $display_part=
  964: 		    &get_display_part((split(/_/,$part))[0],$symb);
  965: 		$gradeTable.=
  966: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
  967: 	    }
  968: 	} elsif ($submitonly eq 'queued') {
  969: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
  970: 	}
  971: 	$loop++;
  972: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
  973:     }
  974:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
  975: 
  976:     my $ctr = 0;
  977:     foreach my $student (sort 
  978: 			 {
  979: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  980: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  981: 			     }
  982: 			     return $a cmp $b;
  983: 			 }
  984: 			 (keys(%$fullname))) {
  985: 	my ($uname,$udom) = split(/:/,$student);
  986: 
  987: 	my %status = ();
  988: 
  989: 	if ($submitonly eq 'queued') {
  990: 	    my %queue_status = 
  991: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
  992: 							$udom,$uname);
  993: 	    next if (!defined($queue_status{'gradingqueue'}));
  994: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
  995: 	}
  996: 
  997: 	if ($env{'form.showgrading'} eq 'yes' 
  998: 	    && $submitonly ne 'queued'
  999: 	    && $submitonly ne 'all') {
 1000: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
 1001: 	    my $submitted = 0;
 1002: 	    my $graded = 0;
 1003: 	    my $incorrect = 0;
 1004: 	    foreach (keys(%status)) {
 1005: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1006: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1007: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1008: 		
 1009: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1010: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1011: 		    $submitted = 0;
 1012: 		    my ($part)=split(/\./,$partid);
 1013: 		    $gradeTable.='<input type="hidden" name="'.
 1014: 			$student.':'.$part.':submitted_by" value="'.
 1015: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1016: 		}
 1017: 	    }
 1018: 	    
 1019: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1020: 				     $submitonly eq 'incorrect' ||
 1021: 				     $submitonly eq 'graded'));
 1022: 	    next if (!$graded && ($submitonly eq 'graded'));
 1023: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1024: 	}
 1025: 
 1026: 	$ctr++;
 1027: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1028:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1029: 	if ( $perm{'vgr'} eq 'F' ) {
 1030: 	    if ($ctr%2 ==1) {
 1031: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1032: 	    }
 1033: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1034:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1035:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1036: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1037: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1038: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1039: 
 1040: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
 1041: 		foreach (sort(keys(%status))) {
 1042: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1043: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1044: 		}
 1045: 	    }
 1046: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1047: 	    if ($ctr%2 ==0) {
 1048: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1049: 	    }
 1050: 	}
 1051:     }
 1052:     if ($ctr%2 ==1) {
 1053: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1054: 	    if ($env{'form.showgrading'} eq 'yes' 
 1055: 		&& $submitonly ne 'queued'
 1056: 		&& $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)  = shift;
 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);
 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: 	if (val == "Grade Student") {
 1288: 	    formname.showgrading.value = "yes";
 1289: 	    if (formname.Status.value == "") {
 1290: 		formname.Status.value = "Active";
 1291: 	    }
 1292: 	    formname.studentNo.value = total;
 1293: 	}
 1294: 	formname.submit();
 1295:     }
 1296: 
 1297: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1298:     function checkSubmitPage(formname,total) {
 1299: 	noscore = new Array(100);
 1300: 	var ptr = 0;
 1301: 	for (i=1;i<total;i++) {
 1302: 	    var partid = formname["q_"+i].value;
 1303: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1304: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1305: 		var status = formname["solved"+i+"_"+partid].value;
 1306: 		if (points == "" && status != "correct_by_student") {
 1307: 		    noscore[ptr] = i;
 1308: 		    ptr++;
 1309: 		}
 1310: 	    }
 1311: 	}
 1312: 	if (ptr != 0) {
 1313: 	    var sense = ptr == 1 ? ": " : "s: ";
 1314: 	    var prolist = "";
 1315: 	    if (ptr == 1) {
 1316: 		prolist = noscore[0];
 1317: 	    } else {
 1318: 		var i = 0;
 1319: 		while (i < ptr-1) {
 1320: 		    prolist += noscore[i]+", ";
 1321: 		    i++;
 1322: 		}
 1323: 		prolist += "and "+noscore[i];
 1324: 	    }
 1325: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1326: 	    if (resp == false) {
 1327: 		return false;
 1328: 	    }
 1329: 	}
 1330: 
 1331: 	formname.submit();
 1332:     }
 1333: SUBJAVASCRIPT
 1334: }
 1335: 
 1336: #--- javascript for essay type problem --
 1337: sub sub_page_kw_js {
 1338:     my $request = shift;
 1339:     my $iconpath = $request->dir_config('lonIconsURL');
 1340:     &commonJSfunctions($request);
 1341: 
 1342:     my $inner_js_msg_central= &Apache::lonhtmlcommon::scripttag(<<INNERJS);
 1343:     function checkInput() {
 1344:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1345:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1346:       var usrctr = document.msgcenter.usrctr.value;
 1347:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1348:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1349: 
 1350:       var msgchk = "";
 1351:       if (document.msgcenter.subchk.checked) {
 1352:          msgchk = "msgsub,";
 1353:       }
 1354:       var includemsg = 0;
 1355:       for (var i=1; i<=nmsg; i++) {
 1356:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1357:           var frmmsg = document.msgcenter["msg"+i];
 1358:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1359:           var showflg = opener.document.SCORE["shownOnce"+i];
 1360:           showflg.value = "1";
 1361:           var chkbox = document.msgcenter["msgn"+i];
 1362:           if (chkbox.checked) {
 1363:              msgchk += "savemsg"+i+",";
 1364:              includemsg = 1;
 1365:           }
 1366:       }
 1367:       if (document.msgcenter.newmsgchk.checked) {
 1368:          msgchk += "newmsg"+usrctr;
 1369:          includemsg = 1;
 1370:       }
 1371:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1372:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1373:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1374:       includemsg.value = msgchk;
 1375: 
 1376:       self.close()
 1377: 
 1378:     }
 1379: INNERJS
 1380: 
 1381:     my $inner_js_highlight_central= &Apache::lonhtmlcommon::scripttag(<<INNERJS);
 1382:     function updateChoice(flag) {
 1383:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1384:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1385:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1386:       opener.document.SCORE.refresh.value = "on";
 1387:       if (opener.document.SCORE.keywords.value!=""){
 1388:          opener.document.SCORE.submit();
 1389:       }
 1390:       self.close()
 1391:     }
 1392: INNERJS
 1393: 
 1394:     my $start_page_msg_central = 
 1395:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1396: 				       {'js_ready'  => 1,
 1397: 					'only_body' => 1,
 1398: 					'bgcolor'   =>'#FFFFFF',});
 1399:     my $end_page_msg_central = 
 1400: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1401: 
 1402: 
 1403:     my $start_page_highlight_central = 
 1404:         &Apache::loncommon::start_page('Highlight Central',
 1405: 				       $inner_js_highlight_central,
 1406: 				       {'js_ready'  => 1,
 1407: 					'only_body' => 1,
 1408: 					'bgcolor'   =>'#FFFFFF',});
 1409:     my $end_page_highlight_central = 
 1410: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1411: 
 1412:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1413:     $docopen=~s/^document\.//;
 1414:     my $alertmsg = &mt('Please select a word or group of words from document and then click this link.');
 1415:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1416: 
 1417: //===================== Show list of keywords ====================
 1418:   function keywords(formname) {
 1419:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
 1420:     if (nret==null) return;
 1421:     formname.keywords.value = nret;
 1422: 
 1423:     if (formname.keywords.value != "") {
 1424: 	formname.refresh.value = "on";
 1425: 	formname.submit();
 1426:     }
 1427:     return;
 1428:   }
 1429: 
 1430: //===================== Script to view submitted by ==================
 1431:   function viewSubmitter(submitter) {
 1432:     document.SCORE.refresh.value = "on";
 1433:     document.SCORE.NCT.value = "1";
 1434:     document.SCORE.unamedom0.value = submitter;
 1435:     document.SCORE.submit();
 1436:     return;
 1437:   }
 1438: 
 1439: //===================== Script to add keyword(s) ==================
 1440:   function getSel() {
 1441:     if (document.getSelection) txt = document.getSelection();
 1442:     else if (document.selection) txt = document.selection.createRange().text;
 1443:     else return;
 1444:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1445:     if (cleantxt=="") {
 1446: 	alert("$alertmsg");
 1447: 	return;
 1448:     }
 1449:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
 1450:     if (nret==null) return;
 1451:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1452:     if (document.SCORE.keywords.value != "") {
 1453: 	document.SCORE.refresh.value = "on";
 1454: 	document.SCORE.submit();
 1455:     }
 1456:     return;
 1457:   }
 1458: 
 1459: //====================== Script for composing message ==============
 1460:    // preload images
 1461:    img1 = new Image();
 1462:    img1.src = "$iconpath/mailbkgrd.gif";
 1463:    img2 = new Image();
 1464:    img2.src = "$iconpath/mailto.gif";
 1465: 
 1466:   function msgCenter(msgform,usrctr,fullname) {
 1467:     var Nmsg  = msgform.savemsgN.value;
 1468:     savedMsgHeader(Nmsg,usrctr,fullname);
 1469:     var subject = msgform.msgsub.value;
 1470:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1471:     re = /msgsub/;
 1472:     var shwsel = "";
 1473:     if (re.test(msgchk)) { shwsel = "checked" }
 1474:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1475:     displaySubject(checkEntities(subject),shwsel);
 1476:     for (var i=1; i<=Nmsg; i++) {
 1477: 	var testmsg = "savemsg"+i+",";
 1478: 	re = new RegExp(testmsg,"g");
 1479: 	shwsel = "";
 1480: 	if (re.test(msgchk)) { shwsel = "checked" }
 1481: 	var message = document.SCORE["savemsg"+i].value;
 1482: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1483: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1484: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1485:     }
 1486:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1487:     shwsel = "";
 1488:     re = /newmsg/;
 1489:     if (re.test(msgchk)) { shwsel = "checked" }
 1490:     newMsg(newmsg,shwsel);
 1491:     msgTail(); 
 1492:     return;
 1493:   }
 1494: 
 1495:   function checkEntities(strx) {
 1496:     if (strx.length == 0) return strx;
 1497:     var orgStr = ["&", "<", ">", '"']; 
 1498:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1499:     var counter = 0;
 1500:     while (counter < 4) {
 1501: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1502: 	counter++;
 1503:     }
 1504:     return strx;
 1505:   }
 1506: 
 1507:   function strReplace(strx, orgStr, newStr) {
 1508:     return strx.split(orgStr).join(newStr);
 1509:   }
 1510: 
 1511:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1512:     var height = 70*Nmsg+250;
 1513:     var scrollbar = "no";
 1514:     if (height > 600) {
 1515: 	height = 600;
 1516: 	scrollbar = "yes";
 1517:     }
 1518:     var xpos = (screen.width-600)/2;
 1519:     xpos = (xpos < 0) ? '0' : xpos;
 1520:     var ypos = (screen.height-height)/2-30;
 1521:     ypos = (ypos < 0) ? '0' : ypos;
 1522: 
 1523:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
 1524:     pWin.focus();
 1525:     pDoc = pWin.document;
 1526:     pDoc.$docopen;
 1527:     pDoc.write('$start_page_msg_central');
 1528: 
 1529:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1530:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1531:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
 1532: 
 1533:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1534:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1535:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
 1536: }
 1537:     function displaySubject(msg,shwsel) {
 1538:     pDoc = pWin.document;
 1539:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1540:     pDoc.write("<td>Subject<\\/td>");
 1541:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1542:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1543: }
 1544: 
 1545:   function displaySavedMsg(ctr,msg,shwsel) {
 1546:     pDoc = pWin.document;
 1547:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1548:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1549:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1550:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1551: }
 1552: 
 1553:   function newMsg(newmsg,shwsel) {
 1554:     pDoc = pWin.document;
 1555:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1556:     pDoc.write("<td align=\\"center\\">New<\\/td>");
 1557:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1558:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1559: }
 1560: 
 1561:   function msgTail() {
 1562:     pDoc = pWin.document;
 1563:     pDoc.write("<\\/table>");
 1564:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1565:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1566:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
 1567:     pDoc.write("<\\/form>");
 1568:     pDoc.write('$end_page_msg_central');
 1569:     pDoc.close();
 1570: }
 1571: 
 1572: //====================== Script for keyword highlight options ==============
 1573:   function kwhighlight() {
 1574:     var kwclr    = document.SCORE.kwclr.value;
 1575:     var kwsize   = document.SCORE.kwsize.value;
 1576:     var kwstyle  = document.SCORE.kwstyle.value;
 1577:     var redsel = "";
 1578:     var grnsel = "";
 1579:     var blusel = "";
 1580:     if (kwclr=="red")   {var redsel="checked"};
 1581:     if (kwclr=="green") {var grnsel="checked"};
 1582:     if (kwclr=="blue")  {var blusel="checked"};
 1583:     var sznsel = "";
 1584:     var sz1sel = "";
 1585:     var sz2sel = "";
 1586:     if (kwsize=="0")  {var sznsel="checked"};
 1587:     if (kwsize=="+1") {var sz1sel="checked"};
 1588:     if (kwsize=="+2") {var sz2sel="checked"};
 1589:     var synsel = "";
 1590:     var syisel = "";
 1591:     var sybsel = "";
 1592:     if (kwstyle=="")    {var synsel="checked"};
 1593:     if (kwstyle=="<i>") {var syisel="checked"};
 1594:     if (kwstyle=="<b>") {var sybsel="checked"};
 1595:     highlightCentral();
 1596:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
 1597:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
 1598:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
 1599:     highlightend();
 1600:     return;
 1601:   }
 1602: 
 1603:   function highlightCentral() {
 1604: //    if (window.hwdWin) window.hwdWin.close();
 1605:     var xpos = (screen.width-400)/2;
 1606:     xpos = (xpos < 0) ? '0' : xpos;
 1607:     var ypos = (screen.height-330)/2-30;
 1608:     ypos = (ypos < 0) ? '0' : ypos;
 1609: 
 1610:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1611:     hwdWin.focus();
 1612:     var hDoc = hwdWin.document;
 1613:     hDoc.$docopen;
 1614:     hDoc.write('$start_page_highlight_central');
 1615:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1616:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
 1617: 
 1618:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1619:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1620:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
 1621:   }
 1622: 
 1623:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1624:     var hDoc = hwdWin.document;
 1625:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1626:     hDoc.write("<td align=\\"left\\">");
 1627:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
 1628:     hDoc.write("<td align=\\"left\\">");
 1629:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
 1630:     hDoc.write("<td align=\\"left\\">");
 1631:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
 1632:     hDoc.write("<\\/tr>");
 1633:   }
 1634: 
 1635:   function highlightend() { 
 1636:     var hDoc = hwdWin.document;
 1637:     hDoc.write("<\\/table>");
 1638:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1639:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
 1640:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
 1641:     hDoc.write("<\\/form>");
 1642:     hDoc.write('$end_page_highlight_central');
 1643:     hDoc.close();
 1644:   }
 1645: 
 1646: SUBJAVASCRIPT
 1647: }
 1648: 
 1649: sub get_increment {
 1650:     my $increment = $env{'form.increment'};
 1651:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1652:         $increment != .1) {
 1653:         $increment = 1;
 1654:     }
 1655:     return $increment;
 1656: }
 1657: 
 1658: sub gradeBox_start {
 1659:     return (
 1660:         &Apache::loncommon::start_data_table()
 1661:        .&Apache::loncommon::start_data_table_header_row()
 1662:        .'<th>'.&mt('Part').'</th>'
 1663:        .'<th>'.&mt('Points').'</th>'
 1664:        .'<th>&nbsp;</th>'
 1665:        .'<th>'.&mt('Assign Grade').'</th>'
 1666:        .'<th>'.&mt('Weight').'</th>'
 1667:        .'<th>'.&mt('Grade Status').'</th>'
 1668:        .&Apache::loncommon::end_data_table_header_row()
 1669:     );
 1670: }
 1671: 
 1672: sub gradeBox_end {
 1673:     return (
 1674:         &Apache::loncommon::end_data_table()
 1675:     );
 1676: }
 1677: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1678: sub gradeBox {
 1679:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1680:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1681: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1682:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1683:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1684:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1685:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1686:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1687: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1688:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1689:     my $display_part= &get_display_part($partid,$symb);
 1690:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1691: 				       [$partid]);
 1692:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1693:     if ($last_resets{$partid}) {
 1694:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1695:     }
 1696:     $result.=&Apache::loncommon::start_data_table_row();
 1697:     my $ctr = 0;
 1698:     my $thisweight = 0;
 1699:     my $increment = &get_increment();
 1700: 
 1701:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1702:     while ($thisweight<=$wgt) {
 1703: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1704:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1705: 	    $thisweight.')" value="'.$thisweight.'" '.
 1706: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1707: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1708:         $thisweight += $increment;
 1709: 	$ctr++;
 1710:     }
 1711:     $radio.='</tr></table>';
 1712: 
 1713:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1714: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1715: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1716: 	$wgt.')" /></td>'."\n";
 1717:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1718: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1719: 	' </td>'."\n";
 1720:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1721: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1722:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1723: 	$line.='<option></option>'.
 1724: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1725:     } else {
 1726: 	$line.='<option selected="selected"></option>'.
 1727: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1728:     }
 1729:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1730: 
 1731: 
 1732:     $result .= 
 1733: 	    '<td>'.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 1734:     $result.=&Apache::loncommon::end_data_table_row();
 1735:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1736: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1737: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1738: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1739:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1740:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1741:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1742:         $aggtries.'" />'."\n";
 1743:     my $res_error;
 1744:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 1745:     if ($res_error) {
 1746:         return &navmap_errormsg();
 1747:     }
 1748:     return $result;
 1749: }
 1750: 
 1751: sub handback_box {
 1752:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error) = @_;
 1753:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
 1754:     my (@respids);
 1755:      my @part_response_id = &flatten_responseType($responseType);
 1756:     foreach my $part_response_id (@part_response_id) {
 1757:     	my ($part,$resp) = @{ $part_response_id };
 1758:         if ($part eq $partid) {
 1759:             push(@respids,$resp);
 1760:         }
 1761:     }
 1762:     my $result;
 1763:     foreach my $respid (@respids) {
 1764: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1765: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1766: 	next if (!@$files);
 1767: 	my $file_counter = 1;
 1768: 	foreach my $file (@$files) {
 1769: 	    if ($file =~ /\/portfolio\//) {
 1770:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1771:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1772:     	        $file_disp = "$name.$ext";
 1773:     	        $file = $file_path.$file_disp;
 1774:     	        $result.=&mt('Return commented version of [_1] to student.',
 1775:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1776:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1777:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
 1778:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
 1779:     	        $file_counter++;
 1780: 	    }
 1781: 	}
 1782:     }
 1783:     return $result;    
 1784: }
 1785: 
 1786: sub show_problem {
 1787:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1788:     my $rendered;
 1789:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1790:     &Apache::lonxml::remember_problem_counter();
 1791:     if ($mode eq 'both' or $mode eq 'text') {
 1792: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1793: 						       $env{'request.course.id'},
 1794: 						       undef,\%form);
 1795:     }
 1796:     if ($removeform) {
 1797: 	$rendered=~s|<form(.*?)>||g;
 1798: 	$rendered=~s|</form>||g;
 1799: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1800:     }
 1801:     my $companswer;
 1802:     if ($mode eq 'both' or $mode eq 'answer') {
 1803: 	&Apache::lonxml::restore_problem_counter();
 1804: 	$companswer=
 1805: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1806: 						    $env{'request.course.id'},
 1807: 						    %form);
 1808:     }
 1809:     if ($removeform) {
 1810: 	$companswer=~s|<form(.*?)>||g;
 1811: 	$companswer=~s|</form>||g;
 1812: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1813:     }
 1814:     $rendered=
 1815:         '<div class="LC_Box">'
 1816:        .'<h3 class="LC_hcell">'.&mt('View of the problem').'</h3>'
 1817:        .$rendered
 1818:        .'</div>';
 1819:     $companswer=
 1820:         '<div class="LC_Box">'
 1821:        .'<h3 class="LC_hcell">'.&mt('Correct answer').'</h3>'
 1822:        .$companswer
 1823:        .'</div>';
 1824:     my $result;
 1825:     if ($mode eq 'both') {
 1826:         $result=$rendered.$companswer;
 1827:     } elsif ($mode eq 'text') {
 1828:         $result=$rendered;
 1829:     } elsif ($mode eq 'answer') {
 1830:         $result=$companswer;
 1831:     }
 1832:     return $result;
 1833: }
 1834: 
 1835: sub files_exist {
 1836:     my ($r, $symb) = @_;
 1837:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1838: 
 1839:     foreach my $student (@students) {
 1840:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1841:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1842: 					      $udom,$uname);
 1843:         my ($string,$timestamp)= &get_last_submission(\%record);
 1844:         foreach my $submission (@$string) {
 1845:             my ($partid,$respid) =
 1846: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1847:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1848: 					   \%record);
 1849:             return 1 if (@$files);
 1850:         }
 1851:     }
 1852:     return 0;
 1853: }
 1854: 
 1855: sub download_all_link {
 1856:     my ($r,$symb) = @_;
 1857:     my $all_students = 
 1858: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1859: 
 1860:     my $parts =
 1861: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1862: 
 1863:     my $identifier = &Apache::loncommon::get_cgi_id();
 1864:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 1865:                              'cgi.'.$identifier.'.symb' => $symb,
 1866:                              'cgi.'.$identifier.'.parts' => $parts,});
 1867:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1868: 	      &mt('Download All Submitted Documents').'</a>');
 1869:     return
 1870: }
 1871: 
 1872: sub build_section_inputs {
 1873:     my $section_inputs;
 1874:     if ($env{'form.section'} eq '') {
 1875:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 1876:     } else {
 1877:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 1878:         foreach my $section (@sections) {
 1879:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 1880:         }
 1881:     }
 1882:     return $section_inputs;
 1883: }
 1884: 
 1885: # --------------------------- show submissions of a student, option to grade 
 1886: sub submission {
 1887:     my ($request,$counter,$total,$symb) = @_;
 1888:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 1889:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 1890:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 1891:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 1892: 
 1893:     my $probtitle=&Apache::lonnet::gettitle($symb); 
 1894:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 1895: 
 1896:     if (!&canview($usec)) {
 1897: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
 1898: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
 1899: 			$env{'request.course.id'}.')</span>');
 1900: 	return;
 1901:     }
 1902: 
 1903:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 1904:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 1905:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 1906:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 1907:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1908: 	'" src="'.$request->dir_config('lonIconsURL').
 1909: 	'/check.gif" height="16" border="0" />';
 1910: 
 1911:     my %old_essays;
 1912:     # header info
 1913:     if ($counter == 0) {
 1914: 	&sub_page_js($request);
 1915: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
 1916: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
 1917: 	    &download_all_link($request, $symb);
 1918: 	}
 1919: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>');
 1920: 
 1921: 	# option to display problem, only once else it cause problems 
 1922:         # with the form later since the problem has a form.
 1923: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 1924: 	    my $mode;
 1925: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 1926: 		$mode='both';
 1927: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 1928: 		$mode='text';
 1929: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 1930: 		$mode='answer';
 1931: 	    }
 1932: 	    &Apache::lonxml::clear_problem_counter();
 1933: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 1934: 	}
 1935: 
 1936: 	# kwclr is the only variable that is guaranteed to be non blank 
 1937:         # if this subroutine has been called once.
 1938: 	my %keyhash = ();
 1939: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 1940: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 1941: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 1942: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 1943: 
 1944: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 1945: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 1946: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 1947: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 1948: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 1949: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 1950: 		$keyhash{$symb.'_subject'} : $probtitle;
 1951: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 1952: 	}
 1953: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 1954: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 1955: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 1956: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 1957: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 1958: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 1959: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 1960: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 1961: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 1962: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1963: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
 1964: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 1965: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 1966: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 1967: 			&build_section_inputs().
 1968: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 1969: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
 1970: 			'<input type="hidden" name="NCT"'.
 1971: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 1972: 	if ($env{'form.handgrade'} eq 'yes') {
 1973: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 1974: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 1975: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 1976: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 1977: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 1978: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 1979: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 1980: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 1981: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 1982: 	    }
 1983: 	}
 1984: 	
 1985: 	my ($cts,$prnmsg) = (1,'');
 1986: 	while ($cts <= $env{'form.savemsgN'}) {
 1987: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 1988: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 1989: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 1990: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 1991: 		'" />'."\n".
 1992: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 1993: 	    $cts++;
 1994: 	}
 1995: 	$request->print($prnmsg);
 1996: 
 1997: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
 1998: #
 1999: # Print out the keyword options line
 2000: #
 2001: 	    $request->print(<<KEYWORDS);
 2002: &nbsp;<b>Keyword Options:</b>&nbsp;
 2003: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
 2004: <a href="#" onmousedown="javascript:getSel(); return false"
 2005:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
 2006: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
 2007: KEYWORDS
 2008: #
 2009: # Load the other essays for similarity check
 2010: #
 2011:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2012: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2013: 	    $apath=&escape($apath);
 2014: 	    $apath=~s/\W/\_/gs;
 2015: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 2016:         }
 2017:     }
 2018: 
 2019: # This is where output for one specific student would start
 2020:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2021:     $request->print(
 2022:         "\n\n"
 2023:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2024:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2025:        ."\n"
 2026:     );
 2027: 
 2028:     # Show additional functions if allowed
 2029:     if ($perm{'vgr'}) {
 2030:         $request->print(
 2031:             &Apache::loncommon::track_student_link(
 2032:                 &mt('View recent activity'),
 2033:                 $uname,$udom,'check')
 2034:            .' '
 2035:         );
 2036:     }
 2037:     if ($perm{'opa'}) {
 2038:         $request->print(
 2039:             &Apache::loncommon::pprmlink(
 2040:                 &mt('Set/Change parameters'),
 2041:                 $uname,$udom,$symb,'check'));
 2042:     }
 2043: 
 2044:     # Show Problem
 2045:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2046: 	my $mode;
 2047: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2048: 	    $mode='both';
 2049: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2050: 	    $mode='text';
 2051: 	} elsif ($env{'form.vAns'} eq 'all') {
 2052: 	    $mode='answer';
 2053: 	}
 2054: 	&Apache::lonxml::clear_problem_counter();
 2055: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2056:     }
 2057: 
 2058:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2059:     my $res_error;
 2060:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2061:     if ($res_error) {
 2062:         $request->print(&navmap_errormsg());
 2063:         return;
 2064:     }
 2065: 
 2066:     # Display student info
 2067:     $request->print(($counter == 0 ? '' : '<br />'));
 2068: 
 2069:     my $result='<div class="LC_Box">'
 2070:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
 2071:     $result.='<input type="hidden" name="name'.$counter.
 2072:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2073:     if ($env{'form.handgrade'} eq 'no') {
 2074:         $result.='<p class="LC_info">'
 2075:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2076:                 ."</p>\n";
 2077:     }
 2078: 
 2079:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2080:     my $fullname;
 2081:     my $col_fullnames = [];
 2082:     if ($env{'form.handgrade'} eq 'yes') {
 2083: 	(my $sub_result,$fullname,$col_fullnames)=
 2084: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2085: 				 $counter);
 2086: 	$result.=$sub_result;
 2087:     }
 2088:     $request->print($result."\n");
 2089: 
 2090:     # print student answer/submission
 2091:     # Options are (1) Handgraded submission only
 2092:     #             (2) Last submission, includes submission that is not handgraded 
 2093:     #                  (for multi-response type part)
 2094:     #             (3) Last submission plus the parts info
 2095:     #             (4) The whole record for this student
 2096:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
 2097: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2098: 	
 2099: 	my $lastsubonly;
 2100: 
 2101:         if ($$timestamp eq '') {
 2102:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2103:         } else {
 2104:             $lastsubonly =
 2105:                 '<div class="LC_grade_submissions_body">'
 2106:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
 2107: 
 2108: 	    my %seenparts;
 2109: 	    my @part_response_id = &flatten_responseType($responseType);
 2110: 	    foreach my $part (@part_response_id) {
 2111: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2112: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2113: 
 2114: 		my ($partid,$respid) = @{ $part };
 2115: 		my $display_part=&get_display_part($partid,$symb);
 2116: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2117: 		    if (exists($seenparts{$partid})) { next; }
 2118: 		    $seenparts{$partid}=1;
 2119: 		    my $submitby='<b>Part:</b> '.$display_part.
 2120: 			' <b>Collaborative submission by:</b> '.
 2121: 			'<a href="javascript:viewSubmitter(\''.
 2122: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
 2123: 			'\');" target="_self">'.
 2124: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
 2125: 		    $request->print($submitby);
 2126: 		    next;
 2127: 		}
 2128: 		my $responsetype = $responseType->{$partid}->{$respid};
 2129: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2130:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2131:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2132:                         ' <span class="LC_internal_info">'.
 2133:                         '('.&mt('Part ID: [_1]',$respid).')'.
 2134:                         '</span>&nbsp; &nbsp;'.
 2135: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2136: 		    next;
 2137: 		}
 2138: 		foreach my $submission (@$string) {
 2139: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2140: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2141: 		    my ($ressub,$hide,$subval) = split(/:/,$submission,3);
 2142: 		    # Similarity check
 2143: 		    my $similar='';
 2144: 		    if($env{'form.checkPlag'}){
 2145: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2146: 			    &most_similar($uname,$udom,$subval,\%old_essays);
 2147: 			if ($osim) {
 2148: 			    $osim=int($osim*100.0);
 2149: 			    my %old_course_desc = 
 2150: 				&Apache::lonnet::coursedescription($ocrsid,
 2151: 								   {'one_time' => 1});
 2152: 
 2153:                             if ($hide) {
 2154:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2155:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2156:                             } else {
 2157: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
 2158: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2159: 				        $osim,
 2160: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2161: 				        $old_course_desc{'description'},
 2162: 				        $old_course_desc{'num'},
 2163: 				        $old_course_desc{'domain'}).
 2164: 				    '</span></h3><blockquote><i>'.
 2165: 				    &keywords_highlight($oessay).
 2166: 				    '</i></blockquote><hr />';
 2167:                             }
 2168: 			}
 2169: 		    }
 2170: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
 2171: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
 2172: 			($env{'form.lastSub'} eq 'hdgrade' && 
 2173: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2174: 			my $display_part=&get_display_part($partid,$symb);
 2175:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
 2176:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2177:                             ' <span class="LC_internal_info">'.
 2178:                             '('.&mt('Part ID: [_1]',$respid).')'.
 2179:                             '</span>&nbsp; &nbsp;';
 2180: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2181: 			if (@$files) {
 2182:                             if ($hide) {
 2183:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2184:                             } else {
 2185:                                 $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
 2186:                                 foreach my $file (@$files) {
 2187:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2188:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
 2189:                                 }
 2190:                             }
 2191: 			    $lastsubonly.='<br />';
 2192: 			}
 2193:                         if ($hide) {
 2194:                             $lastsubonly.='<b>'.&mt('Anonymous Survey').'</b>'; 
 2195:                         } else {
 2196: 			    $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
 2197: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
 2198: 					     $respid,\%record,$order,undef,$uname,$udom);
 2199:                         }
 2200: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2201: 			$lastsubonly.='</div>';
 2202: 		    }
 2203: 		}
 2204: 	    }
 2205: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2206: 	}
 2207: 	$request->print($lastsubonly);
 2208:    } elsif ($env{'form.lastSub'} eq 'datesub') {
 2209: #	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
 2210:     my ($parts,$handgrade,$responseType) = &response_type($symb);
 2211: 
 2212: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2213:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2214: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2215: 								 $env{'request.course.id'},
 2216: 								 $last,'.submission',
 2217: 								 'Apache::grades::keywords_highlight'));
 2218:     }
 2219: 
 2220:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2221: 	.$udom.'" />'."\n");
 2222:     # return if view submission with no grading option
 2223:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
 2224: 	my $toGrade.='<input type="button" value="Grade Student" '.
 2225: 	    'onclick="javascript:checksubmit(this.form,\'Grade Student\',\''
 2226: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
 2227: 	$toGrade.='</div>'."\n";
 2228: 	$request->print($toGrade);
 2229: 	return;
 2230:     } else {
 2231: 	$request->print('</div>'."\n");
 2232:     }
 2233: 
 2234:     # essay grading message center
 2235:     if ($env{'form.handgrade'} eq 'yes') {
 2236: 	my $result='<div class="LC_grade_message_center">';
 2237:     
 2238: 	$result.='<div class="LC_grade_message_center_header">'.
 2239: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2240: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2241: 	my $msgfor = $givenn.' '.$lastname;
 2242: 	if (scalar(@$col_fullnames) > 0) {
 2243: 	    my $lastone = pop(@$col_fullnames);
 2244: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2245: 	}
 2246: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2247: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2248: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2249: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2250: 	    ',\''.$msgfor.'\');" target="_self">'.
 2251: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
 2252: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2253: 	    '<img src="'.$request->dir_config('lonIconsURL').
 2254: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2255: 	    '<br />&nbsp;('.
 2256: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2257: 	$result.='</div></div>';
 2258: 	$request->print($result);
 2259:     }
 2260: 
 2261:     my %seen = ();
 2262:     my @partlist;
 2263:     my @gradePartRespid;
 2264:     my @part_response_id = &flatten_responseType($responseType);
 2265:     $request->print(
 2266:         '<div class="LC_Box">'
 2267:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2268:     );
 2269:     $request->print(&gradeBox_start());
 2270:     foreach my $part_response_id (@part_response_id) {
 2271:     	my ($partid,$respid) = @{ $part_response_id };
 2272: 	my $part_resp = join('_',@{ $part_response_id });
 2273: 	next if ($seen{$partid} > 0);
 2274: 	$seen{$partid}++;
 2275: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2276: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2277: 	push(@partlist,$partid);
 2278: 	push(@gradePartRespid,$partid.'.'.$respid);
 2279: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2280:     }
 2281:     $request->print(&gradeBox_end()); # </div>
 2282:     $request->print('</div>');
 2283: 
 2284:     $request->print('<div class="LC_grade_info_links">');
 2285:     $request->print('</div>');
 2286: 
 2287:     $result='<input type="hidden" name="partlist'.$counter.
 2288: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2289:     $result.='<input type="hidden" name="gradePartRespid'.
 2290: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2291:     my $ctr = 0;
 2292:     while ($ctr < scalar(@partlist)) {
 2293: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2294: 	    $partlist[$ctr].'" />'."\n";
 2295: 	$ctr++;
 2296:     }
 2297:     $request->print($result.''."\n");
 2298: 
 2299: # Done with printing info for one student
 2300: 
 2301:     $request->print('</div>');#LC_grade_show_user
 2302: 
 2303: 
 2304:     # print end of form
 2305:     if ($counter == $total) {
 2306:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2307: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2308: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2309: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2310: 	my $ntstu ='<select name="NTSTU">'.
 2311: 	    '<option>1</option><option>2</option>'.
 2312: 	    '<option>3</option><option>5</option>'.
 2313: 	    '<option>7</option><option>10</option></select>'."\n";
 2314: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2315: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2316:         $endform.=&mt('[_1]student(s)',$ntstu);
 2317: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2318: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2319: 	    '<input type="button" value="'.&mt('Next').'" '.
 2320: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2321:         $endform.='<span class="LC_warning">'.
 2322:                   &mt('(Next and Previous (student) do not save the scores.)').
 2323:                   '</span>'."\n" ;
 2324:         $endform.="<input type='hidden' value='".&get_increment().
 2325:             "' name='increment' />";
 2326: 	$endform.='</td></tr></table></form>';
 2327: 	$request->print($endform);
 2328:     }
 2329:     return '';
 2330: }
 2331: 
 2332: sub check_collaborators {
 2333:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2334:     my ($result,@col_fullnames);
 2335:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2336:     foreach my $part (keys(%$handgrade)) {
 2337: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2338: 					'.maxcollaborators',
 2339: 					$symb,$udom,$uname);
 2340: 	next if ($ncol <= 0);
 2341: 	$part =~ s/\_/\./g;
 2342: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2343: 	my (@good_collaborators, @bad_collaborators);
 2344: 	foreach my $possible_collaborator
 2345: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2346: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2347: 	    next if ($possible_collaborator eq '');
 2348: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
 2349: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2350: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2351: 	    # Doing this grep allows 'fuzzy' specification
 2352: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2353: 			       keys(%$classlist));
 2354: 	    if (! scalar(@matches)) {
 2355: 		push(@bad_collaborators, $possible_collaborator);
 2356: 	    } else {
 2357: 		push(@good_collaborators, @matches);
 2358: 	    }
 2359: 	}
 2360: 	if (scalar(@good_collaborators) != 0) {
 2361: 	    $result.='<br />'.&mt('Collaborators: ');
 2362: 	    foreach my $name (@good_collaborators) {
 2363: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2364: 		push(@col_fullnames, $givenn.' '.$lastname);
 2365: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
 2366: 	    }
 2367: 	    $result.='<br />'."\n";
 2368: 	    my ($part)=split(/\./,$part);
 2369: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2370: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2371: 		"\n";
 2372: 	}
 2373: 	if (scalar(@bad_collaborators) > 0) {
 2374: 	    $result.='<div class="LC_warning">';
 2375: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2376: 	    $result .= '</div>';
 2377: 	}         
 2378: 	if (scalar(@bad_collaborators > $ncol)) {
 2379: 	    $result .= '<div class="LC_warning">';
 2380: 	    $result .= &mt('This student has submitted too many '.
 2381: 		'collaborators.  Maximum is [_1].',$ncol);
 2382: 	    $result .= '</div>';
 2383: 	}
 2384:     }
 2385:     return ($result,$fullname,\@col_fullnames);
 2386: }
 2387: 
 2388: #--- Retrieve the last submission for all the parts
 2389: sub get_last_submission {
 2390:     my ($returnhash)=@_;
 2391:     my (@string,$timestamp,%lasthidden);
 2392:     if ($$returnhash{'version'}) {
 2393: 	my %lasthash=();
 2394: 	my ($version);
 2395: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2396: 	    foreach my $key (sort(split(/\:/,
 2397: 					$$returnhash{$version.':keys'}))) {
 2398: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2399: 		$timestamp = 
 2400: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2401: 	    }
 2402: 	}
 2403:         my %typeparts;
 2404:         my $showsurv = 
 2405:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2406:         foreach my $key (sort(keys(%lasthash))) {
 2407:             if ($key =~ /\.type$/) {
 2408:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2409:                     ($lasthash{$key} eq 'anonsurveycred')) {
 2410:                     my ($ign,@parts) = split(/\./,$key);
 2411:                     pop(@parts);
 2412:                     unless ($showsurv) {
 2413:                         my $id = join(',',@parts);
 2414:                         $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2415:                     }
 2416:                     delete($lasthash{$key});
 2417:                 }
 2418:             }
 2419:         }
 2420:         my @hidden = keys(%typeparts);
 2421: 	foreach my $key (keys(%lasthash)) {
 2422: 	    next if ($key !~ /\.submission$/);
 2423:             my $hide;
 2424:             if (@hidden) {
 2425:                 foreach my $id (@hidden) {
 2426:                     if ($key =~ /^\Q$id\E/) {
 2427:                         $hide = 1;
 2428:                         last;
 2429:                     }
 2430:                 }
 2431:             }
 2432: 	    my ($partid,$foo) = split(/submission$/,$key);
 2433: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 2434: 		'<span class="LC_warning">Draft Copy</span> ' : '';
 2435: 	    push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
 2436: 	}
 2437:     }
 2438:     if (!@string) {
 2439: 	$string[0] =
 2440: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2441:     }
 2442:     return (\@string,\$timestamp);
 2443: }
 2444: 
 2445: #--- High light keywords, with style choosen by user.
 2446: sub keywords_highlight {
 2447:     my $string    = shift;
 2448:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2449:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2450:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2451:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2452:     foreach my $keyword (@keylist) {
 2453: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2454:     }
 2455:     return $string;
 2456: }
 2457: 
 2458: #--- Called from submission routine
 2459: sub processHandGrade {
 2460:     my ($request,$symb) = @_;
 2461:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2462:     my $button = $env{'form.gradeOpt'};
 2463:     my $ngrade = $env{'form.NCT'};
 2464:     my $ntstu  = $env{'form.NTSTU'};
 2465:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2466:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2467: 
 2468:     if ($button eq 'Save & Next') {
 2469: 	my $ctr = 0;
 2470: 	while ($ctr < $ngrade) {
 2471: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2472: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2473: 	    if ($errorflag eq 'no_score') {
 2474: 		$ctr++;
 2475: 		next;
 2476: 	    }
 2477: 	    if ($errorflag eq 'not_allowed') {
 2478: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
 2479: 		$ctr++;
 2480: 		next;
 2481: 	    }
 2482: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2483: 	    my ($subject,$message,$msgstatus) = ('','','');
 2484: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2485:             my ($feedurl,$showsymb) =
 2486: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2487: 	    my $messagetail;
 2488: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2489: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2490: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2491: 		$subject.=' ['.$restitle.']';
 2492: 		my (@msgnum) = split(/,/,$includemsg);
 2493: 		foreach (@msgnum) {
 2494: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2495: 		}
 2496: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2497: 		if ($env{'form.withgrades'.$ctr}) {
 2498: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2499: 		    $messagetail = " for <a href=\"".
 2500: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
 2501: 		}
 2502: 		$msgstatus = 
 2503:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2504: 						     $message.$messagetail,
 2505:                                                      undef,$feedurl,undef,
 2506:                                                      undef,undef,$showsymb,
 2507:                                                      $restitle);
 2508: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 2509: 				$msgstatus);
 2510: 	    }
 2511: 	    if ($env{'form.collaborator'.$ctr}) {
 2512: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2513: 		foreach my $collabstr (@collabstrs) {
 2514: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2515: 		    foreach my $collaborator (@collaborators) {
 2516: 			my ($errorflag,$pts,$wgt) = 
 2517: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2518: 					   $env{'form.unamedom'.$ctr},$part);
 2519: 			if ($errorflag eq 'not_allowed') {
 2520: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2521: 			    next;
 2522: 			} elsif ($message ne '') {
 2523: 			    my ($baseurl,$showsymb) = 
 2524: 				&get_feedurl_and_symb($symb,$collaborator,
 2525: 						      $udom);
 2526: 			    if ($env{'form.withgrades'.$ctr}) {
 2527: 				$messagetail = " for <a href=\"".
 2528:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
 2529: 			    }
 2530: 			    $msgstatus = 
 2531: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2532: 			}
 2533: 		    }
 2534: 		}
 2535: 	    }
 2536: 	    $ctr++;
 2537: 	}
 2538:     }
 2539: 
 2540:     if ($env{'form.handgrade'} eq 'yes') {
 2541: 	# Keywords sorted in alphabatical order
 2542: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2543: 	my %keyhash = ();
 2544: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2545: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2546: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2547: 	$env{'form.keywords'} = join(' ',@keywords);
 2548: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2549: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2550: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2551: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2552: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2553: 
 2554: 	# message center - Order of message gets changed. Blank line is eliminated.
 2555: 	# New messages are saved in env for the next student.
 2556: 	# All messages are saved in nohist_handgrade.db
 2557: 	my ($ctr,$idx) = (1,1);
 2558: 	while ($ctr <= $env{'form.savemsgN'}) {
 2559: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2560: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2561: 		$idx++;
 2562: 	    }
 2563: 	    $ctr++;
 2564: 	}
 2565: 	$ctr = 0;
 2566: 	while ($ctr < $ngrade) {
 2567: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2568: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2569: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2570: 		$idx++;
 2571: 	    }
 2572: 	    $ctr++;
 2573: 	}
 2574: 	$env{'form.savemsgN'} = --$idx;
 2575: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2576: 	my $putresult = &Apache::lonnet::put
 2577: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2578:     }
 2579:     # Called by Save & Refresh from Highlight Attribute Window
 2580:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2581:     if ($env{'form.refresh'} eq 'on') {
 2582: 	my ($ctr,$total) = (0,0);
 2583: 	while ($ctr < $ngrade) {
 2584: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2585: 	    $ctr++;
 2586: 	}
 2587: 	$env{'form.NTSTU'}=$ngrade;
 2588: 	$ctr = 0;
 2589: 	while ($ctr < $total) {
 2590: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2591: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2592: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2593: 	    &submission($request,$ctr,$total-1);
 2594: 	    $ctr++;
 2595: 	}
 2596: 	return '';
 2597:     }
 2598: 
 2599: # Go directly to grade student - from submission or link from chart page
 2600:     if ($button eq 'Grade Student') {
 2601: #	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
 2602: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
 2603: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2604: 	$env{'form.fullname'} = $$fullname{$processUser};
 2605: 	&submission($request,0,0);
 2606: 	return '';
 2607:     }
 2608: 
 2609:     # Get the next/previous one or group of students
 2610:     my $firststu = $env{'form.unamedom0'};
 2611:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2612:     my $ctr = 2;
 2613:     while ($laststu eq '') {
 2614: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2615: 	$ctr++;
 2616: 	$laststu = $firststu if ($ctr > $ngrade);
 2617:     }
 2618: 
 2619:     my (@parsedlist,@nextlist);
 2620:     my ($nextflg) = 0;
 2621:     foreach my $item (sort 
 2622: 	     {
 2623: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2624: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2625: 		 }
 2626: 		 return $a cmp $b;
 2627: 	     } (keys(%$fullname))) {
 2628: # FIXME: this is fishy, looks like the button label
 2629: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2630: 	    push(@parsedlist,$item);
 2631: 	}
 2632: 	$nextflg = 1 if ($item eq $laststu);
 2633: 	if ($button eq 'Previous') {
 2634: 	    last if ($item eq $firststu);
 2635: 	    push(@parsedlist,$item);
 2636: 	}
 2637:     }
 2638:     $ctr = 0;
 2639: # FIXME: this is fishy, looks like the button label
 2640:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2641:     my $res_error;
 2642:     my ($partlist) = &response_type($symb,\$res_error);
 2643:     if ($res_error) {
 2644:         $request->print(&navmap_errormsg());
 2645:         return;
 2646:     }
 2647:     foreach my $student (@parsedlist) {
 2648: 	my $submitonly=$env{'form.submitonly'};
 2649: 	my ($uname,$udom) = split(/:/,$student);
 2650: 	
 2651: 	if ($submitonly eq 'queued') {
 2652: 	    my %queue_status = 
 2653: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2654: 							$udom,$uname);
 2655: 	    next if (!defined($queue_status{'gradingqueue'}));
 2656: 	}
 2657: 
 2658: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2659: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2660: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2661: 	    my $submitted = 0;
 2662: 	    my $ungraded = 0;
 2663: 	    my $incorrect = 0;
 2664: 	    foreach my $item (keys(%status)) {
 2665: 		$submitted = 1 if ($status{$item} ne 'nothing');
 2666: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 2667: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 2668: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 2669: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2670: 		    $submitted = 0;
 2671: 		}
 2672: 	    }
 2673: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2674: 				     $submitonly eq 'incorrect' ||
 2675: 				     $submitonly eq 'graded'));
 2676: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2677: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2678: 	}
 2679: 	push(@nextlist,$student) if ($ctr < $ntstu);
 2680: 	last if ($ctr == $ntstu);
 2681: 	$ctr++;
 2682:     }
 2683: 
 2684:     $ctr = 0;
 2685:     my $total = scalar(@nextlist)-1;
 2686: 
 2687:     foreach (sort(@nextlist)) {
 2688: 	my ($uname,$udom,$submitter) = split(/:/);
 2689: 	$env{'form.student'}  = $uname;
 2690: 	$env{'form.userdom'}  = $udom;
 2691: 	$env{'form.fullname'} = $$fullname{$_};
 2692: 	&submission($request,$ctr,$total);
 2693: 	$ctr++;
 2694:     }
 2695:     if ($total < 0) {
 2696: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
 2697: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
 2698: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
 2699: 	$request->print($the_end);
 2700:     }
 2701:     return '';
 2702: }
 2703: 
 2704: #---- Save the score and award for each student, if changed
 2705: sub saveHandGrade {
 2706:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 2707:     my @version_parts;
 2708:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 2709: 					   $env{'request.course.id'});
 2710:     if (!&canmodify($usec)) { return('not_allowed'); }
 2711:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 2712:     my @parts_graded;
 2713:     my %newrecord  = ();
 2714:     my ($pts,$wgt) = ('','');
 2715:     my %aggregate = ();
 2716:     my $aggregateflag = 0;
 2717:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 2718:     foreach my $new_part (@parts) {
 2719: 	#collaborator ($submi may vary for different parts
 2720: 	if ($submitter && $new_part ne $part) { next; }
 2721: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 2722: 	if ($dropMenu eq 'excused') {
 2723: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 2724: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 2725: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 2726: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 2727: 		}
 2728: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 2729: 	    }
 2730: 	} elsif ($dropMenu eq 'reset status'
 2731: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 2732: 	    foreach my $key (keys(%record)) {
 2733: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 2734: 	    }
 2735: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2736: 		"$env{'user.name'}:$env{'user.domain'}";
 2737:             my $totaltries = $record{'resource.'.$part.'.tries'};
 2738: 
 2739:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2740: 					       [$new_part]);
 2741:             my $aggtries =$totaltries;
 2742:             if ($last_resets{$new_part}) {
 2743:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 2744: 					   $new_part);
 2745:             }
 2746: 
 2747:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 2748:             if ($aggtries > 0) {
 2749:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 2750:                 $aggregateflag = 1;
 2751:             }
 2752: 	} elsif ($dropMenu eq '') {
 2753: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 2754: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 2755: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 2756: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 2757: 		next;
 2758: 	    }
 2759: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 2760: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 2761: 	    my $partial= $pts/$wgt;
 2762: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 2763: 		#do not update score for part if not changed.
 2764:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 2765: 		next;
 2766: 	    } else {
 2767: 	        push(@parts_graded,$new_part);
 2768: 	    }
 2769: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 2770: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 2771: 	    }
 2772: 	    my $reckey = 'resource.'.$new_part.'.solved';
 2773: 	    if ($partial == 0) {
 2774: 		if ($record{$reckey} ne 'incorrect_by_override') {
 2775: 		    $newrecord{$reckey} = 'incorrect_by_override';
 2776: 		}
 2777: 	    } else {
 2778: 		if ($record{$reckey} ne 'correct_by_override') {
 2779: 		    $newrecord{$reckey} = 'correct_by_override';
 2780: 		}
 2781: 	    }	    
 2782: 	    if ($submitter && 
 2783: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 2784: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 2785: 	    }
 2786: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2787: 		"$env{'user.name'}:$env{'user.domain'}";
 2788: 	}
 2789: 	# unless problem has been graded, set flag to version the submitted files
 2790: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 2791: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 2792: 	        $dropMenu eq 'reset status')
 2793: 	   {
 2794: 	    push(@version_parts,$new_part);
 2795: 	}
 2796:     }
 2797:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2798:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2799: 
 2800:     if (%newrecord) {
 2801:         if (@version_parts) {
 2802:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 2803:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 2804: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 2805: 	    foreach my $new_part (@version_parts) {
 2806: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 2807: 				$new_part,\%newrecord);
 2808: 	    }
 2809:         }
 2810: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 2811: 				$env{'request.course.id'},$domain,$stuname);
 2812: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 2813: 				     $cdom,$cnum,$domain,$stuname);
 2814:     }
 2815:     if ($aggregateflag) {
 2816:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 2817: 			      $cdom,$cnum);
 2818:     }
 2819:     return ('',$pts,$wgt);
 2820: }
 2821: 
 2822: sub check_and_remove_from_queue {
 2823:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 2824:     my @ungraded_parts;
 2825:     foreach my $part (@{$parts}) {
 2826: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 2827: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 2828: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 2829: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 2830: 		) {
 2831: 	    push(@ungraded_parts, $part);
 2832: 	}
 2833:     }
 2834:     if ( !@ungraded_parts ) {
 2835: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 2836: 					       $cnum,$domain,$stuname);
 2837:     }
 2838: }
 2839: 
 2840: sub handback_files {
 2841:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 2842:     my $portfolio_root = '/userfiles/portfolio';
 2843:     my $res_error;
 2844:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2845:     if ($res_error) {
 2846:         $request->print('<br />'.&navmap_errormsg().'<br />');
 2847:         return;
 2848:     }
 2849:     my @part_response_id = &flatten_responseType($responseType);
 2850:     foreach my $part_response_id (@part_response_id) {
 2851:     	my ($part_id,$resp_id) = @{ $part_response_id };
 2852: 	my $part_resp = join('_',@{ $part_response_id });
 2853:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
 2854:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 2855:                 my $file_counter = 1;
 2856: 		my $file_msg;
 2857:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
 2858:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
 2859:                     my ($directory,$answer_file) = 
 2860:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
 2861:                     my ($answer_name,$answer_ver,$answer_ext) =
 2862: 		        &file_name_version_ext($answer_file);
 2863: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 2864:                     my $getpropath = 1;
 2865: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
 2866: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2867:                     # fix file name
 2868:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 2869:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 2870:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
 2871:             	                                $save_file_name);
 2872:                     if ($result !~ m|^/uploaded/|) {
 2873:                         $request->print('<br /><span class="LC_error">'.
 2874:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 2875:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
 2876:                                         '</span>');
 2877:                     } else {
 2878:                         # mark the file as read only
 2879:                         my @files = ($save_file_name);
 2880:                         my @what = ($symb,$env{'request.course.id'},'handback');
 2881:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
 2882: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 2883: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 2884: 			}
 2885:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 2886: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
 2887: 
 2888:                     }
 2889:                     $request->print("<br />".$fname." will be the uploaded file name");
 2890:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
 2891:                     $file_counter++;
 2892:                 }
 2893: 		my $subject = "File Handed Back by Instructor ";
 2894: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
 2895: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
 2896: 		$message .= ' The returned file(s) are named: '. $file_msg;
 2897: 		$message .= " and can be found in your portfolio space.";
 2898: 		my ($feedurl,$showsymb) = 
 2899: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
 2900:                 my $restitle = &Apache::lonnet::gettitle($symb);
 2901: 		my $msgstatus = 
 2902:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
 2903: 			 ' (File Returned) ['.$restitle.']',$message,undef,
 2904:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
 2905:             }
 2906:         }
 2907:     return;
 2908: }
 2909: 
 2910: sub get_feedurl_and_symb {
 2911:     my ($symb,$uname,$udom) = @_;
 2912:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2913:     $url = &Apache::lonnet::clutter($url);
 2914:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 2915: 					$symb,$udom,$uname);
 2916:     if ($encrypturl =~ /^yes$/i) {
 2917: 	&Apache::lonenc::encrypted(\$url,1);
 2918: 	&Apache::lonenc::encrypted(\$symb,1);
 2919:     }
 2920:     return ($url,$symb);
 2921: }
 2922: 
 2923: sub get_submitted_files {
 2924:     my ($udom,$uname,$partid,$respid,$record) = @_;
 2925:     my @files;
 2926:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 2927:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 2928:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 2929:     	    push(@files,$file_url.$file);
 2930:         }
 2931:     }
 2932:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 2933:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 2934:     }
 2935:     return (\@files);
 2936: }
 2937: 
 2938: # ----------- Provides number of tries since last reset.
 2939: sub get_num_tries {
 2940:     my ($record,$last_reset,$part) = @_;
 2941:     my $timestamp = '';
 2942:     my $num_tries = 0;
 2943:     if ($$record{'version'}) {
 2944:         for (my $version=$$record{'version'};$version>=1;$version--) {
 2945:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 2946:                 $timestamp = $$record{$version.':timestamp'};
 2947:                 if ($timestamp > $last_reset) {
 2948:                     $num_tries ++;
 2949:                 } else {
 2950:                     last;
 2951:                 }
 2952:             }
 2953:         }
 2954:     }
 2955:     return $num_tries;
 2956: }
 2957: 
 2958: # ----------- Determine decrements required in aggregate totals 
 2959: sub decrement_aggs {
 2960:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 2961:     my %decrement = (
 2962:                         attempts => 0,
 2963:                         users => 0,
 2964:                         correct => 0
 2965:                     );
 2966:     $decrement{'attempts'} = $aggtries;
 2967:     if ($solvedstatus =~ /^correct/) {
 2968:         $decrement{'correct'} = 1;
 2969:     }
 2970:     if ($aggtries == $totaltries) {
 2971:         $decrement{'users'} = 1;
 2972:     }
 2973:     foreach my $type (keys(%decrement)) {
 2974:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 2975:     }
 2976:     return;
 2977: }
 2978: 
 2979: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 2980: sub get_last_resets {
 2981:     my ($symb,$courseid,$partids) =@_;
 2982:     my %last_resets;
 2983:     my $cdom = $env{'course.'.$courseid.'.domain'};
 2984:     my $cname = $env{'course.'.$courseid.'.num'};
 2985:     my @keys;
 2986:     foreach my $part (@{$partids}) {
 2987: 	push(@keys,"$symb\0$part\0resettime");
 2988:     }
 2989:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 2990: 				     $cdom,$cname);
 2991:     foreach my $part (@{$partids}) {
 2992: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 2993:     }
 2994:     return %last_resets;
 2995: }
 2996: 
 2997: # ----------- Handles creating versions for portfolio files as answers
 2998: sub version_portfiles {
 2999:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3000:     my $version_parts = join('|',@$v_flag);
 3001:     my @returned_keys;
 3002:     my $parts = join('|', @$parts_graded);
 3003:     my $portfolio_root = '/userfiles/portfolio';
 3004:     foreach my $key (keys(%$record)) {
 3005:         my $new_portfiles;
 3006:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3007:             my @versioned_portfiles;
 3008:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3009:             foreach my $file (@portfiles) {
 3010:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 3011:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 3012: 		my ($answer_name,$answer_ver,$answer_ext) =
 3013: 		    &file_name_version_ext($answer_file);
 3014:                 my $getpropath = 1;    
 3015:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
 3016:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 3017:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 3018:                 if ($new_answer ne 'problem getting file') {
 3019:                     push(@versioned_portfiles, $directory.$new_answer);
 3020:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 3021:                         [$directory.$new_answer],
 3022:                         [$symb,$env{'request.course.id'},'graded']);
 3023:                 }
 3024:             }
 3025:             $$record{$key} = join(',',@versioned_portfiles);
 3026:             push(@returned_keys,$key);
 3027:         }
 3028:     } 
 3029:     return (@returned_keys);   
 3030: }
 3031: 
 3032: sub get_next_version {
 3033:     my ($answer_name, $answer_ext, $dir_list) = @_;
 3034:     my $version;
 3035:     foreach my $row (@$dir_list) {
 3036:         my ($file) = split(/\&/,$row,2);
 3037:         my ($file_name,$file_version,$file_ext) =
 3038: 	    &file_name_version_ext($file);
 3039:         if (($file_name eq $answer_name) && 
 3040: 	    ($file_ext eq $answer_ext)) {
 3041:                 # gets here if filename and extension match, regardless of version
 3042:                 if ($file_version ne '') {
 3043:                 # a versioned file is found  so save it for later
 3044:                 if ($file_version > $version) {
 3045: 		    $version = $file_version;
 3046: 	        }
 3047:             }
 3048:         }
 3049:     } 
 3050:     $version ++;
 3051:     return($version);
 3052: }
 3053: 
 3054: sub version_selected_portfile {
 3055:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3056:     my ($answer_name,$answer_ver,$answer_ext) =
 3057:         &file_name_version_ext($file_name);
 3058:     my $new_answer;
 3059:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3060:     if($env{'form.copy'} eq '-1') {
 3061:         $new_answer = 'problem getting file';
 3062:     } else {
 3063:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3064:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3065:                             $stu_name,$domain,'copy',
 3066: 		        '/portfolio'.$directory.$new_answer);
 3067:     }    
 3068:     return ($new_answer);
 3069: }
 3070: 
 3071: sub file_name_version_ext {
 3072:     my ($file)=@_;
 3073:     my @file_parts = split(/\./, $file);
 3074:     my ($name,$version,$ext);
 3075:     if (@file_parts > 1) {
 3076: 	$ext=pop(@file_parts);
 3077: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3078: 	    $version=pop(@file_parts);
 3079: 	}
 3080: 	$name=join('.',@file_parts);
 3081:     } else {
 3082: 	$name=join('.',@file_parts);
 3083:     }
 3084:     return($name,$version,$ext);
 3085: }
 3086: 
 3087: #--------------------------------------------------------------------------------------
 3088: #
 3089: #-------------------------- Next few routines handles grading by section or whole class
 3090: #
 3091: #--- Javascript to handle grading by section or whole class
 3092: sub viewgrades_js {
 3093:     my ($request) = shift;
 3094: 
 3095:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3096:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
 3097:    function writePoint(partid,weight,point) {
 3098: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3099: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3100: 	if (point == "textval") {
 3101: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3102: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3103: 		alert("$alertmsg"+parseFloat(point));
 3104: 		var resetbox = false;
 3105: 		for (var i=0; i<radioButton.length; i++) {
 3106: 		    if (radioButton[i].checked) {
 3107: 			textbox.value = i;
 3108: 			resetbox = true;
 3109: 		    }
 3110: 		}
 3111: 		if (!resetbox) {
 3112: 		    textbox.value = "";
 3113: 		}
 3114: 		return;
 3115: 	    }
 3116: 	    if (parseFloat(point) > parseFloat(weight)) {
 3117: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3118: 				   ") greater than the weight for the part. Accept?");
 3119: 		if (resp == false) {
 3120: 		    textbox.value = "";
 3121: 		    return;
 3122: 		}
 3123: 	    }
 3124: 	    for (var i=0; i<radioButton.length; i++) {
 3125: 		radioButton[i].checked=false;
 3126: 		if (parseFloat(point) == i) {
 3127: 		    radioButton[i].checked=true;
 3128: 		}
 3129: 	    }
 3130: 
 3131: 	} else {
 3132: 	    textbox.value = parseFloat(point);
 3133: 	}
 3134: 	for (i=0;i<document.classgrade.total.value;i++) {
 3135: 	    var user = document.classgrade["ctr"+i].value;
 3136: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3137: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3138: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3139: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3140: 	    if (saveval != "correct") {
 3141: 		scorename.value = point;
 3142: 		if (selname[0].selected != true) {
 3143: 		    selname[0].selected = true;
 3144: 		}
 3145: 	    }
 3146: 	}
 3147: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3148:     }
 3149: 
 3150:     function writeRadText(partid,weight) {
 3151: 	var selval   = document.classgrade["SELVAL_"+partid];
 3152: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3153:         var override = document.classgrade["FORCE_"+partid].checked;
 3154: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3155: 	if (selval[1].selected || selval[2].selected) {
 3156: 	    for (var i=0; i<radioButton.length; i++) {
 3157: 		radioButton[i].checked=false;
 3158: 
 3159: 	    }
 3160: 	    textbox.value = "";
 3161: 
 3162: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3163: 		var user = document.classgrade["ctr"+i].value;
 3164: 		user = user.replace(new RegExp(':', 'g'),"_");
 3165: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3166: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3167: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3168: 		if ((saveval != "correct") || override) {
 3169: 		    scorename.value = "";
 3170: 		    if (selval[1].selected) {
 3171: 			selname[1].selected = true;
 3172: 		    } else {
 3173: 			selname[2].selected = true;
 3174: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3175: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3176: 		    }
 3177: 		}
 3178: 	    }
 3179: 	} else {
 3180: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3181: 		var user = document.classgrade["ctr"+i].value;
 3182: 		user = user.replace(new RegExp(':', 'g'),"_");
 3183: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3184: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3185: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3186: 		if ((saveval != "correct") || override) {
 3187: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3188: 		    selname[0].selected = true;
 3189: 		}
 3190: 	    }
 3191: 	}	    
 3192:     }
 3193: 
 3194:     function changeSelect(partid,user) {
 3195: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3196: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3197: 	var point  = textbox.value;
 3198: 	var weight = document.classgrade["weight_"+partid].value;
 3199: 
 3200: 	if (isNaN(point) || parseFloat(point) < 0) {
 3201: 	    alert("$alertmsg"+parseFloat(point));
 3202: 	    textbox.value = "";
 3203: 	    return;
 3204: 	}
 3205: 	if (parseFloat(point) > parseFloat(weight)) {
 3206: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3207: 			       ") greater than the weight of the part. Accept?");
 3208: 	    if (resp == false) {
 3209: 		textbox.value = "";
 3210: 		return;
 3211: 	    }
 3212: 	}
 3213: 	selval[0].selected = true;
 3214:     }
 3215: 
 3216:     function changeOneScore(partid,user) {
 3217: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3218: 	if (selval[1].selected || selval[2].selected) {
 3219: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3220: 	    if (selval[2].selected) {
 3221: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3222: 	    }
 3223:         }
 3224:     }
 3225: 
 3226:     function resetEntry(numpart) {
 3227: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3228: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3229: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3230: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3231: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3232: 	    for (var i=0; i<radioButton.length; i++) {
 3233: 		radioButton[i].checked=false;
 3234: 
 3235: 	    }
 3236: 	    textbox.value = "";
 3237: 	    selval[0].selected = true;
 3238: 
 3239: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3240: 		var user = document.classgrade["ctr"+i].value;
 3241: 		user = user.replace(new RegExp(':', 'g'),"_");
 3242: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3243: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3244: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3245: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3246: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3247: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3248: 		if (saveselval == "excused") {
 3249: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3250: 		} else {
 3251: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3252: 		}
 3253: 	    }
 3254: 	}
 3255:     }
 3256: 
 3257: VIEWJAVASCRIPT
 3258: }
 3259: 
 3260: #--- show scores for a section or whole class w/ option to change/update a score
 3261: sub viewgrades {
 3262:     my ($request,$symb) = @_;
 3263:     &viewgrades_js($request);
 3264: 
 3265:     #need to make sure we have the correct data for later EXT calls, 
 3266:     #thus invalidate the cache
 3267:     &Apache::lonnet::devalidatecourseresdata(
 3268:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3269:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3270:     &Apache::lonnet::clear_EXT_cache_status();
 3271: 
 3272:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3273: 
 3274:     #view individual student submission form - called using Javascript viewOneStudent
 3275:     $result.=&jscriptNform($symb);
 3276: 
 3277:     #beginning of class grading form
 3278:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3279:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3280: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3281: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3282: 	&build_section_inputs().
 3283: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3284: 
 3285:     my ($common_header,$specific_header);
 3286:     if ($env{'form.section'} eq 'all') {
 3287: 	$common_header = &mt('Assign Common Grade to Class');
 3288:         $specific_header = &mt('Assign Grade to Specific Students in Class');
 3289:     } elsif ($env{'form.section'} eq 'none') {
 3290:         $common_header = &mt('Assign Common Grade to Students in no Section');
 3291: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
 3292:     } else {
 3293:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3294:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3295: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3296:     }
 3297:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
 3298:     #radio buttons/text box for assigning points for a section or class.
 3299:     #handles different parts of a problem
 3300:     my $res_error;
 3301:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3302:     if ($res_error) {
 3303:         return &navmap_errormsg();
 3304:     }
 3305:     my %weight = ();
 3306:     my $ctsparts = 0;
 3307:     my %seen = ();
 3308:     my @part_response_id = &flatten_responseType($responseType);
 3309:     foreach my $part_response_id (@part_response_id) {
 3310:     	my ($partid,$respid) = @{ $part_response_id };
 3311: 	my $part_resp = join('_',@{ $part_response_id });
 3312: 	next if $seen{$partid};
 3313: 	$seen{$partid}++;
 3314: 	my $handgrade=$$handgrade{$part_resp};
 3315: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3316: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3317: 
 3318: 	my $display_part=&get_display_part($partid,$symb);
 3319: 	my $radio.='<table border="0"><tr>';  
 3320: 	my $ctr = 0;
 3321: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3322: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3323: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3324: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3325: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3326: 	    $ctr++;
 3327: 	}
 3328: 	$radio.='</tr></table>';
 3329: 	my $line = '<input type="text" name="TEXTVAL_'.
 3330: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 3331: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3332: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3333: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
 3334: 	    'onchange="javascript:writeRadText(\''.$partid.'\','.
 3335: 		$weight{$partid}.')"> '.
 3336: 	    '<option selected="selected"> </option>'.
 3337: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3338: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3339: 	    '</select></td>'.
 3340:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3341: 	$line.='<input type="hidden" name="partid_'.
 3342: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3343: 	$line.='<input type="hidden" name="weight_'.
 3344: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3345: 
 3346: 	$result.=
 3347: 	    &Apache::loncommon::start_data_table_row()."\n".
 3348: 	    '<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>'.
 3349: 	    &Apache::loncommon::end_data_table_row()."\n";
 3350: 	$ctsparts++;
 3351:     }
 3352:     $result.=&Apache::loncommon::end_data_table()."\n".
 3353: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3354:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3355: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 3356: 
 3357:     #table listing all the students in a section/class
 3358:     #header of table
 3359:     $result.= '<h3>'.$specific_header.'</h3>'.
 3360:               &Apache::loncommon::start_data_table().
 3361: 	      &Apache::loncommon::start_data_table_header_row().
 3362: 	      '<th>'.&mt('No.').'</th>'.
 3363: 	      '<th>'.&nameUserString('header')."</th>\n";
 3364:     my $partserror;
 3365:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3366:     if ($partserror) {
 3367:         return &navmap_errormsg();
 3368:     }
 3369:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3370:     my @partids = ();
 3371:     foreach my $part (@parts) {
 3372: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3373:         my $narrowtext = &mt('Tries');
 3374: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3375: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3376: 	my ($partid) = &split_part_type($part);
 3377:         push(@partids,$partid);
 3378: 	my $display_part=&get_display_part($partid,$symb);
 3379: 	if ($display =~ /^Partial Credit Factor/) {
 3380: 	    $result.='<th>'.
 3381: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
 3382: 		    $display_part,$weight{$partid}).'</th>'."\n";
 3383: 	    next;
 3384: 	    
 3385: 	} else {
 3386: 	    if ($display =~ /Problem Status/) {
 3387: 		my $grade_status_mt = &mt('Grade Status');
 3388: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3389: 	    }
 3390: 	    my $part_mt = &mt('Part:');
 3391: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3392: 	}
 3393: 
 3394: 	$result.='<th>'.$display.'</th>'."\n";
 3395:     }
 3396:     $result.=&Apache::loncommon::end_data_table_header_row();
 3397: 
 3398:     my %last_resets = 
 3399: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3400: 
 3401:     #get info for each student
 3402:     #list all the students - with points and grade status
 3403:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3404:     my $ctr = 0;
 3405:     foreach (sort 
 3406: 	     {
 3407: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3408: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3409: 		 }
 3410: 		 return $a cmp $b;
 3411: 	     } (keys(%$fullname))) {
 3412: 	$ctr++;
 3413: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3414: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3415:     }
 3416:     $result.=&Apache::loncommon::end_data_table();
 3417:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3418:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3419: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 3420:     if (scalar(%$fullname) eq 0) {
 3421: 	my $colspan=3+scalar(@parts);
 3422: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3423:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3424: 	$result='<span class="LC_warning">'.
 3425: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3426: 	        $section_display, $stu_status).
 3427: 	    '</span>';
 3428:     }
 3429:     return $result;
 3430: }
 3431: 
 3432: #--- call by previous routine to display each student
 3433: sub viewstudentgrade {
 3434:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3435:     my ($uname,$udom) = split(/:/,$student);
 3436:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3437:     my %aggregates = (); 
 3438:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3439: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3440: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3441: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3442: 	'\');" target="_self">'.$fullname.'</a> '.
 3443: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3444:     $student=~s/:/_/; # colon doen't work in javascript for names
 3445:     foreach my $apart (@$parts) {
 3446: 	my ($part,$type) = &split_part_type($apart);
 3447: 	my $score=$record{"resource.$part.$type"};
 3448:         $result.='<td align="center">';
 3449:         my ($aggtries,$totaltries);
 3450:         unless (exists($aggregates{$part})) {
 3451: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3452: 
 3453: 	    $aggtries = $totaltries;
 3454:             if ($$last_resets{$part}) {  
 3455:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3456: 					   $part);
 3457:             }
 3458:             $result.='<input type="hidden" name="'.
 3459:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3460:             $result.='<input type="hidden" name="'.
 3461:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3462:             $aggregates{$part} = 1;
 3463:         }
 3464: 	if ($type eq 'awarded') {
 3465: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3466: 	    $result.='<input type="hidden" name="'.
 3467: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3468: 	    $result.='<input type="text" name="'.
 3469: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3470:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3471: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3472: 	} elsif ($type eq 'solved') {
 3473: 	    my ($status,$foo)=split(/_/,$score,2);
 3474: 	    $status = 'nothing' if ($status eq '');
 3475: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3476: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3477: 	    $result.='&nbsp;<select name="'.
 3478: 		'GD_'.$student.'_'.$part.'_solved" '.
 3479:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3480: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3481: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3482: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3483: 	    $result.="</select>&nbsp;</td>\n";
 3484: 	} else {
 3485: 	    $result.='<input type="hidden" name="'.
 3486: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3487: 		    "\n";
 3488: 	    $result.='<input type="text" name="'.
 3489: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3490: 		'value="'.$score.'" size="4" /></td>'."\n";
 3491: 	}
 3492:     }
 3493:     $result.=&Apache::loncommon::end_data_table_row();
 3494:     return $result;
 3495: }
 3496: 
 3497: #--- change scores for all the students in a section/class
 3498: #    record does not get update if unchanged
 3499: sub editgrades {
 3500:     my ($request,$symb) = @_;
 3501: 
 3502:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3503:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3504:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3505: 
 3506:     my $result= &Apache::loncommon::start_data_table().
 3507: 	&Apache::loncommon::start_data_table_header_row().
 3508: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3509: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3510:     my %scoreptr = (
 3511: 		    'correct'  =>'correct_by_override',
 3512: 		    'incorrect'=>'incorrect_by_override',
 3513: 		    'excused'  =>'excused',
 3514: 		    'ungraded' =>'ungraded_attempted',
 3515:                     'credited' =>'credit_attempted',
 3516: 		    'nothing'  => '',
 3517: 		    );
 3518:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3519: 
 3520:     my (@partid);
 3521:     my %weight = ();
 3522:     my %columns = ();
 3523:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3524: 
 3525:     my $partserror;
 3526:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3527:     if ($partserror) {
 3528:         return &navmap_errormsg();
 3529:     }
 3530:     my $header;
 3531:     while ($ctr < $env{'form.totalparts'}) {
 3532: 	my $partid = $env{'form.partid_'.$ctr};
 3533: 	push(@partid,$partid);
 3534: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3535: 	$ctr++;
 3536:     }
 3537:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3538:     foreach my $partid (@partid) {
 3539: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3540: 	    '<th align="center">'.&mt('New Score').'</th>';
 3541: 	$columns{$partid}=2;
 3542: 	foreach my $stores (@parts) {
 3543: 	    my ($part,$type) = &split_part_type($stores);
 3544: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3545: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3546: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3547: 	    $display =~ s/\[Part: \Q$part\E\]//;
 3548:             my $narrowtext = &mt('Tries');
 3549: 	    $display =~ s/Number of Attempts/$narrowtext/;
 3550: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 3551: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 3552: 	    $columns{$partid}+=2;
 3553: 	}
 3554:     }
 3555:     foreach my $partid (@partid) {
 3556: 	my $display_part=&get_display_part($partid,$symb);
 3557: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3558: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3559: 	    '</th>';
 3560: 
 3561:     }
 3562:     $result .= &Apache::loncommon::end_data_table_header_row().
 3563: 	&Apache::loncommon::start_data_table_header_row().
 3564: 	$header.
 3565: 	&Apache::loncommon::end_data_table_header_row();
 3566:     my @noupdate;
 3567:     my ($updateCtr,$noupdateCtr) = (1,1);
 3568:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3569: 	my $line;
 3570: 	my $user = $env{'form.ctr'.$i};
 3571: 	my ($uname,$udom)=split(/:/,$user);
 3572: 	my %newrecord;
 3573: 	my $updateflag = 0;
 3574: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3575: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3576: 	if (!&canmodify($usec)) {
 3577: 	    my $numcols=scalar(@partid)*4+2;
 3578: 	    push(@noupdate,
 3579: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 3580: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 3581: 	    next;
 3582: 	}
 3583:         my %aggregate = ();
 3584:         my $aggregateflag = 0;
 3585: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3586: 	foreach (@partid) {
 3587: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3588: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3589: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3590: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3591: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3592: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3593: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3594: 	    my $score;
 3595: 	    if ($partial eq '') {
 3596: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3597: 	    } elsif ($partial > 0) {
 3598: 		$score = 'correct_by_override';
 3599: 	    } elsif ($partial == 0) {
 3600: 		$score = 'incorrect_by_override';
 3601: 	    }
 3602: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3603: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3604: 
 3605: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3606: 		"$env{'user.name'}:$env{'user.domain'}";
 3607: 	    if ($dropMenu eq 'reset status' &&
 3608: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3609: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3610: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3611: 		$newrecord{'resource.'.$_.'.award'} = '';
 3612: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3613: 		$updateflag = 1;
 3614:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3615:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3616:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3617:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3618:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3619:                     $aggregateflag = 1;
 3620:                 }
 3621: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3622: 		$updateflag = 1;
 3623: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3624: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3625: 		$rec_update++;
 3626: 	    }
 3627: 
 3628: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3629: 		'<td align="center">'.$awarded.
 3630: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3631: 
 3632: 
 3633: 	    my $partid=$_;
 3634: 	    foreach my $stores (@parts) {
 3635: 		my ($part,$type) = &split_part_type($stores);
 3636: 		if ($part !~ m/^\Q$partid\E/) { next;}
 3637: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 3638: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 3639: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 3640: 		if ($awarded ne '' && $awarded ne $old_aw) {
 3641: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 3642: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3643: 		    $updateflag=1;
 3644: 		}
 3645: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3646: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 3647: 	    }
 3648: 	}
 3649: 	$line.="\n";
 3650: 
 3651: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3652: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3653: 
 3654: 	if ($updateflag) {
 3655: 	    $count++;
 3656: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 3657: 				    $udom,$uname);
 3658: 
 3659: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 3660: 					      $cnum,$udom,$uname)) {
 3661: 		# need to figure out if should be in queue.
 3662: 		my %record =  
 3663: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3664: 					     $udom,$uname);
 3665: 		my $all_graded = 1;
 3666: 		my $none_graded = 1;
 3667: 		foreach my $part (@parts) {
 3668: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 3669: 			$all_graded = 0;
 3670: 		    } else {
 3671: 			$none_graded = 0;
 3672: 		    }
 3673: 		}
 3674: 
 3675: 		if ($all_graded || $none_graded) {
 3676: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 3677: 							   $symb,$cdom,$cnum,
 3678: 							   $udom,$uname);
 3679: 		}
 3680: 	    }
 3681: 
 3682: 	    $result.=&Apache::loncommon::start_data_table_row().
 3683: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 3684: 		&Apache::loncommon::end_data_table_row();
 3685: 	    $updateCtr++;
 3686: 	} else {
 3687: 	    push(@noupdate,
 3688: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 3689: 	    $noupdateCtr++;
 3690: 	}
 3691:         if ($aggregateflag) {
 3692:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3693: 				  $cdom,$cnum);
 3694:         }
 3695:     }
 3696:     if (@noupdate) {
 3697: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 3698: 	my $numcols=scalar(@partid)*4+2;
 3699: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 3700: 	    '<td align="center" colspan="'.$numcols.'">'.
 3701: 	    &mt('No Changes Occurred For the Students Below').
 3702: 	    '</td>'.
 3703: 	    &Apache::loncommon::end_data_table_row();
 3704: 	foreach my $line (@noupdate) {
 3705: 	    $result.=
 3706: 		&Apache::loncommon::start_data_table_row().
 3707: 		$line.
 3708: 		&Apache::loncommon::end_data_table_row();
 3709: 	}
 3710:     }
 3711:     $result .= &Apache::loncommon::end_data_table();
 3712:     my $msg = '<p><b>'.
 3713: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 3714: 	    $rec_update,$count).'</b><br />'.
 3715: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 3716: 	'</b></p>';
 3717:     return $title.$msg.$result;
 3718: }
 3719: 
 3720: sub split_part_type {
 3721:     my ($partstr) = @_;
 3722:     my ($temp,@allparts)=split(/_/,$partstr);
 3723:     my $type=pop(@allparts);
 3724:     my $part=join('_',@allparts);
 3725:     return ($part,$type);
 3726: }
 3727: 
 3728: #------------- end of section for handling grading by section/class ---------
 3729: #
 3730: #----------------------------------------------------------------------------
 3731: 
 3732: 
 3733: #----------------------------------------------------------------------------
 3734: #
 3735: #-------------------------- Next few routines handles grading by csv upload
 3736: #
 3737: #--- Javascript to handle csv upload
 3738: sub csvupload_javascript_reverse_associate {
 3739:     my $error1=&mt('You need to specify the username or the student/employee ID');
 3740:     my $error2=&mt('You need to specify at least one grading field');
 3741:   return(<<ENDPICK);
 3742:   function verify(vf) {
 3743:     var foundsomething=0;
 3744:     var founduname=0;
 3745:     var foundID=0;
 3746:     for (i=0;i<=vf.nfields.value;i++) {
 3747:       tw=eval('vf.f'+i+'.selectedIndex');
 3748:       if (i==0 && tw!=0) { foundID=1; }
 3749:       if (i==1 && tw!=0) { founduname=1; }
 3750:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 3751:     }
 3752:     if (founduname==0 && foundID==0) {
 3753: 	alert('$error1');
 3754: 	return;
 3755:     }
 3756:     if (foundsomething==0) {
 3757: 	alert('$error2');
 3758: 	return;
 3759:     }
 3760:     vf.submit();
 3761:   }
 3762:   function flip(vf,tf) {
 3763:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3764:     var i;
 3765:     for (i=0;i<=vf.nfields.value;i++) {
 3766:       //can not pick the same destination field for both name and domain
 3767:       if (((i ==0)||(i ==1)) && 
 3768:           ((tf==0)||(tf==1)) && 
 3769:           (i!=tf) &&
 3770:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3771:         eval('vf.f'+i+'.selectedIndex=0;')
 3772:       }
 3773:     }
 3774:   }
 3775: ENDPICK
 3776: }
 3777: 
 3778: sub csvupload_javascript_forward_associate {
 3779:     my $error1=&mt('You need to specify the username or the student/employee ID');
 3780:     my $error2=&mt('You need to specify at least one grading field');
 3781:   return(<<ENDPICK);
 3782:   function verify(vf) {
 3783:     var foundsomething=0;
 3784:     var founduname=0;
 3785:     var foundID=0;
 3786:     for (i=0;i<=vf.nfields.value;i++) {
 3787:       tw=eval('vf.f'+i+'.selectedIndex');
 3788:       if (tw==1) { foundID=1; }
 3789:       if (tw==2) { founduname=1; }
 3790:       if (tw>3) { foundsomething=1; }
 3791:     }
 3792:     if (founduname==0 && foundID==0) {
 3793: 	alert('$error1');
 3794: 	return;
 3795:     }
 3796:     if (foundsomething==0) {
 3797: 	alert('$error2');
 3798: 	return;
 3799:     }
 3800:     vf.submit();
 3801:   }
 3802:   function flip(vf,tf) {
 3803:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3804:     var i;
 3805:     //can not pick the same destination field twice
 3806:     for (i=0;i<=vf.nfields.value;i++) {
 3807:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3808:         eval('vf.f'+i+'.selectedIndex=0;')
 3809:       }
 3810:     }
 3811:   }
 3812: ENDPICK
 3813: }
 3814: 
 3815: sub csvuploadmap_header {
 3816:     my ($request,$symb,$datatoken,$distotal)= @_;
 3817:     my $javascript;
 3818:     if ($env{'form.upfile_associate'} eq 'reverse') {
 3819: 	$javascript=&csvupload_javascript_reverse_associate();
 3820:     } else {
 3821: 	$javascript=&csvupload_javascript_forward_associate();
 3822:     }
 3823: 
 3824:     my $result='';
 3825:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 3826:     my $ignore=&mt('Ignore First Line');
 3827:     $symb = &Apache::lonenc::check_encrypt($symb);
 3828:     $request->print(<<ENDPICK);
 3829: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3830: <h3><span class="LC_info">Uploading Class Grades</span></h3>
 3831: $result
 3832: <hr />
 3833: <h3>Identify fields</h3>
 3834: Total number of records found in file: $distotal <hr />
 3835: Enter as many fields as you can. The system will inform you and bring you back
 3836: to this page if the data selected is insufficient to run your class.<hr />
 3837: <input type="button" value="Reverse Association" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 3838: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 3839: <input type="hidden" name="associate"  value="" />
 3840: <input type="hidden" name="phase"      value="three" />
 3841: <input type="hidden" name="datatoken"  value="$datatoken" />
 3842: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 3843: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 3844: <input type="hidden" name="upfile_associate" 
 3845:                                        value="$env{'form.upfile_associate'}" />
 3846: <input type="hidden" name="symb"       value="$symb" />
 3847: <input type="hidden" name="command"    value="csvuploadoptions" />
 3848: <hr />
 3849: ENDPICK
 3850:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
 3851:     return '';
 3852: 
 3853: }
 3854: 
 3855: sub csvupload_fields {
 3856:     my ($symb,$errorref) = @_;
 3857:     my (@parts) = &getpartlist($symb,$errorref);
 3858:     if (ref($errorref)) {
 3859:         if ($$errorref) {
 3860:             return;
 3861:         }
 3862:     }
 3863: 
 3864:     my @fields=(['ID','Student/Employee ID'],
 3865: 		['username','Student Username'],
 3866: 		['domain','Student Domain']);
 3867:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3868:     foreach my $part (sort(@parts)) {
 3869: 	my @datum;
 3870: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3871: 	my $name=$part;
 3872: 	if  (!$display) { $display = $name; }
 3873: 	@datum=($name,$display);
 3874: 	if ($name=~/^stores_(.*)_awarded/) {
 3875: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 3876: 	}
 3877: 	push(@fields,\@datum);
 3878:     }
 3879:     return (@fields);
 3880: }
 3881: 
 3882: sub csvuploadmap_footer {
 3883:     my ($request,$i,$keyfields) =@_;
 3884:     $request->print(<<ENDPICK);
 3885: </table>
 3886: <input type="hidden" name="nfields" value="$i" />
 3887: <input type="hidden" name="keyfields" value="$keyfields" />
 3888: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
 3889: </form>
 3890: ENDPICK
 3891: }
 3892: 
 3893: sub checkforfile_js {
 3894:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 3895:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
 3896:     function checkUpload(formname) {
 3897: 	if (formname.upfile.value == "") {
 3898: 	    alert("$alertmsg");
 3899: 	    return false;
 3900: 	}
 3901: 	formname.submit();
 3902:     }
 3903: CSVFORMJS
 3904:     return $result;
 3905: }
 3906: 
 3907: sub upcsvScores_form {
 3908:     my ($request,$symb) = @_;
 3909:     if (!$symb) {return '';}
 3910:     my $result=&checkforfile_js();
 3911:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 3912:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 3913:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
 3914: 	'</b></td></tr>'."\n";
 3915:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 3916:     my $upload=&mt("Upload Scores");
 3917:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 3918:     my $ignore=&mt('Ignore First Line');
 3919:     $symb = &Apache::lonenc::check_encrypt($symb);
 3920:     $result.=<<ENDUPFORM;
 3921: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3922: <input type="hidden" name="symb" value="$symb" />
 3923: <input type="hidden" name="command" value="csvuploadmap" />
 3924: $upfile_select
 3925: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 3926: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 3927: </form>
 3928: ENDUPFORM
 3929:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 3930:                            &mt("How do I create a CSV file from a spreadsheet"))
 3931:     .'</td></tr></table>'."\n";
 3932:     $result.='</td></tr></table><br /><br />'."\n";
 3933:     return $result;
 3934: }
 3935: 
 3936: 
 3937: sub csvuploadmap {
 3938:     my ($request,$symb)= @_;
 3939:     if (!$symb) {return '';}
 3940: 
 3941:     my $datatoken;
 3942:     if (!$env{'form.datatoken'}) {
 3943: 	$datatoken=&Apache::loncommon::upfile_store($request);
 3944:     } else {
 3945: 	$datatoken=$env{'form.datatoken'};
 3946: 	&Apache::loncommon::load_tmp_file($request);
 3947:     }
 3948:     my @records=&Apache::loncommon::upfile_record_sep();
 3949:     if ($env{'form.noFirstLine'}) { shift(@records); }
 3950:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 3951:     my ($i,$keyfields);
 3952:     if (@records) {
 3953:         my $fieldserror;
 3954: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 3955:         if ($fieldserror) {
 3956:             $request->print(&navmap_errormsg());
 3957:             return;
 3958:         }
 3959: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 3960: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 3961: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 3962: 							  \@fields);
 3963: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 3964: 	    chop($keyfields);
 3965: 	} else {
 3966: 	    unshift(@fields,['none','']);
 3967: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 3968: 							    \@fields);
 3969:             foreach my $rec (@records) {
 3970:                 my %temp = &Apache::loncommon::record_sep($rec);
 3971:                 if (%temp) {
 3972:                     $keyfields=join(',',sort(keys(%temp)));
 3973:                     last;
 3974:                 }
 3975:             }
 3976: 	}
 3977:     }
 3978:     &csvuploadmap_footer($request,$i,$keyfields);
 3979: 
 3980:     return '';
 3981: }
 3982: 
 3983: sub csvuploadoptions {
 3984:     my ($request,$symb)= @_;
 3985:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 3986:     my $ignore=&mt('Ignore First Line');
 3987:     $request->print(<<ENDPICK);
 3988: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3989: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
 3990: <input type="hidden" name="command"    value="csvuploadassign" />
 3991: <!--
 3992: <p>
 3993: <label>
 3994:    <input type="checkbox" name="show_full_results" />
 3995:    Show a table of all changes
 3996: </label>
 3997: </p>
 3998: -->
 3999: <p>
 4000: <label>
 4001:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4002:    Overwrite any existing score
 4003: </label>
 4004: </p>
 4005: ENDPICK
 4006:     my %fields=&get_fields();
 4007:     if (!defined($fields{'domain'})) {
 4008: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4009: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
 4010:     }
 4011:     foreach my $key (sort(keys(%env))) {
 4012: 	if ($key !~ /^form\.(.*)$/) { next; }
 4013: 	my $cleankey=$1;
 4014: 	if ($cleankey eq 'command') { next; }
 4015: 	$request->print('<input type="hidden" name="'.$cleankey.
 4016: 			'"  value="'.$env{$key}.'" />'."\n");
 4017:     }
 4018:     # FIXME do a check for any duplicated user ids...
 4019:     # FIXME do a check for any invalid user ids?...
 4020:     $request->print('<input type="submit" value="Assign Grades" /><br />
 4021: <hr /></form>'."\n");
 4022:     return '';
 4023: }
 4024: 
 4025: sub get_fields {
 4026:     my %fields;
 4027:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4028:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4029: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4030: 	    if ($env{'form.f'.$i} ne 'none') {
 4031: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4032: 	    }
 4033: 	} else {
 4034: 	    if ($env{'form.f'.$i} ne 'none') {
 4035: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4036: 	    }
 4037: 	}
 4038:     }
 4039:     return %fields;
 4040: }
 4041: 
 4042: sub csvuploadassign {
 4043:     my ($request,$symb)= @_;
 4044:     if (!$symb) {return '';}
 4045:     my $error_msg = '';
 4046:     &Apache::loncommon::load_tmp_file($request);
 4047:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4048:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 4049:     my %fields=&get_fields();
 4050:     $request->print('<h3>Assigning Grades</h3>');
 4051:     my $courseid=$env{'request.course.id'};
 4052:     my ($classlist) = &getclasslist('all',0);
 4053:     my @notallowed;
 4054:     my @skipped;
 4055:     my $countdone=0;
 4056:     foreach my $grade (@gradedata) {
 4057: 	my %entries=&Apache::loncommon::record_sep($grade);
 4058: 	my $domain;
 4059: 	if ($entries{$fields{'domain'}}) {
 4060: 	    $domain=$entries{$fields{'domain'}};
 4061: 	} else {
 4062: 	    $domain=$env{'form.default_domain'};
 4063: 	}
 4064: 	$domain=~s/\s//g;
 4065: 	my $username=$entries{$fields{'username'}};
 4066: 	$username=~s/\s//g;
 4067: 	if (!$username) {
 4068: 	    my $id=$entries{$fields{'ID'}};
 4069: 	    $id=~s/\s//g;
 4070: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4071: 	    $username=$ids{$id};
 4072: 	}
 4073: 	if (!exists($$classlist{"$username:$domain"})) {
 4074: 	    my $id=$entries{$fields{'ID'}};
 4075: 	    $id=~s/\s//g;
 4076: 	    if ($id) {
 4077: 		push(@skipped,"$id:$domain");
 4078: 	    } else {
 4079: 		push(@skipped,"$username:$domain");
 4080: 	    }
 4081: 	    next;
 4082: 	}
 4083: 	my $usec=$classlist->{"$username:$domain"}[5];
 4084: 	if (!&canmodify($usec)) {
 4085: 	    push(@notallowed,"$username:$domain");
 4086: 	    next;
 4087: 	}
 4088: 	my %points;
 4089: 	my %grades;
 4090: 	foreach my $dest (keys(%fields)) {
 4091: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4092: 		$dest eq 'domain') { next; }
 4093: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4094: 	    if ($dest=~/stores_(.*)_points/) {
 4095: 		my $part=$1;
 4096: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4097: 					      $symb,$domain,$username);
 4098:                 if ($wgt) {
 4099:                     $entries{$fields{$dest}}=~s/\s//g;
 4100:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4101:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4102:                                           : 'correct_by_override';
 4103:                     $grades{"resource.$part.awarded"}=$pcr;
 4104:                     $grades{"resource.$part.solved"}=$award;
 4105:                     $points{$part}=1;
 4106:                 } else {
 4107:                     $error_msg = "<br />" .
 4108:                         &mt("Some point values were assigned"
 4109:                             ." for problems with a weight "
 4110:                             ."of zero. These values were "
 4111:                             ."ignored.");
 4112:                 }
 4113: 	    } else {
 4114: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4115: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4116: 		my $store_key=$dest;
 4117: 		$store_key=~s/^stores/resource/;
 4118: 		$store_key=~s/_/\./g;
 4119: 		$grades{$store_key}=$entries{$fields{$dest}};
 4120: 	    }
 4121: 	}
 4122: 	if (! %grades) { 
 4123:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4124:         } else {
 4125: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4126: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4127: 					   $env{'request.course.id'},
 4128: 					   $domain,$username);
 4129: 	   if ($result eq 'ok') {
 4130: 	      $request->print('.');
 4131: 	   } else {
 4132: 	      $request->print("<p><span class=\"LC_error\">".
 4133:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4134:                                   "$username:$domain",$result)."</span></p>");
 4135: 	   }
 4136: 	   $request->rflush();
 4137: 	   $countdone++;
 4138:         }
 4139:     }
 4140:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 4141:     if (@skipped) {
 4142: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 4143:         $request->print(join(', ',@skipped));
 4144:     }
 4145:     if (@notallowed) {
 4146: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 4147: 	$request->print(join(', ',@notallowed));
 4148:     }
 4149:     $request->print("<br />\n");
 4150:     return $error_msg;
 4151: }
 4152: #------------- end of section for handling csv file upload ---------
 4153: #
 4154: #-------------------------------------------------------------------
 4155: #
 4156: #-------------- Next few routines handle grading by page/sequence
 4157: #
 4158: #--- Select a page/sequence and a student to grade
 4159: sub pickStudentPage {
 4160:     my ($request,$symb) = @_;
 4161: 
 4162:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4163:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
 4164: 
 4165: function checkPickOne(formname) {
 4166:     if (radioSelection(formname.student) == null) {
 4167: 	alert("$alertmsg");
 4168: 	return;
 4169:     }
 4170:     ptr = pullDownSelection(formname.selectpage);
 4171:     formname.page.value = formname["page"+ptr].value;
 4172:     formname.title.value = formname["title"+ptr].value;
 4173:     formname.submit();
 4174: }
 4175: 
 4176: LISTJAVASCRIPT
 4177:     &commonJSfunctions($request);
 4178: 
 4179:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4180:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4181:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4182: 
 4183:     my $result='<h3><span class="LC_info">&nbsp;'.
 4184: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4185: 
 4186:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4187:     my $map_error;
 4188:     my ($titles,$symbx) = &getSymbMap($map_error);
 4189:     if ($map_error) {
 4190:         $request->print(&navmap_errormsg());
 4191:         return; 
 4192:     }
 4193:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4194: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4195: #    my $type=($curpage =~ /\.(page|sequence)/);
 4196:     my $select = '<select name="selectpage">'."\n";
 4197:     my $ctr=0;
 4198:     foreach (@$titles) {
 4199: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4200: 	$select.='<option value="'.$ctr.'" '.
 4201: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4202: 	    '>'.$showtitle.'</option>'."\n";
 4203: 	$ctr++;
 4204:     }
 4205:     $select.= '</select>';
 4206:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
 4207: 
 4208:     $ctr=0;
 4209:     foreach (@$titles) {
 4210: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4211: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4212: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4213: 	$ctr++;
 4214:     }
 4215:     $result.='<input type="hidden" name="page" />'."\n".
 4216: 	'<input type="hidden" name="title" />'."\n";
 4217: 
 4218:     my $options =
 4219: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
 4220: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
 4221:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
 4222: 
 4223:     $options =
 4224: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
 4225: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
 4226: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
 4227:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
 4228:     
 4229:     $result.=&build_section_inputs();
 4230:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4231:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4232: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4233: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."<br />\n";
 4234: 
 4235:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
 4236: 
 4237:     $result.='&nbsp;<input type="button" '.
 4238:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4239: 
 4240:     $request->print($result);
 4241: 
 4242:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4243: 	&Apache::loncommon::start_data_table().
 4244: 	&Apache::loncommon::start_data_table_header_row().
 4245: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4246: 	'<th>'.&nameUserString('header').'</th>'.
 4247: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4248: 	'<th>'.&nameUserString('header').'</th>'.
 4249: 	&Apache::loncommon::end_data_table_header_row();
 4250:  
 4251:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4252:     my $ptr = 1;
 4253:     foreach my $student (sort 
 4254: 			 {
 4255: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4256: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4257: 			     }
 4258: 			     return $a cmp $b;
 4259: 			 } (keys(%$fullname))) {
 4260: 	my ($uname,$udom) = split(/:/,$student);
 4261: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4262:                                   : '</td>');
 4263: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4264: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4265: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4266: 	$studentTable.=
 4267: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4268:                          : '');
 4269: 	$ptr++;
 4270:     }
 4271:     if ($ptr%2 == 0) {
 4272: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4273: 	    &Apache::loncommon::end_data_table_row();
 4274:     }
 4275:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4276:     $studentTable.='<input type="button" '.
 4277:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4278: 
 4279:     $request->print($studentTable);
 4280: 
 4281:     return '';
 4282: }
 4283: 
 4284: sub getSymbMap {
 4285:     my ($map_error) = @_;
 4286:     my $navmap = Apache::lonnavmaps::navmap->new();
 4287:     unless (ref($navmap)) {
 4288:         if (ref($map_error)) {
 4289:             $$map_error = 'navmap';
 4290:         }
 4291:         return;
 4292:     }
 4293:     my %symbx = ();
 4294:     my @titles = ();
 4295:     my $minder = 0;
 4296: 
 4297:     # Gather every sequence that has problems.
 4298:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4299: 					       1,0,1);
 4300:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4301: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4302: 	    my $title = $minder.'.'.
 4303: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4304: 	    push(@titles, $title); # minder in case two titles are identical
 4305: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4306: 	    $minder++;
 4307: 	}
 4308:     }
 4309:     return \@titles,\%symbx;
 4310: }
 4311: 
 4312: #
 4313: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4314: sub displayPage {
 4315:     my ($request,$symb) = @_;
 4316:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4317:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4318:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4319:     my $pageTitle = $env{'form.page'};
 4320:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4321:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4322:     my $usec=$classlist->{$env{'form.student'}}[5];
 4323: 
 4324:     #need to make sure we have the correct data for later EXT calls, 
 4325:     #thus invalidate the cache
 4326:     &Apache::lonnet::devalidatecourseresdata(
 4327:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4328:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4329:     &Apache::lonnet::clear_EXT_cache_status();
 4330: 
 4331:     if (!&canview($usec)) {
 4332: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
 4333: 	return;
 4334:     }
 4335:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4336:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4337: 	'</h3>'."\n";
 4338:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4339:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4340: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4341:     } else {
 4342: 	delete($env{'form.CODE'});
 4343:     }
 4344:     &sub_page_js($request);
 4345:     $request->print($result);
 4346: 
 4347:     my $navmap = Apache::lonnavmaps::navmap->new();
 4348:     unless (ref($navmap)) {
 4349:         $request->print(&navmap_errormsg());
 4350:         return;
 4351:     }
 4352:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4353:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4354:     if (!$map) {
 4355: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4356: 	return; 
 4357:     }
 4358:     my $iterator = $navmap->getIterator($map->map_start(),
 4359: 					$map->map_finish());
 4360: 
 4361:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4362: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4363: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4364: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4365: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4366: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4367: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4368: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
 4369: 
 4370:     if (defined($env{'form.CODE'})) {
 4371: 	$studentTable.=
 4372: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4373:     }
 4374:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4375: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4376: 
 4377:     $studentTable.='&nbsp;<span class="LC_info">'.
 4378:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 4379:         '</span>'."\n".
 4380: 	&Apache::loncommon::start_data_table().
 4381: 	&Apache::loncommon::start_data_table_header_row().
 4382: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
 4383: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4384: 	&Apache::loncommon::end_data_table_header_row();
 4385: 
 4386:     &Apache::lonxml::clear_problem_counter();
 4387:     my ($depth,$question,$prob) = (1,1,1);
 4388:     $iterator->next(); # skip the first BEGIN_MAP
 4389:     my $curRes = $iterator->next(); # for "current resource"
 4390:     while ($depth > 0) {
 4391:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4392:         if($curRes == $iterator->END_MAP) { $depth--; }
 4393: 
 4394:         if (ref($curRes) && $curRes->is_problem()) {
 4395: 	    my $parts = $curRes->parts();
 4396:             my $title = $curRes->compTitle();
 4397: 	    my $symbx = $curRes->symb();
 4398: 	    $studentTable.=
 4399: 		&Apache::loncommon::start_data_table_row().
 4400: 		'<td align="center" valign="top" >'.$prob.
 4401: 		(scalar(@{$parts}) == 1 ? '' 
 4402: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
 4403: 							scalar(@{$parts}))
 4404: 		 ).
 4405: 		 '</td>';
 4406: 	    $studentTable.='<td valign="top">';
 4407: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4408: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4409: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4410: 					     undef,'both',\%form);
 4411: 	    } else {
 4412: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4413: 		$companswer =~ s|<form(.*?)>||g;
 4414: 		$companswer =~ s|</form>||g;
 4415: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4416: #		    $companswer =~ s/$1/ /ms;
 4417: #		    $request->print('match='.$1."<br />\n");
 4418: #		}
 4419: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4420: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 4421: 	    }
 4422: 
 4423: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4424: 
 4425: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4426: 		if ($record{'version'} eq '') {
 4427: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4428: 		} else {
 4429: 		    my %responseType = ();
 4430: 		    foreach my $partid (@{$parts}) {
 4431: 			my @responseIds =$curRes->responseIds($partid);
 4432: 			my @responseType =$curRes->responseType($partid);
 4433: 			my %responseIds;
 4434: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4435: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4436: 			}
 4437: 			$responseType{$partid} = \%responseIds;
 4438: 		    }
 4439: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4440: 
 4441: 		}
 4442: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4443: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4444: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4445: 									$env{'request.course.id'},
 4446: 									'','.submission');
 4447:  
 4448: 	    }
 4449: 	    if (&canmodify($usec)) {
 4450:             $studentTable.=&gradeBox_start();
 4451: 		foreach my $partid (@{$parts}) {
 4452: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4453: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4454: 		    $question++;
 4455: 		}
 4456:             $studentTable.=&gradeBox_end();
 4457: 		$prob++;
 4458: 	    }
 4459: 	    $studentTable.='</td></tr>';
 4460: 
 4461: 	}
 4462:         $curRes = $iterator->next();
 4463:     }
 4464: 
 4465:     $studentTable.=
 4466:         '</table>'."\n".
 4467:         '<input type="button" value="'.&mt('Save').'" '.
 4468:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4469:         '</form>'."\n";
 4470:     $request->print($studentTable);
 4471: 
 4472:     return '';
 4473: }
 4474: 
 4475: sub displaySubByDates {
 4476:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4477:     my $isCODE=0;
 4478:     my $isTask = ($symb =~/\.task$/);
 4479:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4480:     my $studentTable=&Apache::loncommon::start_data_table().
 4481: 	&Apache::loncommon::start_data_table_header_row().
 4482: 	'<th>'.&mt('Date/Time').'</th>'.
 4483: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4484: 	'<th>'.&mt('Submission').'</th>'.
 4485: 	'<th>'.&mt('Status').'</th>'.
 4486: 	&Apache::loncommon::end_data_table_header_row();
 4487:     my ($version);
 4488:     my %mark;
 4489:     my %orders;
 4490:     $mark{'correct_by_student'} = $checkIcon;
 4491:     if (!exists($$record{'1:timestamp'})) {
 4492: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 4493:     }
 4494: 
 4495:     my $interaction;
 4496:     my $no_increment = 1;
 4497:     for ($version=1;$version<=$$record{'version'};$version++) {
 4498: 	my $timestamp = 
 4499: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4500: 	if (exists($$record{$version.':resource.0.version'})) {
 4501: 	    $interaction = $$record{$version.':resource.0.version'};
 4502: 	}
 4503: 
 4504: 	my $where = ($isTask ? "$version:resource.$interaction"
 4505: 		             : "$version:resource");
 4506: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4507: 	    '<td>'.$timestamp.'</td>';
 4508: 	if ($isCODE) {
 4509: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4510: 	}
 4511: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4512: 	my @displaySub = ();
 4513: 	foreach my $partid (@{$parts}) {
 4514:             my $hidden;
 4515:             if (($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurvey') ||
 4516:                 ($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurveycred')) {
 4517:                 $hidden = 1;
 4518:             }
 4519: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4520: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4521: 	    
 4522: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4523: 	    my $display_part=&get_display_part($partid,$symb);
 4524: 	    foreach my $matchKey (@matchKey) {
 4525: 		if (exists($$record{$version.':'.$matchKey}) &&
 4526: 		    $$record{$version.':'.$matchKey} ne '') {
 4527:                     
 4528: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4529: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4530:                     $displaySub[0].='<span class="LC_nobreak"';
 4531:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 4532:                                    .' <span class="LC_internal_info">'
 4533:                                    .'('.&mt('Part ID: [_1]',$responseId).')'
 4534:                                    .'</span>'
 4535:                                    .' <b>';
 4536:                     if ($hidden) {
 4537:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
 4538:                     } else {
 4539: 		        if ($$record{"$where.$partid.tries"} eq '') {
 4540: 			    $displaySub[0].=&mt('Trial not counted');
 4541: 		        } else {
 4542: 			    $displaySub[0].=&mt('Trial: [_1]',
 4543: 					    $$record{"$where.$partid.tries"});
 4544: 		        }
 4545: 		        my $responseType=($isTask ? 'Task'
 4546:                                               : $responseType->{$partid}->{$responseId});
 4547: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4548: 		        if (!exists($orders{$partid}->{$responseId})) {
 4549: 			    $orders{$partid}->{$responseId}=
 4550: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
 4551:                                            $no_increment);
 4552: 		        }
 4553: 		        $displaySub[0].='</b></span>'; # /nobreak
 4554: 		        $displaySub[0].='&nbsp; '.
 4555: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
 4556:                     }
 4557: 		}
 4558: 	    }
 4559: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4560: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 4561: 				    $$record{"$where.$partid.checkedin"},
 4562: 				    $$record{"$where.$partid.checkedin.slot"}).
 4563: 					'<br />';
 4564: 	    }
 4565: 	    if (exists $$record{"$where.$partid.award"}) {
 4566: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 4567: 		    lc($$record{"$where.$partid.award"}).' '.
 4568: 		    $mark{$$record{"$where.$partid.solved"}}.
 4569: 		    '<br />';
 4570: 	    }
 4571: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4572: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4573: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4574: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4575: 		$displaySub[2].=
 4576: 		    $$record{"$version:resource.$partid.regrader"}.
 4577: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4578: 	    }
 4579: 	}
 4580: 	# needed because old essay regrader has not parts info
 4581: 	if (exists $$record{"$version:resource.regrader"}) {
 4582: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 4583: 	}
 4584: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 4585: 	if ($displaySub[2]) {
 4586: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 4587: 	}
 4588: 	$studentTable.='&nbsp;</td>'.
 4589: 	    &Apache::loncommon::end_data_table_row();
 4590:     }
 4591:     $studentTable.=&Apache::loncommon::end_data_table();
 4592:     return $studentTable;
 4593: }
 4594: 
 4595: sub updateGradeByPage {
 4596:     my ($request,$symb) = @_;
 4597: 
 4598:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4599:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4600:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4601:     my $pageTitle = $env{'form.page'};
 4602:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4603:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4604:     my $usec=$classlist->{$env{'form.student'}}[5];
 4605:     if (!&canmodify($usec)) {
 4606: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 4607: 	return;
 4608:     }
 4609:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4610:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 4611: 	'</h3>'."\n";
 4612: 
 4613:     $request->print($result);
 4614: 
 4615: 
 4616:     my $navmap = Apache::lonnavmaps::navmap->new();
 4617:     unless (ref($navmap)) {
 4618:         $request->print(&navmap_errormsg());
 4619:         return;
 4620:     }
 4621:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 4622:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4623:     if (!$map) {
 4624: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 4625: 	return; 
 4626:     }
 4627:     my $iterator = $navmap->getIterator($map->map_start(),
 4628: 					$map->map_finish());
 4629: 
 4630:     my $studentTable=
 4631: 	&Apache::loncommon::start_data_table().
 4632: 	&Apache::loncommon::start_data_table_header_row().
 4633: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 4634: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 4635: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 4636: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 4637: 	&Apache::loncommon::end_data_table_header_row();
 4638: 
 4639:     $iterator->next(); # skip the first BEGIN_MAP
 4640:     my $curRes = $iterator->next(); # for "current resource"
 4641:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 4642:     while ($depth > 0) {
 4643:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4644:         if($curRes == $iterator->END_MAP) { $depth--; }
 4645: 
 4646:         if (ref($curRes) && $curRes->is_problem()) {
 4647: 	    my $parts = $curRes->parts();
 4648:             my $title = $curRes->compTitle();
 4649: 	    my $symbx = $curRes->symb();
 4650: 	    $studentTable.=
 4651: 		&Apache::loncommon::start_data_table_row().
 4652: 		'<td align="center" valign="top" >'.$prob.
 4653: 		(scalar(@{$parts}) == 1 ? '' 
 4654:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
 4655: 		.')').'</td>';
 4656: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 4657: 
 4658: 	    my %newrecord=();
 4659: 	    my @displayPts=();
 4660:             my %aggregate = ();
 4661:             my $aggregateflag = 0;
 4662: 	    foreach my $partid (@{$parts}) {
 4663: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 4664: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 4665: 
 4666: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 4667: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 4668: 		my $partial = $newpts/$wgt;
 4669: 		my $score;
 4670: 		if ($partial > 0) {
 4671: 		    $score = 'correct_by_override';
 4672: 		} elsif ($newpts ne '') { #empty is taken as 0
 4673: 		    $score = 'incorrect_by_override';
 4674: 		}
 4675: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 4676: 		if ($dropMenu eq 'excused') {
 4677: 		    $partial = '';
 4678: 		    $score = 'excused';
 4679: 		} elsif ($dropMenu eq 'reset status'
 4680: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 4681: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 4682: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 4683: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 4684: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 4685: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 4686: 		    $changeflag++;
 4687: 		    $newpts = '';
 4688:                     
 4689:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 4690:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 4691:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 4692:                     if ($aggtries > 0) {
 4693:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4694:                         $aggregateflag = 1;
 4695:                     }
 4696: 		}
 4697: 		my $display_part=&get_display_part($partid,$curRes->symb());
 4698: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 4699: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4700: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 4701: 		    '&nbsp;<br />';
 4702: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4703: 		     (($score eq 'excused') ? 'excused' : $newpts).
 4704: 		    '&nbsp;<br />';
 4705: 		$question++;
 4706: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 4707: 
 4708: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 4709: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 4710: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 4711: 		    if (scalar(keys(%newrecord)) > 0);
 4712: 
 4713: 		$changeflag++;
 4714: 	    }
 4715: 	    if (scalar(keys(%newrecord)) > 0) {
 4716: 		my %record = 
 4717: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 4718: 					     $udom,$uname);
 4719: 
 4720: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 4721: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 4722: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 4723: 		    $newrecord{'resource.CODE'} = '';
 4724: 		}
 4725: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 4726: 					$udom,$uname);
 4727: 		%record = &Apache::lonnet::restore($symbx,
 4728: 						   $env{'request.course.id'},
 4729: 						   $udom,$uname);
 4730: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 4731: 					     $cdom,$cnum,$udom,$uname);
 4732: 	    }
 4733: 	    
 4734:             if ($aggregateflag) {
 4735:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4736:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 4737:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 4738:             }
 4739: 
 4740: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 4741: 		'<td valign="top">'.$displayPts[1].'</td>'.
 4742: 		&Apache::loncommon::end_data_table_row();
 4743: 
 4744: 	    $prob++;
 4745: 	}
 4746:         $curRes = $iterator->next();
 4747:     }
 4748: 
 4749:     $studentTable.=&Apache::loncommon::end_data_table();
 4750:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 4751: 		  &mt('The scores were changed for [quant,_1,problem].',
 4752: 		  $changeflag));
 4753:     $request->print($grademsg.$studentTable);
 4754: 
 4755:     return '';
 4756: }
 4757: 
 4758: #-------- end of section for handling grading by page/sequence ---------
 4759: #
 4760: #-------------------------------------------------------------------
 4761: 
 4762: #-------------------- Bubblesheet (Scantron) Grading -------------------
 4763: #
 4764: #------ start of section for handling grading by page/sequence ---------
 4765: 
 4766: =pod
 4767: 
 4768: =head1 Bubble sheet grading routines
 4769: 
 4770:   For this documentation:
 4771: 
 4772:    'scanline' refers to the full line of characters
 4773:    from the file that we are parsing that represents one entire sheet
 4774: 
 4775:    'bubble line' refers to the data
 4776:    representing the line of bubbles that are on the physical bubble sheet
 4777: 
 4778: 
 4779: The overall process is that a scanned in bubble sheet data is uploaded
 4780: into a course. When a user wants to grade, they select a
 4781: sequence/folder of resources, a file of bubble sheet info, and pick
 4782: one of the predefined configurations for what each scanline looks
 4783: like.
 4784: 
 4785: Next each scanline is checked for any errors of either 'missing
 4786: bubbles' (it's an error because it may have been mis-scanned
 4787: because too light bubbling), 'double bubble' (each bubble line should
 4788: have no more that one letter picked), invalid or duplicated CODE,
 4789: invalid student/employee ID
 4790: 
 4791: If the CODE option is used that determines the randomization of the
 4792: homework problems, either way the student/employee ID is looked up into a
 4793: username:domain.
 4794: 
 4795: During the validation phase the instructor can choose to skip scanlines. 
 4796: 
 4797: After the validation phase, there are now 3 bubble sheet files
 4798: 
 4799:   scantron_original_filename (unmodified original file)
 4800:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 4801:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 4802: 
 4803: Also there is a separate hash nohist_scantrondata that contains extra
 4804: correction information that isn't representable in the bubble sheet
 4805: file (see &scantron_getfile() for more information)
 4806: 
 4807: After all scanlines are either valid, marked as valid or skipped, then
 4808: foreach line foreach problem in the picked sequence, an ssi request is
 4809: made that simulates a user submitting their selected letter(s) against
 4810: the homework problem.
 4811: 
 4812: =over 4
 4813: 
 4814: 
 4815: 
 4816: =item defaultFormData
 4817: 
 4818:   Returns html hidden inputs used to hold context/default values.
 4819: 
 4820:  Arguments:
 4821:   $symb - $symb of the current resource 
 4822: 
 4823: =cut
 4824: 
 4825: sub defaultFormData {
 4826:     my ($symb)=@_;
 4827:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
 4828: }
 4829: 
 4830: 
 4831: =pod 
 4832: 
 4833: =item getSequenceDropDown
 4834: 
 4835:    Return html dropdown of possible sequences to grade
 4836:  
 4837:  Arguments:
 4838:    $symb - $symb of the current resource
 4839:    $map_error - ref to scalar which will container error if
 4840:                 $navmap object is unavailable in &getSymbMap().
 4841: 
 4842: =cut
 4843: 
 4844: sub getSequenceDropDown {
 4845:     my ($symb,$map_error)=@_;
 4846:     my $result='<select name="selectpage">'."\n";
 4847:     my ($titles,$symbx) = &getSymbMap($map_error);
 4848:     if (ref($map_error)) {
 4849:         return if ($$map_error);
 4850:     }
 4851:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 4852:     my $ctr=0;
 4853:     foreach (@$titles) {
 4854: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4855: 	$result.='<option value="'.$$symbx{$_}.'" '.
 4856: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4857: 	    '>'.$showtitle.'</option>'."\n";
 4858: 	$ctr++;
 4859:     }
 4860:     $result.= '</select>';
 4861:     return $result;
 4862: }
 4863: 
 4864: my %bubble_lines_per_response;     # no. bubble lines for each response.
 4865:                                    # key is zero-based index - 0, 1, 2 ...
 4866: 
 4867: my %first_bubble_line;             # First bubble line no. for each bubble.
 4868: 
 4869: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 4870:                                    # matchresponse or rankresponse, where 
 4871:                                    # an individual response can have multiple 
 4872:                                    # lines
 4873: 
 4874: my %responsetype_per_response;     # responsetype for each response
 4875: 
 4876: # Save and restore the bubble lines array to the form env.
 4877: 
 4878: 
 4879: sub save_bubble_lines {
 4880:     foreach my $line (keys(%bubble_lines_per_response)) {
 4881: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 4882: 	$env{"form.scantron.first_bubble_line.$line"} =
 4883: 	    $first_bubble_line{$line};
 4884:         $env{"form.scantron.sub_bubblelines.$line"} = 
 4885:             $subdivided_bubble_lines{$line};
 4886:         $env{"form.scantron.responsetype.$line"} =
 4887:             $responsetype_per_response{$line};
 4888:     }
 4889: }
 4890: 
 4891: 
 4892: sub restore_bubble_lines {
 4893:     my $line = 0;
 4894:     %bubble_lines_per_response = ();
 4895:     while ($env{"form.scantron.bubblelines.$line"}) {
 4896: 	my $value = $env{"form.scantron.bubblelines.$line"};
 4897: 	$bubble_lines_per_response{$line} = $value;
 4898: 	$first_bubble_line{$line}  =
 4899: 	    $env{"form.scantron.first_bubble_line.$line"};
 4900:         $subdivided_bubble_lines{$line} =
 4901:             $env{"form.scantron.sub_bubblelines.$line"};
 4902:         $responsetype_per_response{$line} =
 4903:             $env{"form.scantron.responsetype.$line"};
 4904: 	$line++;
 4905:     }
 4906: }
 4907: 
 4908: #  Given the parsed scanline, get the response for 
 4909: #  'answer' number n:
 4910: 
 4911: sub get_response_bubbles {
 4912:     my ($parsed_line, $response)  = @_;
 4913: 
 4914:     my $bubble_line = $first_bubble_line{$response-1} +1;
 4915:     my $bubble_lines= $bubble_lines_per_response{$response-1};
 4916:     
 4917:     my $selected = "";
 4918: 
 4919:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
 4920: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
 4921: 	$bubble_line++;
 4922:     }
 4923:     return $selected;
 4924: }
 4925: 
 4926: =pod 
 4927: 
 4928: =item scantron_filenames
 4929: 
 4930:    Returns a list of the scantron files in the current course 
 4931: 
 4932: =cut
 4933: 
 4934: sub scantron_filenames {
 4935:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4936:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4937:     my $getpropath = 1;
 4938:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
 4939:                                        $getpropath);
 4940:     my @possiblenames;
 4941:     foreach my $filename (sort(@files)) {
 4942: 	($filename)=split(/&/,$filename);
 4943: 	if ($filename!~/^scantron_orig_/) { next ; }
 4944: 	$filename=~s/^scantron_orig_//;
 4945: 	push(@possiblenames,$filename);
 4946:     }
 4947:     return @possiblenames;
 4948: }
 4949: 
 4950: =pod 
 4951: 
 4952: =item scantron_uploads
 4953: 
 4954:    Returns  html drop-down list of scantron files in current course.
 4955: 
 4956:  Arguments:
 4957:    $file2grade - filename to set as selected in the dropdown
 4958: 
 4959: =cut
 4960: 
 4961: sub scantron_uploads {
 4962:     my ($file2grade) = @_;
 4963:     my $result=	'<select name="scantron_selectfile">';
 4964:     $result.="<option></option>";
 4965:     foreach my $filename (sort(&scantron_filenames())) {
 4966: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 4967:     }
 4968:     $result.="</select>";
 4969:     return $result;
 4970: }
 4971: 
 4972: =pod 
 4973: 
 4974: =item scantron_scantab
 4975: 
 4976:   Returns html drop down of the scantron formats in the scantronformat.tab
 4977:   file.
 4978: 
 4979: =cut
 4980: 
 4981: sub scantron_scantab {
 4982:     my $result='<select name="scantron_format">'."\n";
 4983:     $result.='<option></option>'."\n";
 4984:     my @lines = &get_scantronformat_file();
 4985:     if (@lines > 0) {
 4986:         foreach my $line (@lines) {
 4987:             next if (($line =~ /^\#/) || ($line eq ''));
 4988: 	    my ($name,$descrip)=split(/:/,$line);
 4989: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 4990:         }
 4991:     }
 4992:     $result.='</select>'."\n";
 4993:     return $result;
 4994: }
 4995: 
 4996: =pod
 4997: 
 4998: =item get_scantronformat_file
 4999: 
 5000:   Returns an array containing lines from the scantron format file for
 5001:   the domain of the course.
 5002: 
 5003:   If a url for a custom.tab file is listed in domain's configuration.db, 
 5004:   lines are from this file.
 5005: 
 5006:   Otherwise, if a default.tab has been published in RES space by the 
 5007:   domainconfig user, lines are from this file.
 5008: 
 5009:   Otherwise, fall back to getting lines from the legacy file on the
 5010:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 5011: 
 5012: =cut
 5013: 
 5014: sub get_scantronformat_file {
 5015:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5016:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 5017:     my $gottab = 0;
 5018:     my @lines;
 5019:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5020:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5021:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5022:             if ($formatfile ne '-1') {
 5023:                 @lines = split("\n",$formatfile,-1);
 5024:                 $gottab = 1;
 5025:             }
 5026:         }
 5027:     }
 5028:     if (!$gottab) {
 5029:         my $confname = $cdom.'-domainconfig';
 5030:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5031:         my $formatfile =  &Apache::lonnet::getfile($default);
 5032:         if ($formatfile ne '-1') {
 5033:             @lines = split("\n",$formatfile,-1);
 5034:             $gottab = 1;
 5035:         }
 5036:     }
 5037:     if (!$gottab) {
 5038:         my @domains = &Apache::lonnet::current_machine_domains();
 5039:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5040:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5041:             @lines = <$fh>;
 5042:             close($fh);
 5043:         } else {
 5044:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 5045:             @lines = <$fh>;
 5046:             close($fh);
 5047:         }
 5048:     }
 5049:     return @lines;
 5050: }
 5051: 
 5052: =pod 
 5053: 
 5054: =item scantron_CODElist
 5055: 
 5056:   Returns html drop down of the saved CODE lists from current course,
 5057:   generated from earlier printings.
 5058: 
 5059: =cut
 5060: 
 5061: sub scantron_CODElist {
 5062:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5063:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5064:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5065:     my $namechoice='<option></option>';
 5066:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5067: 	if ($name =~ /^error: 2 /) { next; }
 5068: 	if ($name =~ /^type\0/) { next; }
 5069: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5070:     }
 5071:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5072:     return $namechoice;
 5073: }
 5074: 
 5075: =pod 
 5076: 
 5077: =item scantron_CODEunique
 5078: 
 5079:   Returns the html for "Each CODE to be used once" radio.
 5080: 
 5081: =cut
 5082: 
 5083: sub scantron_CODEunique {
 5084:     my $result='<span class="LC_nobreak">
 5085:                  <label><input type="radio" name="scantron_CODEunique"
 5086:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5087:                 </span>
 5088:                 <span class="LC_nobreak">
 5089:                  <label><input type="radio" name="scantron_CODEunique"
 5090:                         value="no" />'.&mt('No').' </label>
 5091:                 </span>';
 5092:     return $result;
 5093: }
 5094: 
 5095: =pod 
 5096: 
 5097: =item scantron_selectphase
 5098: 
 5099:   Generates the initial screen to start the bubble sheet process.
 5100:   Allows for - starting a grading run.
 5101:              - downloading existing scan data (original, corrected
 5102:                                                 or skipped info)
 5103: 
 5104:              - uploading new scan data
 5105: 
 5106:  Arguments:
 5107:   $r          - The Apache request object
 5108:   $file2grade - name of the file that contain the scanned data to score
 5109: 
 5110: =cut
 5111: 
 5112: sub scantron_selectphase {
 5113:     my ($r,$file2grade,$symb) = @_;
 5114:     if (!$symb) {return '';}
 5115:     my $map_error;
 5116:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 5117:     if ($map_error) {
 5118:         $r->print('<br />'.&navmap_errormsg().'<br />');
 5119:         return;
 5120:     }
 5121:     my $default_form_data=&defaultFormData($symb);
 5122:     my $file_selector=&scantron_uploads($file2grade);
 5123:     my $format_selector=&scantron_scantab();
 5124:     my $CODE_selector=&scantron_CODElist();
 5125:     my $CODE_unique=&scantron_CODEunique();
 5126:     my $result;
 5127: 
 5128:     $ssi_error = 0;
 5129: 
 5130:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5131:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5132: 
 5133: 	# Chunk of form to prompt for a scantron file upload.
 5134: 
 5135:         $r->print('
 5136:     <br />
 5137:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5138:        '.&Apache::loncommon::start_data_table_header_row().'
 5139:             <th>
 5140:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 5141:             </th>
 5142:        '.&Apache::loncommon::end_data_table_header_row().'
 5143:        '.&Apache::loncommon::start_data_table_row().'
 5144:             <td>
 5145: ');
 5146:     my $default_form_data=&defaultFormData($symb);
 5147:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5148:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5149:     $r->print(&Apache::lonhtmlcommon::scripttag('
 5150:     function checkUpload(formname) {
 5151: 	if (formname.upfile.value == "") {
 5152: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 5153: 	    return false;
 5154: 	}
 5155: 	formname.submit();
 5156:     }'));
 5157:     $r->print('
 5158:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5159:                 '.$default_form_data.'
 5160:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5161:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5162:                 <input name="command" value="scantronupload_save" type="hidden" />
 5163:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5164:                 <br />
 5165:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 5166:               </form>
 5167: ');
 5168: 
 5169:         $r->print('
 5170:             </td>
 5171:        '.&Apache::loncommon::end_data_table_row().'
 5172:        '.&Apache::loncommon::end_data_table().'
 5173: ');
 5174:     }
 5175: 
 5176:     # Chunk of form to prompt for a file to grade and how:
 5177: 
 5178:     $result.= '
 5179:     <br />
 5180:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5181:     <input type="hidden" name="command" value="scantron_warning" />
 5182:     '.$default_form_data.'
 5183:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5184:        '.&Apache::loncommon::start_data_table_header_row().'
 5185:             <th colspan="2">
 5186:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5187:             </th>
 5188:        '.&Apache::loncommon::end_data_table_header_row().'
 5189:        '.&Apache::loncommon::start_data_table_row().'
 5190:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5191:        '.&Apache::loncommon::end_data_table_row().'
 5192:        '.&Apache::loncommon::start_data_table_row().'
 5193:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 5194:        '.&Apache::loncommon::end_data_table_row().'
 5195:        '.&Apache::loncommon::start_data_table_row().'
 5196:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 5197:        '.&Apache::loncommon::end_data_table_row().'
 5198:        '.&Apache::loncommon::start_data_table_row().'
 5199:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5200:        '.&Apache::loncommon::end_data_table_row().'
 5201:        '.&Apache::loncommon::start_data_table_row().'
 5202:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5203:        '.&Apache::loncommon::end_data_table_row().'
 5204:        '.&Apache::loncommon::start_data_table_row().'
 5205: 	    <td> '.&mt('Options:').' </td>
 5206:             <td>
 5207: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5208:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5209:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5210: 	    </td>
 5211:        '.&Apache::loncommon::end_data_table_row().'
 5212:        '.&Apache::loncommon::start_data_table_row().'
 5213:             <td colspan="2">
 5214:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 5215:             </td>
 5216:        '.&Apache::loncommon::end_data_table_row().'
 5217:     '.&Apache::loncommon::end_data_table().'
 5218:     </form>
 5219: ';
 5220:    
 5221:     $r->print($result);
 5222: 
 5223: 
 5224: 
 5225:     # Chunk of the form that prompts to view a scoring office file,
 5226:     # corrected file, skipped records in a file.
 5227: 
 5228:     $r->print('
 5229:    <br />
 5230:    <form action="/adm/grades" name="scantron_download">
 5231:      '.$default_form_data.'
 5232:      <input type="hidden" name="command" value="scantron_download" />
 5233:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5234:        '.&Apache::loncommon::start_data_table_header_row().'
 5235:               <th>
 5236:                 &nbsp;'.&mt('Download a scoring office file').'
 5237:               </th>
 5238:        '.&Apache::loncommon::end_data_table_header_row().'
 5239:        '.&Apache::loncommon::start_data_table_row().'
 5240:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5241:                 <br />
 5242:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5243:        '.&Apache::loncommon::end_data_table_row().'
 5244:      '.&Apache::loncommon::end_data_table().'
 5245:    </form>
 5246:    <br />
 5247: ');
 5248: 
 5249:     &Apache::lonpickcode::code_list($r,2);
 5250: 
 5251:     $r->print('<br /><form method="post" name="checkscantron">'.
 5252:              $default_form_data."\n".
 5253:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5254:              &Apache::loncommon::start_data_table_header_row()."\n".
 5255:              '<th colspan="2">
 5256:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 5257:              '</th>'."\n".
 5258:               &Apache::loncommon::end_data_table_header_row()."\n".
 5259:               &Apache::loncommon::start_data_table_row()."\n".
 5260:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5261:               '<td> '.$sequence_selector.' </td>'.
 5262:               &Apache::loncommon::end_data_table_row()."\n".
 5263:               &Apache::loncommon::start_data_table_row()."\n".
 5264:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5265:               '<td> '.$file_selector.' </td>'."\n".
 5266:               &Apache::loncommon::end_data_table_row()."\n".
 5267:               &Apache::loncommon::start_data_table_row()."\n".
 5268:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5269:               '<td> '.$format_selector.' </td>'."\n".
 5270:               &Apache::loncommon::end_data_table_row()."\n".
 5271:               &Apache::loncommon::start_data_table_row()."\n".
 5272:               '<td> '.&mt('Options').' </td>'."\n".
 5273:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 5274:               &Apache::loncommon::end_data_table_row()."\n".
 5275:               &Apache::loncommon::start_data_table_row()."\n".
 5276:               '<td colspan="2">'."\n".
 5277:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5278:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 5279:               '</td>'."\n".
 5280:               &Apache::loncommon::end_data_table_row()."\n".
 5281:               &Apache::loncommon::end_data_table()."\n".
 5282:               '</form><br />');
 5283:     return;
 5284: }
 5285: 
 5286: =pod
 5287: 
 5288: =item get_scantron_config
 5289: 
 5290:    Parse and return the scantron configuration line selected as a
 5291:    hash of configuration file fields.
 5292: 
 5293:  Arguments:
 5294:     which - the name of the configuration to parse from the file.
 5295: 
 5296: 
 5297:  Returns:
 5298:             If the named configuration is not in the file, an empty
 5299:             hash is returned.
 5300:     a hash with the fields
 5301:       name         - internal name for the this configuration setup
 5302:       description  - text to display to operator that describes this config
 5303:       CODElocation - if 0 or the string 'none'
 5304:                           - no CODE exists for this config
 5305:                      if -1 || the string 'letter'
 5306:                           - a CODE exists for this config and is
 5307:                             a string of letters
 5308:                      Unsupported value (but planned for future support)
 5309:                           if a positive integer
 5310:                                - The CODE exists as the first n items from
 5311:                                  the question section of the form
 5312:                           if the string 'number'
 5313:                                - The CODE exists for this config and is
 5314:                                  a string of numbers
 5315:       CODEstart   - (only matter if a CODE exists) column in the line where
 5316:                      the CODE starts
 5317:       CODElength  - length of the CODE
 5318:       IDstart     - column where the student/employee ID starts
 5319:       IDlength    - length of the student/employee ID info
 5320:       Qstart      - column where the information from the bubbled
 5321:                     'questions' start
 5322:       Qlength     - number of columns comprising a single bubble line from
 5323:                     the sheet. (usually either 1 or 10)
 5324:       Qon         - either a single character representing the character used
 5325:                     to signal a bubble was chosen in the positional setup, or
 5326:                     the string 'letter' if the letter of the chosen bubble is
 5327:                     in the final, or 'number' if a number representing the
 5328:                     chosen bubble is in the file (1->A 0->J)
 5329:       Qoff        - the character used to represent that a bubble was
 5330:                     left blank
 5331:       PaperID     - if the scanning process generates a unique number for each
 5332:                     sheet scanned the column that this ID number starts in
 5333:       PaperIDlength - number of columns that comprise the unique ID number
 5334:                       for the sheet of paper
 5335:       FirstName   - column that the first name starts in
 5336:       FirstNameLength - number of columns that the first name spans
 5337:  
 5338:       LastName    - column that the last name starts in
 5339:       LastNameLength - number of columns that the last name spans
 5340: 
 5341: =cut
 5342: 
 5343: sub get_scantron_config {
 5344:     my ($which) = @_;
 5345:     my @lines = &get_scantronformat_file();
 5346:     my %config;
 5347:     #FIXME probably should move to XML it has already gotten a bit much now
 5348:     foreach my $line (@lines) {
 5349: 	my ($name,$descrip)=split(/:/,$line);
 5350: 	if ($name ne $which ) { next; }
 5351: 	chomp($line);
 5352: 	my @config=split(/:/,$line);
 5353: 	$config{'name'}=$config[0];
 5354: 	$config{'description'}=$config[1];
 5355: 	$config{'CODElocation'}=$config[2];
 5356: 	$config{'CODEstart'}=$config[3];
 5357: 	$config{'CODElength'}=$config[4];
 5358: 	$config{'IDstart'}=$config[5];
 5359: 	$config{'IDlength'}=$config[6];
 5360: 	$config{'Qstart'}=$config[7];
 5361:  	$config{'Qlength'}=$config[8];
 5362: 	$config{'Qoff'}=$config[9];
 5363: 	$config{'Qon'}=$config[10];
 5364: 	$config{'PaperID'}=$config[11];
 5365: 	$config{'PaperIDlength'}=$config[12];
 5366: 	$config{'FirstName'}=$config[13];
 5367: 	$config{'FirstNamelength'}=$config[14];
 5368: 	$config{'LastName'}=$config[15];
 5369: 	$config{'LastNamelength'}=$config[16];
 5370: 	last;
 5371:     }
 5372:     return %config;
 5373: }
 5374: 
 5375: =pod 
 5376: 
 5377: =item username_to_idmap
 5378: 
 5379:     creates a hash keyed by student/employee ID with values of the corresponding
 5380:     student username:domain.
 5381: 
 5382:   Arguments:
 5383: 
 5384:     $classlist - reference to the class list hash. This is a hash
 5385:                  keyed by student name:domain  whose elements are references
 5386:                  to arrays containing various chunks of information
 5387:                  about the student. (See loncoursedata for more info).
 5388: 
 5389:   Returns
 5390:     %idmap - the constructed hash
 5391: 
 5392: =cut
 5393: 
 5394: sub username_to_idmap {
 5395:     my ($classlist)= @_;
 5396:     my %idmap;
 5397:     foreach my $student (keys(%$classlist)) {
 5398: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5399: 	    $student;
 5400:     }
 5401:     return %idmap;
 5402: }
 5403: 
 5404: =pod
 5405: 
 5406: =item scantron_fixup_scanline
 5407: 
 5408:    Process a requested correction to a scanline.
 5409: 
 5410:   Arguments:
 5411:     $scantron_config   - hash from &get_scantron_config()
 5412:     $scan_data         - hash of correction information 
 5413:                           (see &scantron_getfile())
 5414:     $line              - existing scanline
 5415:     $whichline         - line number of the passed in scanline
 5416:     $field             - type of change to process 
 5417:                          (either 
 5418:                           'ID'     -> correct the student/employee ID
 5419:                           'CODE'   -> correct the CODE
 5420:                           'answer' -> fixup the submitted answers)
 5421:     
 5422:    $args               - hash of additional info,
 5423:                           - 'ID' 
 5424:                                'newid' -> studentID to use in replacement
 5425:                                           of existing one
 5426:                           - 'CODE' 
 5427:                                'CODE_ignore_dup' - set to true if duplicates
 5428:                                                    should be ignored.
 5429: 	                       'CODE' - is new code or 'use_unfound'
 5430:                                         if the existing unfound code should
 5431:                                         be used as is
 5432:                           - 'answer'
 5433:                                'response' - new answer or 'none' if blank
 5434:                                'question' - the bubble line to change
 5435:                                'questionnum' - the question identifier,
 5436:                                                may include subquestion. 
 5437: 
 5438:   Returns:
 5439:     $line - the modified scanline
 5440: 
 5441:   Side effects: 
 5442:     $scan_data - may be updated
 5443: 
 5444: =cut
 5445: 
 5446: 
 5447: sub scantron_fixup_scanline {
 5448:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5449:     if ($field eq 'ID') {
 5450: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5451: 	    return ($line,1,'New value too large');
 5452: 	}
 5453: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5454: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5455: 				     $args->{'newid'});
 5456: 	}
 5457: 	substr($line,$$scantron_config{'IDstart'}-1,
 5458: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5459: 	if ($args->{'newid'}=~/^\s*$/) {
 5460: 	    &scan_data($scan_data,"$whichline.user",
 5461: 		       $args->{'username'}.':'.$args->{'domain'});
 5462: 	}
 5463:     } elsif ($field eq 'CODE') {
 5464: 	if ($args->{'CODE_ignore_dup'}) {
 5465: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5466: 	}
 5467: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5468: 	if ($args->{'CODE'} ne 'use_unfound') {
 5469: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5470: 		return ($line,1,'New CODE value too large');
 5471: 	    }
 5472: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5473: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5474: 	    }
 5475: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5476: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5477: 	}
 5478:     } elsif ($field eq 'answer') {
 5479: 	my $length=$scantron_config->{'Qlength'};
 5480: 	my $off=$scantron_config->{'Qoff'};
 5481: 	my $on=$scantron_config->{'Qon'};
 5482: 	my $answer=${off}x$length;
 5483: 	if ($args->{'response'} eq 'none') {
 5484: 	    &scan_data($scan_data,
 5485: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5486: 	} else {
 5487: 	    if ($on eq 'letter') {
 5488: 		my @alphabet=('A'..'Z');
 5489: 		$answer=$alphabet[$args->{'response'}];
 5490: 	    } elsif ($on eq 'number') {
 5491: 		$answer=$args->{'response'}+1;
 5492: 		if ($answer == 10) { $answer = '0'; }
 5493: 	    } else {
 5494: 		substr($answer,$args->{'response'},1)=$on;
 5495: 	    }
 5496: 	    &scan_data($scan_data,
 5497: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5498: 	}
 5499: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5500: 	substr($line,$where-1,$length)=$answer;
 5501:     }
 5502:     return $line;
 5503: }
 5504: 
 5505: =pod
 5506: 
 5507: =item scan_data
 5508: 
 5509:     Edit or look up  an item in the scan_data hash.
 5510: 
 5511:   Arguments:
 5512:     $scan_data  - The hash (see scantron_getfile)
 5513:     $key        - shorthand of the key to edit (actual key is
 5514:                   scantronfilename_key).
 5515:     $data        - New value of the hash entry.
 5516:     $delete      - If true, the entry is removed from the hash.
 5517: 
 5518:   Returns:
 5519:     The new value of the hash table field (undefined if deleted).
 5520: 
 5521: =cut
 5522: 
 5523: 
 5524: sub scan_data {
 5525:     my ($scan_data,$key,$value,$delete)=@_;
 5526:     my $filename=$env{'form.scantron_selectfile'};
 5527:     if (defined($value)) {
 5528: 	$scan_data->{$filename.'_'.$key} = $value;
 5529:     }
 5530:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5531:     return $scan_data->{$filename.'_'.$key};
 5532: }
 5533: 
 5534: # ----- These first few routines are general use routines.----
 5535: 
 5536: # Return the number of occurences of a pattern in a string.
 5537: 
 5538: sub occurence_count {
 5539:     my ($string, $pattern) = @_;
 5540: 
 5541:     my @matches = ($string =~ /$pattern/g);
 5542: 
 5543:     return scalar(@matches);
 5544: }
 5545: 
 5546: 
 5547: # Take a string known to have digits and convert all the
 5548: # digits into letters in the range J,A..I.
 5549: 
 5550: sub digits_to_letters {
 5551:     my ($input) = @_;
 5552: 
 5553:     my @alphabet = ('J', 'A'..'I');
 5554: 
 5555:     my @input    = split(//, $input);
 5556:     my $output ='';
 5557:     for (my $i = 0; $i < scalar(@input); $i++) {
 5558: 	if ($input[$i] =~ /\d/) {
 5559: 	    $output .= $alphabet[$input[$i]];
 5560: 	} else {
 5561: 	    $output .= $input[$i];
 5562: 	}
 5563:     }
 5564:     return $output;
 5565: }
 5566: 
 5567: =pod 
 5568: 
 5569: =item scantron_parse_scanline
 5570: 
 5571:   Decodes a scanline from the selected scantron file
 5572: 
 5573:  Arguments:
 5574:     line             - The text of the scantron file line to process
 5575:     whichline        - Line number
 5576:     scantron_config  - Hash describing the format of the scantron lines.
 5577:     scan_data        - Hash of extra information about the scanline
 5578:                        (see scantron_getfile for more information)
 5579:     just_header      - True if should not process question answers but only
 5580:                        the stuff to the left of the answers.
 5581:  Returns:
 5582:    Hash containing the result of parsing the scanline
 5583: 
 5584:    Keys are all proceeded by the string 'scantron.'
 5585: 
 5586:        CODE    - the CODE in use for this scanline
 5587:        useCODE - 1 if the CODE is invalid but it usage has been forced
 5588:                  by the operator
 5589:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 5590:                             CODEs were selected, but the usage has been
 5591:                             forced by the operator
 5592:        ID  - student/employee ID
 5593:        PaperID - if used, the ID number printed on the sheet when the 
 5594:                  paper was scanned
 5595:        FirstName - first name from the sheet
 5596:        LastName  - last name from the sheet
 5597: 
 5598:      if just_header was not true these key may also exist
 5599: 
 5600:        missingerror - a list of bubble ranges that are considered to be answers
 5601:                       to a single question that don't have any bubbles filled in.
 5602:                       Of the form questionnumber:firstbubblenumber:count.
 5603:        doubleerror  - a list of bubble ranges that are considered to be answers
 5604:                       to a single question that have more than one bubble filled in.
 5605:                       Of the form questionnumber::firstbubblenumber:count
 5606:    
 5607:                 In the above, count is the number of bubble responses in the
 5608:                 input line needed to represent the possible answers to the question.
 5609:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 5610:                 per line would have count = 2.
 5611: 
 5612:        maxquest     - the number of the last bubble line that was parsed
 5613: 
 5614:        (<number> starts at 1)
 5615:        <number>.answer - zero or more letters representing the selected
 5616:                          letters from the scanline for the bubble line 
 5617:                          <number>.
 5618:                          if blank there was either no bubble or there where
 5619:                          multiple bubbles, (consult the keys missingerror and
 5620:                          doubleerror if this is an error condition)
 5621: 
 5622: =cut
 5623: 
 5624: sub scantron_parse_scanline {
 5625:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
 5626: 
 5627:     my %record;
 5628:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 5629:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 5630:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
 5631:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 5632: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 5633: 	if ($$scantron_config{'CODElocation'} < 0 ||
 5634: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 5635: 	    $$scantron_config{'CODElocation'} eq 'number') {
 5636: 	    $record{'scantron.CODE'}=substr($data,
 5637: 					    $$scantron_config{'CODEstart'}-1,
 5638: 					    $$scantron_config{'CODElength'});
 5639: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 5640: 		$record{'scantron.useCODE'}=1;
 5641: 	    }
 5642: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 5643: 		$record{'scantron.CODE_ignore_dup'}=1;
 5644: 	    }
 5645: 	} else {
 5646: 	    #FIXME interpret first N questions
 5647: 	}
 5648:     }
 5649:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 5650: 				  $$scantron_config{'IDlength'});
 5651:     $record{'scantron.PaperID'}=
 5652: 	substr($data,$$scantron_config{'PaperID'}-1,
 5653: 	       $$scantron_config{'PaperIDlength'});
 5654:     $record{'scantron.FirstName'}=
 5655: 	substr($data,$$scantron_config{'FirstName'}-1,
 5656: 	       $$scantron_config{'FirstNamelength'});
 5657:     $record{'scantron.LastName'}=
 5658: 	substr($data,$$scantron_config{'LastName'}-1,
 5659: 	       $$scantron_config{'LastNamelength'});
 5660:     if ($just_header) { return \%record; }
 5661: 
 5662:     my @alphabet=('A'..'Z');
 5663:     my $questnum=0;
 5664:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 5665: 
 5666:     chomp($questions);		# Get rid of any trailing \n.
 5667:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 5668:     while (length($questions)) {
 5669: 	my $answers_needed = $bubble_lines_per_response{$questnum};
 5670:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 5671:                              || 1;
 5672:         $questnum++;
 5673:         my $quest_id = $questnum;
 5674:         my $currentquest = substr($questions,0,$answer_length);
 5675:         $questions       = substr($questions,$answer_length);
 5676:         if (length($currentquest) < $answer_length) { next; }
 5677: 
 5678:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
 5679:             my $subquestnum = 1;
 5680:             my $subquestions = $currentquest;
 5681:             my @subanswers_needed = 
 5682:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
 5683:             foreach my $subans (@subanswers_needed) {
 5684:                 my $subans_length =
 5685:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 5686:                 my $currsubquest = substr($subquestions,0,$subans_length);
 5687:                 $subquestions   = substr($subquestions,$subans_length);
 5688:                 $quest_id = "$questnum.$subquestnum";
 5689:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 5690:                     ($$scantron_config{'Qon'} eq 'number')) {
 5691:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 5692:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 5693:                         \@alphabet,\%record,$scantron_config,$scan_data);
 5694:                 } else {
 5695:                     $ansnum = &scantron_validator_positional($ansnum,
 5696:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
 5697:                 }
 5698:                 $subquestnum ++;
 5699:             }
 5700:         } else {
 5701:             if (($$scantron_config{'Qon'} eq 'letter') ||
 5702:                 ($$scantron_config{'Qon'} eq 'number')) {
 5703:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 5704:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5705:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5706:             } else {
 5707:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 5708:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5709:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5710:             }
 5711:         }
 5712:     }
 5713:     $record{'scantron.maxquest'}=$questnum;
 5714:     return \%record;
 5715: }
 5716: 
 5717: sub scantron_validator_lettnum {
 5718:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 5719:         $alphabet,$record,$scantron_config,$scan_data) = @_;
 5720: 
 5721:     # Qon 'letter' implies for each slot in currquest we have:
 5722:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 5723:     #    about anything else (esp. a value of Qoff) for missing
 5724:     #    bubbles.
 5725:     #
 5726:     # Qon 'number' implies each slot gives a digit that indexes the
 5727:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 5728:     #    and * or ? for double bubbles on a single line.
 5729:     #
 5730: 
 5731:     my $matchon;
 5732:     if ($$scantron_config{'Qon'} eq 'letter') {
 5733:         $matchon = '[A-Z]';
 5734:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 5735:         $matchon = '\d';
 5736:     }
 5737:     my $occurrences = 0;
 5738:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5739:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5740:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5741:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5742:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5743:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5744:         my @singlelines = split('',$currquest);
 5745:         foreach my $entry (@singlelines) {
 5746:             $occurrences = &occurence_count($entry,$matchon);
 5747:             if ($occurrences > 1) {
 5748:                 last;
 5749:             }
 5750:         } 
 5751:     } else {
 5752:         $occurrences = &occurence_count($currquest,$matchon); 
 5753:     }
 5754:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 5755:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5756:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5757:             my $bubble = substr($currquest,$ans,1);
 5758:             if ($bubble =~ /$matchon/ ) {
 5759:                 if ($$scantron_config{'Qon'} eq 'number') {
 5760:                     if ($bubble == 0) {
 5761:                         $bubble = 10; 
 5762:                     }
 5763:                     $record->{"scantron.$ansnum.answer"} = 
 5764:                         $alphabet->[$bubble-1];
 5765:                 } else {
 5766:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 5767:                 }
 5768:             } else {
 5769:                 $record->{"scantron.$ansnum.answer"}='';
 5770:             }
 5771:             $ansnum++;
 5772:         }
 5773:     } elsif (!defined($currquest)
 5774:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 5775:             || (&occurence_count($currquest,$matchon) == 0)) {
 5776:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5777:             $record->{"scantron.$ansnum.answer"}='';
 5778:             $ansnum++;
 5779:         }
 5780:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5781:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 5782:         }
 5783:     } else {
 5784:         if ($$scantron_config{'Qon'} eq 'number') {
 5785:             $currquest = &digits_to_letters($currquest);            
 5786:         }
 5787:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5788:             my $bubble = substr($currquest,$ans,1);
 5789:             $record->{"scantron.$ansnum.answer"} = $bubble;
 5790:             $ansnum++;
 5791:         }
 5792:     }
 5793:     return $ansnum;
 5794: }
 5795: 
 5796: sub scantron_validator_positional {
 5797:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 5798:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
 5799: 
 5800:     # Otherwise there's a positional notation;
 5801:     # each bubble line requires Qlength items, and there are filled in
 5802:     # bubbles for each case where there 'Qon' characters.
 5803:     #
 5804: 
 5805:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 5806: 
 5807:     # If the split only gives us one element.. the full length of the
 5808:     # answer string, no bubbles are filled in:
 5809: 
 5810:     if ($answers_needed eq '') {
 5811:         return;
 5812:     }
 5813: 
 5814:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 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:     } elsif (scalar(@array) == 2) {
 5823:         my $location = length($array[0]);
 5824:         my $line_num = int($location / $$scantron_config{'Qlength'});
 5825:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 5826:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5827:             if ($ans eq $line_num) {
 5828:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 5829:             } else {
 5830:                 $record->{"scantron.$ansnum.answer"} = ' ';
 5831:             }
 5832:             $ansnum++;
 5833:          }
 5834:     } else {
 5835:         #  If there's more than one instance of a bubble character
 5836:         #  That's a double bubble; with positional notation we can
 5837:         #  record all the bubbles filled in as well as the
 5838:         #  fact this response consists of multiple bubbles.
 5839:         #
 5840:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5841:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5842:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5843:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5844:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5845:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5846:             my $doubleerror = 0;
 5847:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 5848:                    (!$doubleerror)) {
 5849:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 5850:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 5851:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 5852:                if (length(@currarray) > 2) {
 5853:                    $doubleerror = 1;
 5854:                } 
 5855:             }
 5856:             if ($doubleerror) {
 5857:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5858:             }
 5859:         } else {
 5860:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5861:         }
 5862:         my $item = $ansnum;
 5863:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5864:             $record->{"scantron.$item.answer"} = '';
 5865:             $item ++;
 5866:         }
 5867: 
 5868:         my @ans=@array;
 5869:         my $i=0;
 5870:         my $increment = 0;
 5871:         while ($#ans) {
 5872:             $i+=length($ans[0]) + $increment;
 5873:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 5874:             my $bubble = $i%$$scantron_config{'Qlength'};
 5875:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 5876:             shift(@ans);
 5877:             $increment = 1;
 5878:         }
 5879:         $ansnum += $answers_needed;
 5880:     }
 5881:     return $ansnum;
 5882: }
 5883: 
 5884: =pod
 5885: 
 5886: =item scantron_add_delay
 5887: 
 5888:    Adds an error message that occurred during the grading phase to a
 5889:    queue of messages to be shown after grading pass is complete
 5890: 
 5891:  Arguments:
 5892:    $delayqueue  - arrary ref of hash ref of error messages
 5893:    $scanline    - the scanline that caused the error
 5894:    $errormesage - the error message
 5895:    $errorcode   - a numeric code for the error
 5896: 
 5897:  Side Effects:
 5898:    updates the $delayqueue to have a new hash ref of the error
 5899: 
 5900: =cut
 5901: 
 5902: sub scantron_add_delay {
 5903:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 5904:     push(@$delayqueue,
 5905: 	 {'line' => $scanline, 'emsg' => $errormessage,
 5906: 	  'ecode' => $errorcode }
 5907: 	 );
 5908: }
 5909: 
 5910: =pod
 5911: 
 5912: =item scantron_find_student
 5913: 
 5914:    Finds the username for the current scanline
 5915: 
 5916:   Arguments:
 5917:    $scantron_record - hash result from scantron_parse_scanline
 5918:    $scan_data       - hash of correction information 
 5919:                       (see &scantron_getfile() form more information)
 5920:    $idmap           - hash from &username_to_idmap()
 5921:    $line            - number of current scanline
 5922:  
 5923:   Returns:
 5924:    Either 'username:domain' or undef if unknown
 5925: 
 5926: =cut
 5927: 
 5928: sub scantron_find_student {
 5929:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 5930:     my $scanID=$$scantron_record{'scantron.ID'};
 5931:     if ($scanID =~ /^\s*$/) {
 5932:  	return &scan_data($scan_data,"$line.user");
 5933:     }
 5934:     foreach my $id (keys(%$idmap)) {
 5935:  	if (lc($id) eq lc($scanID)) {
 5936:  	    return $$idmap{$id};
 5937:  	}
 5938:     }
 5939:     return undef;
 5940: }
 5941: 
 5942: =pod
 5943: 
 5944: =item scantron_filter
 5945: 
 5946:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 5947:    hidden resources was selected
 5948: 
 5949: =cut
 5950: 
 5951: sub scantron_filter {
 5952:     my ($curres)=@_;
 5953: 
 5954:     if (ref($curres) && $curres->is_problem()) {
 5955: 	# if the user has asked to not have either hidden
 5956: 	# or 'randomout' controlled resources to be graded
 5957: 	# don't include them
 5958: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 5959: 	    && $curres->randomout) {
 5960: 	    return 0;
 5961: 	}
 5962: 	return 1;
 5963:     }
 5964:     return 0;
 5965: }
 5966: 
 5967: =pod
 5968: 
 5969: =item scantron_process_corrections
 5970: 
 5971:    Gets correction information out of submitted form data and corrects
 5972:    the scanline
 5973: 
 5974: =cut
 5975: 
 5976: sub scantron_process_corrections {
 5977:     my ($r) = @_;
 5978:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 5979:     my ($scanlines,$scan_data)=&scantron_getfile();
 5980:     my $classlist=&Apache::loncoursedata::get_classlist();
 5981:     my $which=$env{'form.scantron_line'};
 5982:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 5983:     my ($skip,$err,$errmsg);
 5984:     if ($env{'form.scantron_skip_record'}) {
 5985: 	$skip=1;
 5986:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 5987: 	my $newstudent=$env{'form.scantron_username'}.':'.
 5988: 	    $env{'form.scantron_domain'};
 5989: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 5990: 	($line,$err,$errmsg)=
 5991: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 5992: 				     'ID',{'newid'=>$newid,
 5993: 				    'username'=>$env{'form.scantron_username'},
 5994: 				    'domain'=>$env{'form.scantron_domain'}});
 5995:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 5996: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 5997: 	my $newCODE;
 5998: 	my %args;
 5999: 	if      ($resolution eq 'use_unfound') {
 6000: 	    $newCODE='use_unfound';
 6001: 	} elsif ($resolution eq 'use_found') {
 6002: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6003: 	} elsif ($resolution eq 'use_typed') {
 6004: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6005: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6006: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6007: 	}
 6008: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6009: 	    $args{'CODE_ignore_dup'}=1;
 6010: 	}
 6011: 	$args{'CODE'}=$newCODE;
 6012: 	($line,$err,$errmsg)=
 6013: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6014: 				     'CODE',\%args);
 6015:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6016: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6017: 	    ($line,$err,$errmsg)=
 6018: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6019: 					 $which,'answer',
 6020: 					 { 'question'=>$question,
 6021: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6022:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6023: 	    if ($err) { last; }
 6024: 	}
 6025:     }
 6026:     if ($err) {
 6027: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
 6028:     } else {
 6029: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 6030: 	&scantron_putfile($scanlines,$scan_data);
 6031:     }
 6032: }
 6033: 
 6034: =pod
 6035: 
 6036: =item reset_skipping_status
 6037: 
 6038:    Forgets the current set of remember skipped scanlines (and thus
 6039:    reverts back to considering all lines in the
 6040:    scantron_skipped_<filename> file)
 6041: 
 6042: =cut
 6043: 
 6044: sub reset_skipping_status {
 6045:     my ($scanlines,$scan_data)=&scantron_getfile();
 6046:     &scan_data($scan_data,'remember_skipping',undef,1);
 6047:     &scantron_putfile(undef,$scan_data);
 6048: }
 6049: 
 6050: =pod
 6051: 
 6052: =item start_skipping
 6053: 
 6054:    Marks a scanline to be skipped. 
 6055: 
 6056: =cut
 6057: 
 6058: sub start_skipping {
 6059:     my ($scan_data,$i)=@_;
 6060:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6061:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6062: 	$remembered{$i}=2;
 6063:     } else {
 6064: 	$remembered{$i}=1;
 6065:     }
 6066:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6067: }
 6068: 
 6069: =pod
 6070: 
 6071: =item should_be_skipped
 6072: 
 6073:    Checks whether a scanline should be skipped.
 6074: 
 6075: =cut
 6076: 
 6077: sub should_be_skipped {
 6078:     my ($scanlines,$scan_data,$i)=@_;
 6079:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6080: 	# not redoing old skips
 6081: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6082: 	return 0;
 6083:     }
 6084:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6085: 
 6086:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6087: 	return 0;
 6088:     }
 6089:     return 1;
 6090: }
 6091: 
 6092: =pod
 6093: 
 6094: =item remember_current_skipped
 6095: 
 6096:    Discovers what scanlines are in the scantron_skipped_<filename>
 6097:    file and remembers them into scan_data for later use.
 6098: 
 6099: =cut
 6100: 
 6101: sub remember_current_skipped {
 6102:     my ($scanlines,$scan_data)=&scantron_getfile();
 6103:     my %to_remember;
 6104:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6105: 	if ($scanlines->{'skipped'}[$i]) {
 6106: 	    $to_remember{$i}=1;
 6107: 	}
 6108:     }
 6109: 
 6110:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6111:     &scantron_putfile(undef,$scan_data);
 6112: }
 6113: 
 6114: =pod
 6115: 
 6116: =item check_for_error
 6117: 
 6118:     Checks if there was an error when attempting to remove a specific
 6119:     scantron_.. bubble sheet data file. Prints out an error if
 6120:     something went wrong.
 6121: 
 6122: =cut
 6123: 
 6124: sub check_for_error {
 6125:     my ($r,$result)=@_;
 6126:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6127: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6128:     }
 6129: }
 6130: 
 6131: =pod
 6132: 
 6133: =item scantron_warning_screen
 6134: 
 6135:    Interstitial screen to make sure the operator has selected the
 6136:    correct options before we start the validation phase.
 6137: 
 6138: =cut
 6139: 
 6140: sub scantron_warning_screen {
 6141:     my ($button_text)=@_;
 6142:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6143:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6144:     my $CODElist;
 6145:     if ($scantron_config{'CODElocation'} &&
 6146: 	$scantron_config{'CODEstart'} &&
 6147: 	$scantron_config{'CODElength'}) {
 6148: 	$CODElist=$env{'form.scantron_CODElist'};
 6149: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
 6150: 	$CODElist=
 6151: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6152: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6153:     }
 6154:     return ('
 6155: <p>
 6156: <span class="LC_warning">
 6157: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
 6158: </p>
 6159: <table>
 6160: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6161: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6162: '.$CODElist.'
 6163: </table>
 6164: <br />
 6165: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
 6166: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
 6167: 
 6168: <br />
 6169: ');
 6170: }
 6171: 
 6172: =pod
 6173: 
 6174: =item scantron_do_warning
 6175: 
 6176:    Check if the operator has picked something for all required
 6177:    fields. Error out if something is missing.
 6178: 
 6179: =cut
 6180: 
 6181: sub scantron_do_warning {
 6182:     my ($r,$symb)=@_;
 6183:     if (!$symb) {return '';}
 6184:     my $default_form_data=&defaultFormData($symb);
 6185:     $r->print(&scantron_form_start().$default_form_data);
 6186:     if ( $env{'form.selectpage'} eq '' ||
 6187: 	 $env{'form.scantron_selectfile'} eq '' ||
 6188: 	 $env{'form.scantron_format'} eq '' ) {
 6189: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
 6190: 	if ( $env{'form.selectpage'} eq '') {
 6191: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6192: 	} 
 6193: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6194: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a file that contains the student\'s response data.').'</span></p>');
 6195: 	} 
 6196: 	if ( $env{'form.scantron_format'} eq '') {
 6197: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a the format of the student\'s response data.').'</span></p>');
 6198: 	} 
 6199:     } else {
 6200: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
 6201: 	$r->print('
 6202: '.$warning.'
 6203: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6204: <input type="hidden" name="command" value="scantron_validate" />
 6205: ');
 6206:     }
 6207:     $r->print("</form><br />");
 6208:     return '';
 6209: }
 6210: 
 6211: =pod
 6212: 
 6213: =item scantron_form_start
 6214: 
 6215:     html hidden input for remembering all selected grading options
 6216: 
 6217: =cut
 6218: 
 6219: sub scantron_form_start {
 6220:     my ($max_bubble)=@_;
 6221:     my $result= <<SCANTRONFORM;
 6222: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6223:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6224:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6225:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6226:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6227:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6228:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6229:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6230:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6231:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6232: SCANTRONFORM
 6233: 
 6234:   my $line = 0;
 6235:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6236:        my $chunk =
 6237: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6238:        $chunk .=
 6239: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6240:        $chunk .= 
 6241:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6242:        $chunk .=
 6243:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6244:        $result .= $chunk;
 6245:        $line++;
 6246:    }
 6247:     return $result;
 6248: }
 6249: 
 6250: =pod
 6251: 
 6252: =item scantron_validate_file
 6253: 
 6254:     Dispatch routine for doing validation of a bubble sheet data file.
 6255: 
 6256:     Also processes any necessary information resets that need to
 6257:     occur before validation begins (ignore previous corrections,
 6258:     restarting the skipped records processing)
 6259: 
 6260: =cut
 6261: 
 6262: sub scantron_validate_file {
 6263:     my ($r,$symb) = @_;
 6264:     if (!$symb) {return '';}
 6265:     my $default_form_data=&defaultFormData($symb);
 6266:     
 6267:     # do the detection of only doing skipped records first befroe we delete
 6268:     # them when doing the corrections reset
 6269:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6270: 	&reset_skipping_status();
 6271:     }
 6272:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6273: 	&remember_current_skipped();
 6274: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6275:     }
 6276: 
 6277:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6278: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6279: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6280: 	&check_for_error($r,&scantron_remove_scan_data());
 6281: 	$env{'form.scantron_options_ignore'}='done';
 6282:     }
 6283: 
 6284:     if ($env{'form.scantron_corrections'}) {
 6285: 	&scantron_process_corrections($r);
 6286:     }
 6287:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6288:     #get the student pick code ready
 6289:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6290:     my $nav_error;
 6291:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
 6292:     if ($nav_error) {
 6293:         $r->print(&navmap_errormsg());
 6294:         return '';
 6295:     }
 6296:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6297:     $r->print($result);
 6298:     
 6299:     my @validate_phases=( 'sequence',
 6300: 			  'ID',
 6301: 			  'CODE',
 6302: 			  'doublebubble',
 6303: 			  'missingbubbles');
 6304:     if (!$env{'form.validatepass'}) {
 6305: 	$env{'form.validatepass'} = 0;
 6306:     }
 6307:     my $currentphase=$env{'form.validatepass'};
 6308: 
 6309: 
 6310:     my $stop=0;
 6311:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6312: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6313: 	$r->rflush();
 6314: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6315: 	{
 6316: 	    no strict 'refs';
 6317: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6318: 	}
 6319:     }
 6320:     if (!$stop) {
 6321: 	my $warning=&scantron_warning_screen('Start Grading');
 6322: 	$r->print(&mt('Validation process complete.').'<br />'.
 6323:                   $warning.
 6324:                   &mt('Perform verification for each student after storage of submissions?').
 6325:                   '&nbsp;<span class="LC_nobreak"><label>'.
 6326:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 6327:                   ('&nbsp;'x3).'<label>'.
 6328:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 6329:                   '</label></span><br />'.
 6330:                   &mt('Grading will take longer if you use verification.').'<br />'.
 6331:                   &mt("Alternatively, the 'Review bubblesheet data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
 6332:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 6333:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 6334:     } else {
 6335: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6336: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6337:     }
 6338:     if ($stop) {
 6339: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6340: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 6341: 	    $r->print(' '.&mt('this error').' <br />');
 6342: 
 6343: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
 6344: 	} else {
 6345:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6346: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 6347:             } else {
 6348:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 6349:             }
 6350: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6351: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6352: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6353: 	}
 6354:     }
 6355:     $r->print(" </form><br />");
 6356:     return '';
 6357: }
 6358: 
 6359: 
 6360: =pod
 6361: 
 6362: =item scantron_remove_file
 6363: 
 6364:    Removes the requested bubble sheet data file, makes sure that
 6365:    scantron_original_<filename> is never removed
 6366: 
 6367: 
 6368: =cut
 6369: 
 6370: sub scantron_remove_file {
 6371:     my ($which)=@_;
 6372:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6373:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6374:     my $file='scantron_';
 6375:     if ($which eq 'corrected' || $which eq 'skipped') {
 6376: 	$file.=$which.'_';
 6377:     } else {
 6378: 	return 'refused';
 6379:     }
 6380:     $file.=$env{'form.scantron_selectfile'};
 6381:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6382: }
 6383: 
 6384: 
 6385: =pod
 6386: 
 6387: =item scantron_remove_scan_data
 6388: 
 6389:    Removes all scan_data correction for the requested bubble sheet
 6390:    data file.  (In the case that both the are doing skipped records we need
 6391:    to remember the old skipped lines for the time being so that element
 6392:    persists for a while.)
 6393: 
 6394: =cut
 6395: 
 6396: sub scantron_remove_scan_data {
 6397:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6398:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6399:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6400:     my @todelete;
 6401:     my $filename=$env{'form.scantron_selectfile'};
 6402:     foreach my $key (@keys) {
 6403: 	if ($key=~/^\Q$filename\E_/) {
 6404: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6405: 		$key=~/remember_skipping/) {
 6406: 		next;
 6407: 	    }
 6408: 	    push(@todelete,$key);
 6409: 	}
 6410:     }
 6411:     my $result;
 6412:     if (@todelete) {
 6413: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6414: 				       \@todelete,$cdom,$cname);
 6415:     } else {
 6416: 	$result = 'ok';
 6417:     }
 6418:     return $result;
 6419: }
 6420: 
 6421: 
 6422: =pod
 6423: 
 6424: =item scantron_getfile
 6425: 
 6426:     Fetches the requested bubble sheet data file (all 3 versions), and
 6427:     the scan_data hash
 6428:   
 6429:   Arguments:
 6430:     None
 6431: 
 6432:   Returns:
 6433:     2 hash references
 6434: 
 6435:      - first one has 
 6436:          orig      -
 6437:          corrected -
 6438:          skipped   -  each of which points to an array ref of the specified
 6439:                       file broken up into individual lines
 6440:          count     - number of scanlines
 6441:  
 6442:      - second is the scan_data hash possible keys are
 6443:        ($number refers to scanline numbered $number and thus the key affects
 6444:         only that scanline
 6445:         $bubline refers to the specific bubble line element and the aspects
 6446:         refers to that specific bubble line element)
 6447: 
 6448:        $number.user - username:domain to use
 6449:        $number.CODE_ignore_dup 
 6450:                     - ignore the duplicate CODE error 
 6451:        $number.useCODE
 6452:                     - use the CODE in the scanline as is
 6453:        $number.no_bubble.$bubline
 6454:                     - it is valid that there is no bubbled in bubble
 6455:                       at $number $bubline
 6456:        remember_skipping
 6457:                     - a frozen hash containing keys of $number and values
 6458:                       of either 
 6459:                         1 - we are on a 'do skipped records pass' and plan
 6460:                             on processing this line
 6461:                         2 - we are on a 'do skipped records pass' and this
 6462:                             scanline has been marked to skip yet again
 6463: 
 6464: =cut
 6465: 
 6466: sub scantron_getfile {
 6467:     #FIXME really would prefer a scantron directory
 6468:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6469:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6470:     my $lines;
 6471:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6472: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 6473:     my %scanlines;
 6474:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 6475:     my $temp=$scanlines{'orig'};
 6476:     $scanlines{'count'}=$#$temp;
 6477: 
 6478:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6479: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 6480:     if ($lines eq '-1') {
 6481: 	$scanlines{'corrected'}=[];
 6482:     } else {
 6483: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 6484:     }
 6485:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6486: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 6487:     if ($lines eq '-1') {
 6488: 	$scanlines{'skipped'}=[];
 6489:     } else {
 6490: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 6491:     }
 6492:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 6493:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 6494:     my %scan_data = @tmp;
 6495:     return (\%scanlines,\%scan_data);
 6496: }
 6497: 
 6498: =pod
 6499: 
 6500: =item lonnet_putfile
 6501: 
 6502:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 6503: 
 6504:  Arguments:
 6505:    $contents - data to store
 6506:    $filename - filename to store $contents into
 6507: 
 6508:  Returns:
 6509:    result value from &Apache::lonnet::finishuserfileupload
 6510: 
 6511: =cut
 6512: 
 6513: sub lonnet_putfile {
 6514:     my ($contents,$filename)=@_;
 6515:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6516:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6517:     $env{'form.sillywaytopassafilearound'}=$contents;
 6518:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 6519: 
 6520: }
 6521: 
 6522: =pod
 6523: 
 6524: =item scantron_putfile
 6525: 
 6526:     Stores the current version of the bubble sheet data files, and the
 6527:     scan_data hash. (Does not modify the original version only the
 6528:     corrected and skipped versions.
 6529: 
 6530:  Arguments:
 6531:     $scanlines - hash ref that looks like the first return value from
 6532:                  &scantron_getfile()
 6533:     $scan_data - hash ref that looks like the second return value from
 6534:                  &scantron_getfile()
 6535: 
 6536: =cut
 6537: 
 6538: sub scantron_putfile {
 6539:     my ($scanlines,$scan_data) = @_;
 6540:     #FIXME really would prefer a scantron directory
 6541:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6542:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6543:     if ($scanlines) {
 6544: 	my $prefix='scantron_';
 6545: # no need to update orig, shouldn't change
 6546: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 6547: #		    $env{'form.scantron_selectfile'});
 6548: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 6549: 			$prefix.'corrected_'.
 6550: 			$env{'form.scantron_selectfile'});
 6551: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 6552: 			$prefix.'skipped_'.
 6553: 			$env{'form.scantron_selectfile'});
 6554:     }
 6555:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 6556: }
 6557: 
 6558: =pod
 6559: 
 6560: =item scantron_get_line
 6561: 
 6562:    Returns the correct version of the scanline
 6563: 
 6564:  Arguments:
 6565:     $scanlines - hash ref that looks like the first return value from
 6566:                  &scantron_getfile()
 6567:     $scan_data - hash ref that looks like the second return value from
 6568:                  &scantron_getfile()
 6569:     $i         - number of the requested line (starts at 0)
 6570: 
 6571:  Returns:
 6572:    A scanline, (either the original or the corrected one if it
 6573:    exists), or undef if the requested scanline should be
 6574:    skipped. (Either because it's an skipped scanline, or it's an
 6575:    unskipped scanline and we are not doing a 'do skipped scanlines'
 6576:    pass.
 6577: 
 6578: =cut
 6579: 
 6580: sub scantron_get_line {
 6581:     my ($scanlines,$scan_data,$i)=@_;
 6582:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 6583:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 6584:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 6585:     return $scanlines->{'orig'}[$i]; 
 6586: }
 6587: 
 6588: =pod
 6589: 
 6590: =item scantron_todo_count
 6591: 
 6592:     Counts the number of scanlines that need processing.
 6593: 
 6594:  Arguments:
 6595:     $scanlines - hash ref that looks like the first return value from
 6596:                  &scantron_getfile()
 6597:     $scan_data - hash ref that looks like the second return value from
 6598:                  &scantron_getfile()
 6599: 
 6600:  Returns:
 6601:     $count - number of scanlines to process
 6602: 
 6603: =cut
 6604: 
 6605: sub get_todo_count {
 6606:     my ($scanlines,$scan_data)=@_;
 6607:     my $count=0;
 6608:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6609: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6610: 	if ($line=~/^[\s\cz]*$/) { next; }
 6611: 	$count++;
 6612:     }
 6613:     return $count;
 6614: }
 6615: 
 6616: =pod
 6617: 
 6618: =item scantron_put_line
 6619: 
 6620:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
 6621:     data file.
 6622: 
 6623:  Arguments:
 6624:     $scanlines - hash ref that looks like the first return value from
 6625:                  &scantron_getfile()
 6626:     $scan_data - hash ref that looks like the second return value from
 6627:                  &scantron_getfile()
 6628:     $i         - line number to update
 6629:     $newline   - contents of the updated scanline
 6630:     $skip      - if true make the line for skipping and update the
 6631:                  'skipped' file
 6632: 
 6633: =cut
 6634: 
 6635: sub scantron_put_line {
 6636:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 6637:     if ($skip) {
 6638: 	$scanlines->{'skipped'}[$i]=$newline;
 6639: 	&start_skipping($scan_data,$i);
 6640: 	return;
 6641:     }
 6642:     $scanlines->{'corrected'}[$i]=$newline;
 6643: }
 6644: 
 6645: =pod
 6646: 
 6647: =item scantron_clear_skip
 6648: 
 6649:    Remove a line from the 'skipped' file
 6650: 
 6651:  Arguments:
 6652:     $scanlines - hash ref that looks like the first return value from
 6653:                  &scantron_getfile()
 6654:     $scan_data - hash ref that looks like the second return value from
 6655:                  &scantron_getfile()
 6656:     $i         - line number to update
 6657: 
 6658: =cut
 6659: 
 6660: sub scantron_clear_skip {
 6661:     my ($scanlines,$scan_data,$i)=@_;
 6662:     if (exists($scanlines->{'skipped'}[$i])) {
 6663: 	undef($scanlines->{'skipped'}[$i]);
 6664: 	return 1;
 6665:     }
 6666:     return 0;
 6667: }
 6668: 
 6669: =pod
 6670: 
 6671: =item scantron_filter_not_exam
 6672: 
 6673:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 6674:    filter out resources that are not marked as 'exam' mode
 6675: 
 6676: =cut
 6677: 
 6678: sub scantron_filter_not_exam {
 6679:     my ($curres)=@_;
 6680:     
 6681:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 6682: 	# if the user has asked to not have either hidden
 6683: 	# or 'randomout' controlled resources to be graded
 6684: 	# don't include them
 6685: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6686: 	    && $curres->randomout) {
 6687: 	    return 0;
 6688: 	}
 6689: 	return 1;
 6690:     }
 6691:     return 0;
 6692: }
 6693: 
 6694: =pod
 6695: 
 6696: =item scantron_validate_sequence
 6697: 
 6698:     Validates the selected sequence, checking for resource that are
 6699:     not set to exam mode.
 6700: 
 6701: =cut
 6702: 
 6703: sub scantron_validate_sequence {
 6704:     my ($r,$currentphase) = @_;
 6705: 
 6706:     my $navmap=Apache::lonnavmaps::navmap->new();
 6707:     unless (ref($navmap)) {
 6708:         $r->print(&navmap_errormsg());
 6709:         return (1,$currentphase);
 6710:     }
 6711:     my (undef,undef,$sequence)=
 6712: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6713: 
 6714:     my $map=$navmap->getResourceByUrl($sequence);
 6715: 
 6716:     $r->print('<input type="hidden" name="validate_sequence_exam"
 6717:                                     value="ignore" />');
 6718:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 6719: 	my @resources=
 6720: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 6721: 	if (@resources) {
 6722: 	    $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>");
 6723: 	    return (1,$currentphase);
 6724: 	}
 6725:     }
 6726: 
 6727:     return (0,$currentphase+1);
 6728: }
 6729: 
 6730: 
 6731: 
 6732: sub scantron_validate_ID {
 6733:     my ($r,$currentphase) = @_;
 6734:     
 6735:     #get student info
 6736:     my $classlist=&Apache::loncoursedata::get_classlist();
 6737:     my %idmap=&username_to_idmap($classlist);
 6738: 
 6739:     #get scantron line setup
 6740:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6741:     my ($scanlines,$scan_data)=&scantron_getfile();
 6742: 
 6743:     my $nav_error;
 6744:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble_lines.. array.
 6745:     if ($nav_error) {
 6746:         $r->print(&navmap_errormsg());
 6747:         return(1,$currentphase);
 6748:     }
 6749: 
 6750:     my %found=('ids'=>{},'usernames'=>{});
 6751:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6752: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6753: 	if ($line=~/^[\s\cz]*$/) { next; }
 6754: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6755: 						 $scan_data);
 6756: 	my $id=$$scan_record{'scantron.ID'};
 6757: 	my $found;
 6758: 	foreach my $checkid (keys(%idmap)) {
 6759: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 6760: 	}
 6761: 	if ($found) {
 6762: 	    my $username=$idmap{$found};
 6763: 	    if ($found{'ids'}{$found}) {
 6764: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6765: 					 $line,'duplicateID',$found);
 6766: 		return(1,$currentphase);
 6767: 	    } elsif ($found{'usernames'}{$username}) {
 6768: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6769: 					 $line,'duplicateID',$username);
 6770: 		return(1,$currentphase);
 6771: 	    }
 6772: 	    #FIXME store away line we previously saw the ID on to use above
 6773: 	    $found{'ids'}{$found}++;
 6774: 	    $found{'usernames'}{$username}++;
 6775: 	} else {
 6776: 	    if ($id =~ /^\s*$/) {
 6777: 		my $username=&scan_data($scan_data,"$i.user");
 6778: 		if (defined($username) && $found{'usernames'}{$username}) {
 6779: 		    &scantron_get_correction($r,$i,$scan_record,
 6780: 					     \%scantron_config,
 6781: 					     $line,'duplicateID',$username);
 6782: 		    return(1,$currentphase);
 6783: 		} elsif (!defined($username)) {
 6784: 		    &scantron_get_correction($r,$i,$scan_record,
 6785: 					     \%scantron_config,
 6786: 					     $line,'incorrectID');
 6787: 		    return(1,$currentphase);
 6788: 		}
 6789: 		$found{'usernames'}{$username}++;
 6790: 	    } else {
 6791: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6792: 					 $line,'incorrectID');
 6793: 		return(1,$currentphase);
 6794: 	    }
 6795: 	}
 6796:     }
 6797: 
 6798:     return (0,$currentphase+1);
 6799: }
 6800: 
 6801: 
 6802: sub scantron_get_correction {
 6803:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
 6804: #FIXME in the case of a duplicated ID the previous line, probably need
 6805: #to show both the current line and the previous one and allow skipping
 6806: #the previous one or the current one
 6807: 
 6808:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 6809: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6810: 			    " for PaperID <tt>[_1]</tt>",
 6811: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
 6812:     } else {
 6813: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6814: 			    " in scanline [_1] <pre>[_2]</pre>",
 6815: 			    $i,$line)."</p> \n");
 6816:     }
 6817:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
 6818: 			  "The name on the paper is [_2],[_3]",
 6819: 			  $$scan_record{'scantron.ID'},
 6820: 			  $$scan_record{'scantron.LastName'},
 6821: 			  $$scan_record{'scantron.FirstName'})."</p>";
 6822: 
 6823:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 6824:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 6825:                            # Array populated for doublebubble or
 6826:     my @lines_to_correct;  # missingbubble errors to build javascript
 6827:                            # to validate radio button checking   
 6828: 
 6829:     if ($error =~ /ID$/) {
 6830: 	if ($error eq 'incorrectID') {
 6831: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
 6832: 		      "</p>\n");
 6833: 	} elsif ($error eq 'duplicateID') {
 6834: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 6835: 	}
 6836: 	$r->print($message);
 6837: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6838: 	$r->print("\n<ul><li> ");
 6839: 	#FIXME it would be nice if this sent back the user ID and
 6840: 	#could do partial userID matches
 6841: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 6842: 				       'scantron_username','scantron_domain'));
 6843: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 6844: 	$r->print("\n@".
 6845: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 6846: 
 6847: 	$r->print('</li>');
 6848:     } elsif ($error =~ /CODE$/) {
 6849: 	if ($error eq 'incorrectCODE') {
 6850: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 6851: 	} elsif ($error eq 'duplicateCODE') {
 6852: 	    $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");
 6853: 	}
 6854: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
 6855: 			    $$scan_record{'scantron.CODE'})."<br />\n");
 6856: 	$r->print($message);
 6857: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6858: 	$r->print("\n<br /> ");
 6859: 	my $i=0;
 6860: 	if ($error eq 'incorrectCODE' 
 6861: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 6862: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 6863: 	    if ($closest > 0) {
 6864: 		foreach my $testcode (@{$closest}) {
 6865: 		    my $checked='';
 6866: 		    if (!$i) { $checked=' checked="checked"'; }
 6867: 		    $r->print("
 6868:    <label>
 6869:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 6870:        ".&mt("Use the similar CODE [_1] instead.",
 6871: 	    "<b><tt>".$testcode."</tt></b>")."
 6872:     </label>
 6873:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 6874: 		    $r->print("\n<br />");
 6875: 		    $i++;
 6876: 		}
 6877: 	    }
 6878: 	}
 6879: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 6880: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 6881: 	    $r->print("
 6882:     <label>
 6883:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 6884:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
 6885: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 6886:     </label>");
 6887: 	    $r->print("\n<br />");
 6888: 	}
 6889: 
 6890: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
 6891: function change_radio(field) {
 6892:     var slct=document.scantronupload.scantron_CODE_resolution;
 6893:     var i;
 6894:     for (i=0;i<slct.length;i++) {
 6895:         if (slct[i].value==field) { slct[i].checked=true; }
 6896:     }
 6897: }
 6898: ENDSCRIPT
 6899: 	my $href="/adm/pickcode?".
 6900: 	   "form=".&escape("scantronupload").
 6901: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 6902: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 6903: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 6904: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 6905: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 6906: 	    $r->print("
 6907:     <label>
 6908:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 6909:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 6910: 	     "<a target='_blank' href='$href'>","</a>")."
 6911:     </label> 
 6912:     ".&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\')" />'));
 6913: 	    $r->print("\n<br />");
 6914: 	}
 6915: 	$r->print("
 6916:     <label>
 6917:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 6918:        ".&mt("Use [_1] as the CODE.",
 6919: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 6920: 	$r->print("\n<br /><br />");
 6921:     } elsif ($error eq 'doublebubble') {
 6922: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 6923: 
 6924: 	# The form field scantron_questions is acutally a list of line numbers.
 6925: 	# represented by this form so:
 6926: 
 6927: 	my $line_list = &questions_to_line_list($arg);
 6928: 
 6929: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6930: 		  $line_list.'" />');
 6931: 	$r->print($message);
 6932: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 6933: 	foreach my $question (@{$arg}) {
 6934: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6935:                                                    $scan_record, $error);
 6936:             push(@lines_to_correct,@linenums);
 6937: 	}
 6938:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6939:     } elsif ($error eq 'missingbubble') {
 6940: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
 6941: 	$r->print($message);
 6942: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 6943: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 6944: 
 6945: 	# The form field scantron_questions is actually a list of line numbers not
 6946: 	# a list of question numbers. Therefore:
 6947: 	#
 6948: 	
 6949: 	my $line_list = &questions_to_line_list($arg);
 6950: 
 6951: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6952: 		  $line_list.'" />');
 6953: 	foreach my $question (@{$arg}) {
 6954: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6955:                                                    $scan_record, $error);
 6956:             push(@lines_to_correct,@linenums);
 6957: 	}
 6958:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6959:     } else {
 6960: 	$r->print("\n<ul>");
 6961:     }
 6962:     $r->print("\n</li></ul>");
 6963: }
 6964: 
 6965: sub verify_bubbles_checked {
 6966:     my (@ansnums) = @_;
 6967:     my $ansnumstr = join('","',@ansnums);
 6968:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 6969:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
 6970: function verify_bubble_radio(form) {
 6971:     var ansnumArray = new Array ("$ansnumstr");
 6972:     var need_bubble_count = 0;
 6973:     for (var i=0; i<ansnumArray.length; i++) {
 6974:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 6975:             var bubble_picked = 0; 
 6976:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 6977:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 6978:                     bubble_picked = 1;
 6979:                 }
 6980:             }
 6981:             if (bubble_picked == 0) {
 6982:                 need_bubble_count ++;
 6983:             }
 6984:         }
 6985:     }
 6986:     if (need_bubble_count) {
 6987:         alert("$warning");
 6988:         return;
 6989:     }
 6990:     form.submit(); 
 6991: }
 6992: ENDSCRIPT
 6993:     return $output;
 6994: }
 6995: 
 6996: =pod
 6997: 
 6998: =item  questions_to_line_list
 6999: 
 7000: Converts a list of questions into a string of comma separated
 7001: line numbers in the answer sheet used by the questions.  This is
 7002: used to fill in the scantron_questions form field.
 7003: 
 7004:   Arguments:
 7005:      questions    - Reference to an array of questions.
 7006: 
 7007: =cut
 7008: 
 7009: 
 7010: sub questions_to_line_list {
 7011:     my ($questions) = @_;
 7012:     my @lines;
 7013: 
 7014:     foreach my $item (@{$questions}) {
 7015:         my $question = $item;
 7016:         my ($first,$count,$last);
 7017:         if ($item =~ /^(\d+)\.(\d+)$/) {
 7018:             $question = $1;
 7019:             my $subquestion = $2;
 7020:             $first = $first_bubble_line{$question-1} + 1;
 7021:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7022:             my $subcount = 1;
 7023:             while ($subcount<$subquestion) {
 7024:                 $first += $subans[$subcount-1];
 7025:                 $subcount ++;
 7026:             }
 7027:             $count = $subans[$subquestion-1];
 7028:         } else {
 7029: 	    $first   = $first_bubble_line{$question-1} + 1;
 7030: 	    $count   = $bubble_lines_per_response{$question-1};
 7031:         }
 7032:         $last = $first+$count-1;
 7033:         push(@lines, ($first..$last));
 7034:     }
 7035:     return join(',', @lines);
 7036: }
 7037: 
 7038: =pod 
 7039: 
 7040: =item prompt_for_corrections
 7041: 
 7042: Prompts for a potentially multiline correction to the
 7043: user's bubbling (factors out common code from scantron_get_correction
 7044: for multi and missing bubble cases).
 7045: 
 7046:  Arguments:
 7047:    $r           - Apache request object.
 7048:    $question    - The question number to prompt for.
 7049:    $scan_config - The scantron file configuration hash.
 7050:    $scan_record - Reference to the hash that has the the parsed scanlines.
 7051:    $error       - Type of error
 7052: 
 7053:  Implicit inputs:
 7054:    %bubble_lines_per_response   - Starting line numbers for each question.
 7055:                                   Numbered from 0 (but question numbers are from
 7056:                                   1.
 7057:    %first_bubble_line           - Starting bubble line for each question.
 7058:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 7059:                                   type problems render as separate sub-questions, 
 7060:                                   in exam mode. This hash contains a 
 7061:                                   comma-separated list of the lines per 
 7062:                                   sub-question.
 7063:    %responsetype_per_response   - essayresponse, formularesponse,
 7064:                                   stringresponse, imageresponse, reactionresponse,
 7065:                                   and organicresponse type problem parts can have
 7066:                                   multiple lines per response if the weight
 7067:                                   assigned exceeds 10.  In this case, only
 7068:                                   one bubble per line is permitted, but more 
 7069:                                   than one line might contain bubbles, e.g.
 7070:                                   bubbling of: line 1 - J, line 2 - J, 
 7071:                                   line 3 - B would assign 22 points.  
 7072: 
 7073: =cut
 7074: 
 7075: sub prompt_for_corrections {
 7076:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
 7077:     my ($current_line,$lines);
 7078:     my @linenums;
 7079:     my $questionnum = $question;
 7080:     if ($question =~ /^(\d+)\.(\d+)$/) {
 7081:         $question = $1;
 7082:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7083:         my $subquestion = $2;
 7084:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7085:         my $subcount = 1;
 7086:         while ($subcount<$subquestion) {
 7087:             $current_line += $subans[$subcount-1];
 7088:             $subcount ++;
 7089:         }
 7090:         $lines = $subans[$subquestion-1];
 7091:     } else {
 7092:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7093:         $lines        = $bubble_lines_per_response{$question-1};
 7094:     }
 7095:     if ($lines > 1) {
 7096:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7097:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
 7098:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
 7099:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
 7100:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
 7101:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
 7102:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
 7103:             $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 />');
 7104:         } else {
 7105:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7106:         }
 7107:     }
 7108:     for (my $i =0; $i < $lines; $i++) {
 7109:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7110: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
 7111: 	        		  $questionnum,$error,split('', $selected));
 7112:         push(@linenums,$current_line);
 7113: 	$current_line++;
 7114:     }
 7115:     if ($lines > 1) {
 7116: 	$r->print("<hr /><br />");
 7117:     }
 7118:     return @linenums;
 7119: }
 7120: 
 7121: =pod
 7122: 
 7123: =item scantron_bubble_selector
 7124:   
 7125:    Generates the html radiobuttons to correct a single bubble line
 7126:    possibly showing the existing the selected bubbles if known
 7127: 
 7128:  Arguments:
 7129:     $r           - Apache request object
 7130:     $scan_config - hash from &get_scantron_config()
 7131:     $line        - Number of the line being displayed.
 7132:     $questionnum - Question number (may include subquestion)
 7133:     $error       - Type of error.
 7134:     @selected    - Array of bubbles picked on this line.
 7135: 
 7136: =cut
 7137: 
 7138: sub scantron_bubble_selector {
 7139:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7140:     my $max=$$scan_config{'Qlength'};
 7141: 
 7142:     my $scmode=$$scan_config{'Qon'};
 7143:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
 7144: 
 7145:     my @alphabet=('A'..'Z');
 7146:     $r->print(&Apache::loncommon::start_data_table().
 7147:               &Apache::loncommon::start_data_table_row());
 7148:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7149:     for (my $i=0;$i<$max+1;$i++) {
 7150: 	$r->print("\n".'<td align="center">');
 7151: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7152: 	else { $r->print('&nbsp;'); }
 7153: 	$r->print('</td>');
 7154:     }
 7155:     $r->print(&Apache::loncommon::end_data_table_row().
 7156:               &Apache::loncommon::start_data_table_row());
 7157:     for (my $i=0;$i<$max;$i++) {
 7158: 	$r->print("\n".
 7159: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7160: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7161:     }
 7162:     my $nobub_checked = ' ';
 7163:     if ($error eq 'missingbubble') {
 7164:         $nobub_checked = ' checked = "checked" ';
 7165:     }
 7166:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7167: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7168:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7169:               $line.'" value="'.$questionnum.'" /></td>');
 7170:     $r->print(&Apache::loncommon::end_data_table_row().
 7171:               &Apache::loncommon::end_data_table());
 7172: }
 7173: 
 7174: =pod
 7175: 
 7176: =item num_matches
 7177: 
 7178:    Counts the number of characters that are the same between the two arguments.
 7179: 
 7180:  Arguments:
 7181:    $orig - CODE from the scanline
 7182:    $code - CODE to match against
 7183: 
 7184:  Returns:
 7185:    $count - integer count of the number of same characters between the
 7186:             two arguments
 7187: 
 7188: =cut
 7189: 
 7190: sub num_matches {
 7191:     my ($orig,$code) = @_;
 7192:     my @code=split(//,$code);
 7193:     my @orig=split(//,$orig);
 7194:     my $same=0;
 7195:     for (my $i=0;$i<scalar(@code);$i++) {
 7196: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7197:     }
 7198:     return $same;
 7199: }
 7200: 
 7201: =pod
 7202: 
 7203: =item scantron_get_closely_matching_CODEs
 7204: 
 7205:    Cycles through all CODEs and finds the set that has the greatest
 7206:    number of same characters as the provided CODE
 7207: 
 7208:  Arguments:
 7209:    $allcodes - hash ref returned by &get_codes()
 7210:    $CODE     - CODE from the current scanline
 7211: 
 7212:  Returns:
 7213:    2 element list
 7214:     - first elements is number of how closely matching the best fit is 
 7215:       (5 means best set has 5 matching characters)
 7216:     - second element is an arrary ref containing the set of valid CODEs
 7217:       that best fit the passed in CODE
 7218: 
 7219: =cut
 7220: 
 7221: sub scantron_get_closely_matching_CODEs {
 7222:     my ($allcodes,$CODE)=@_;
 7223:     my @CODEs;
 7224:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7225: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7226:     }
 7227: 
 7228:     return ($#CODEs,$CODEs[-1]);
 7229: }
 7230: 
 7231: =pod
 7232: 
 7233: =item get_codes
 7234: 
 7235:    Builds a hash which has keys of all of the valid CODEs from the selected
 7236:    set of remembered CODEs.
 7237: 
 7238:  Arguments:
 7239:   $old_name - name of the set of remembered CODEs
 7240:   $cdom     - domain of the course
 7241:   $cnum     - internal course name
 7242: 
 7243:  Returns:
 7244:   %allcodes - keys are the valid CODEs, values are all 1
 7245: 
 7246: =cut
 7247: 
 7248: sub get_codes {
 7249:     my ($old_name, $cdom, $cnum) = @_;
 7250:     if (!$old_name) {
 7251: 	$old_name=$env{'form.scantron_CODElist'};
 7252:     }
 7253:     if (!$cdom) {
 7254: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7255:     }
 7256:     if (!$cnum) {
 7257: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7258:     }
 7259:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7260: 				    $cdom,$cnum);
 7261:     my %allcodes;
 7262:     if ($result{"type\0$old_name"} eq 'number') {
 7263: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7264:     } else {
 7265: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7266:     }
 7267:     return %allcodes;
 7268: }
 7269: 
 7270: =pod
 7271: 
 7272: =item scantron_validate_CODE
 7273: 
 7274:    Validates all scanlines in the selected file to not have any
 7275:    invalid or underspecified CODEs and that none of the codes are
 7276:    duplicated if this was requested.
 7277: 
 7278: =cut
 7279: 
 7280: sub scantron_validate_CODE {
 7281:     my ($r,$currentphase) = @_;
 7282:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7283:     if ($scantron_config{'CODElocation'} &&
 7284: 	$scantron_config{'CODEstart'} &&
 7285: 	$scantron_config{'CODElength'}) {
 7286: 	if (!defined($env{'form.scantron_CODElist'})) {
 7287: 	    &FIXME_blow_up()
 7288: 	}
 7289:     } else {
 7290: 	return (0,$currentphase+1);
 7291:     }
 7292:     
 7293:     my %usedCODEs;
 7294: 
 7295:     my %allcodes=&get_codes();
 7296: 
 7297:     my $nav_error;
 7298:     &scantron_get_maxbubble(\$nav_error); # parse needs the lines per response array.
 7299:     if ($nav_error) {
 7300:         $r->print(&navmap_errormsg());
 7301:         return(1,$currentphase);
 7302:     }
 7303: 
 7304:     my ($scanlines,$scan_data)=&scantron_getfile();
 7305:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7306: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7307: 	if ($line=~/^[\s\cz]*$/) { next; }
 7308: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7309: 						 $scan_data);
 7310: 	my $CODE=$$scan_record{'scantron.CODE'};
 7311: 	my $error=0;
 7312: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7313: 	    &scantron_get_correction($r,$i,$scan_record,
 7314: 				     \%scantron_config,
 7315: 				     $line,'incorrectCODE',\%allcodes);
 7316: 	    return(1,$currentphase);
 7317: 	}
 7318: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7319: 	    && !$$scan_record{'scantron.useCODE'}) {
 7320: 	    &scantron_get_correction($r,$i,$scan_record,
 7321: 				     \%scantron_config,
 7322: 				     $line,'incorrectCODE',\%allcodes);
 7323: 	    return(1,$currentphase);
 7324: 	}
 7325: 	if (exists($usedCODEs{$CODE}) 
 7326: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 7327: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 7328: 	    &scantron_get_correction($r,$i,$scan_record,
 7329: 				     \%scantron_config,
 7330: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 7331: 	    return(1,$currentphase);
 7332: 	}
 7333: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 7334:     }
 7335:     return (0,$currentphase+1);
 7336: }
 7337: 
 7338: =pod
 7339: 
 7340: =item scantron_validate_doublebubble
 7341: 
 7342:    Validates all scanlines in the selected file to not have any
 7343:    bubble lines with multiple bubbles marked.
 7344: 
 7345: =cut
 7346: 
 7347: sub scantron_validate_doublebubble {
 7348:     my ($r,$currentphase) = @_;
 7349:     #get student info
 7350:     my $classlist=&Apache::loncoursedata::get_classlist();
 7351:     my %idmap=&username_to_idmap($classlist);
 7352: 
 7353:     #get scantron line setup
 7354:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7355:     my ($scanlines,$scan_data)=&scantron_getfile();
 7356:     my $nav_error;
 7357:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble line array.
 7358:     if ($nav_error) {
 7359:         $r->print(&navmap_errormsg());
 7360:         return(1,$currentphase);
 7361:     }
 7362: 
 7363:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7364: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7365: 	if ($line=~/^[\s\cz]*$/) { next; }
 7366: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7367: 						 $scan_data);
 7368: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 7369: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 7370: 				 'doublebubble',
 7371: 				 $$scan_record{'scantron.doubleerror'});
 7372:     	return (1,$currentphase);
 7373:     }
 7374:     return (0,$currentphase+1);
 7375: }
 7376: 
 7377: 
 7378: sub scantron_get_maxbubble {
 7379:     my ($nav_error) = @_;
 7380:     if (defined($env{'form.scantron_maxbubble'}) &&
 7381: 	$env{'form.scantron_maxbubble'}) {
 7382: 	&restore_bubble_lines();
 7383: 	return $env{'form.scantron_maxbubble'};
 7384:     }
 7385: 
 7386:     my (undef, undef, $sequence) =
 7387: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7388: 
 7389:     my $navmap=Apache::lonnavmaps::navmap->new();
 7390:     unless (ref($navmap)) {
 7391:         if (ref($nav_error)) {
 7392:             $$nav_error = 1;
 7393:         }
 7394:         return;
 7395:     }
 7396:     my $map=$navmap->getResourceByUrl($sequence);
 7397:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7398: 
 7399:     &Apache::lonxml::clear_problem_counter();
 7400: 
 7401:     my $uname       = $env{'user.name'};
 7402:     my $udom        = $env{'user.domain'};
 7403:     my $cid         = $env{'request.course.id'};
 7404:     my $total_lines = 0;
 7405:     %bubble_lines_per_response = ();
 7406:     %first_bubble_line         = ();
 7407:     %subdivided_bubble_lines   = ();
 7408:     %responsetype_per_response = ();
 7409: 
 7410:     my $response_number = 0;
 7411:     my $bubble_line     = 0;
 7412:     foreach my $resource (@resources) {
 7413:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
 7414:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 7415: 	    foreach my $part_id (@{$parts}) {
 7416:                 my $lines;
 7417: 
 7418: 	        # TODO - make this a persistent hash not an array.
 7419: 
 7420:                 # optionresponse, matchresponse and rankresponse type items 
 7421:                 # render as separate sub-questions in exam mode.
 7422:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 7423:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 7424:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 7425:                     my ($numbub,$numshown);
 7426:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 7427:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 7428:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 7429:                         }
 7430:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 7431:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 7432:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 7433:                         }
 7434:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 7435:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 7436:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 7437:                         }
 7438:                     }
 7439:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 7440:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 7441:                     }
 7442:                     my $bubbles_per_line = 10;
 7443:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
 7444:                     if (($numbub % $bubbles_per_line) != 0) {
 7445:                         $inner_bubble_lines++;
 7446:                     }
 7447:                     for (my $i=0; $i<$numshown; $i++) {
 7448:                         $subdivided_bubble_lines{$response_number} .= 
 7449:                             $inner_bubble_lines.',';
 7450:                     }
 7451:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 7452:                     $lines = $numshown * $inner_bubble_lines;
 7453:                 } else {
 7454:                     $lines = $analysis->{"$part_id.bubble_lines"};
 7455:                 } 
 7456: 
 7457:                 $first_bubble_line{$response_number} = $bubble_line;
 7458: 	        $bubble_lines_per_response{$response_number} = $lines;
 7459:                 $responsetype_per_response{$response_number} = 
 7460:                     $analysis->{$part_id.'.type'};
 7461: 	        $response_number++;
 7462: 
 7463: 	        $bubble_line +=  $lines;
 7464: 	        $total_lines +=  $lines;
 7465: 	    }
 7466:         }
 7467:     }
 7468:     &Apache::lonnet::delenv('scantron.');
 7469: 
 7470:     &save_bubble_lines();
 7471:     $env{'form.scantron_maxbubble'} =
 7472: 	$total_lines;
 7473:     return $env{'form.scantron_maxbubble'};
 7474: }
 7475: 
 7476: sub scantron_validate_missingbubbles {
 7477:     my ($r,$currentphase) = @_;
 7478:     #get student info
 7479:     my $classlist=&Apache::loncoursedata::get_classlist();
 7480:     my %idmap=&username_to_idmap($classlist);
 7481: 
 7482:     #get scantron line setup
 7483:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7484:     my ($scanlines,$scan_data)=&scantron_getfile();
 7485:     my $nav_error;
 7486:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
 7487:     if ($nav_error) {
 7488:         return(1,$currentphase);
 7489:     }
 7490:     if (!$max_bubble) { $max_bubble=2**31; }
 7491:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7492: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7493: 	if ($line=~/^[\s\cz]*$/) { next; }
 7494: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7495: 						 $scan_data);
 7496: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 7497: 	my @to_correct;
 7498: 	
 7499: 	# Probably here's where the error is...
 7500: 
 7501: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 7502:             my $lastbubble;
 7503:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 7504:                my $question = $1;
 7505:                my $subquestion = $2;
 7506:                if (!defined($first_bubble_line{$question -1})) { next; }
 7507:                my $first = $first_bubble_line{$question-1};
 7508:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7509:                my $subcount = 1;
 7510:                while ($subcount<$subquestion) {
 7511:                    $first += $subans[$subcount-1];
 7512:                    $subcount ++;
 7513:                }
 7514:                my $count = $subans[$subquestion-1];
 7515:                $lastbubble = $first + $count;
 7516:             } else {
 7517:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
 7518:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
 7519:             }
 7520:             if ($lastbubble > $max_bubble) { next; }
 7521: 	    push(@to_correct,$missing);
 7522: 	}
 7523: 	if (@to_correct) {
 7524: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7525: 				     $line,'missingbubble',\@to_correct);
 7526: 	    return (1,$currentphase);
 7527: 	}
 7528: 
 7529:     }
 7530:     return (0,$currentphase+1);
 7531: }
 7532: 
 7533: 
 7534: sub scantron_process_students {
 7535:     my ($r,$symb) = @_;
 7536: 
 7537:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7538:     if (!$symb) {
 7539: 	return '';
 7540:     }
 7541:     my $default_form_data=&defaultFormData($symb);
 7542: 
 7543:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7544:     my ($scanlines,$scan_data)=&scantron_getfile();
 7545:     my $classlist=&Apache::loncoursedata::get_classlist();
 7546:     my %idmap=&username_to_idmap($classlist);
 7547:     my $navmap=Apache::lonnavmaps::navmap->new();
 7548:     unless (ref($navmap)) {
 7549:         $r->print(&navmap_errormsg());
 7550:         return '';
 7551:     }  
 7552:     my $map=$navmap->getResourceByUrl($sequence);
 7553:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7554:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 7555:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 7556:                             \%grader_randomlists_by_symb);
 7557:     my $resource_error;
 7558:     foreach my $resource (@resources) {
 7559:         my $ressymb;
 7560:         if (ref($resource)) {
 7561:             $ressymb = $resource->symb();
 7562:         } else {
 7563:             $resource_error = 1;
 7564:             last;
 7565:         }
 7566:         my ($analysis,$parts) =
 7567:             &scantron_partids_tograde($resource,$env{'request.course.id'},
 7568:                                       $env{'user.name'},$env{'user.domain'},1);
 7569:         $grader_partids_by_symb{$ressymb} = $parts;
 7570:         if (ref($analysis) eq 'HASH') {
 7571:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7572:                 $grader_randomlists_by_symb{$ressymb} = 
 7573:                     $analysis->{'parts_withrandomlist'};
 7574:             }
 7575:         }
 7576:     }
 7577:     if ($resource_error) {
 7578:         $r->print(&navmap_errormsg());
 7579:         return '';
 7580:     }
 7581: 
 7582:     my ($uname,$udom);
 7583:     my $result= <<SCANTRONFORM;
 7584: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7585:   <input type="hidden" name="command" value="scantron_configphase" />
 7586:   $default_form_data
 7587: SCANTRONFORM
 7588:     $r->print($result);
 7589: 
 7590:     my @delayqueue;
 7591:     my (%completedstudents,%scandata);
 7592:     
 7593:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 7594:     my $count=&get_todo_count($scanlines,$scan_data);
 7595:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
 7596:  				    'Bubblesheet Progress',$count,
 7597: 				    'inline',undef,'scantronupload');
 7598:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 7599: 					  'Processing first student');
 7600:     $r->print('<br />');
 7601:     my $start=&Time::HiRes::time();
 7602:     my $i=-1;
 7603:     my $started;
 7604: 
 7605:     my $nav_error;
 7606:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
 7607:     if ($nav_error) {
 7608:         $r->print(&navmap_errormsg());
 7609:         return '';
 7610:     }
 7611: 
 7612:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 7613:     # the user and return.
 7614: 
 7615:     if ($ssi_error) {
 7616: 	$r->print("</form>");
 7617: 	&ssi_print_error($r);
 7618:         &Apache::lonnet::remove_lock($lock);
 7619: 	return '';		# Dunno why the other returns return '' rather than just returning.
 7620:     }
 7621: 
 7622:     my %lettdig = &letter_to_digits();
 7623:     my $numletts = scalar(keys(%lettdig));
 7624: 
 7625:     while ($i<$scanlines->{'count'}) {
 7626:  	($uname,$udom)=('','');
 7627:  	$i++;
 7628:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7629:  	if ($line=~/^[\s\cz]*$/) { next; }
 7630: 	if ($started) {
 7631: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 7632: 						     'last student');
 7633: 	}
 7634: 	$started=1;
 7635:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7636:  						 $scan_data);
 7637:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 7638:  					      \%idmap,$i)) {
 7639:   	    &scantron_add_delay(\@delayqueue,$line,
 7640:  				'Unable to find a student that matches',1);
 7641:  	    next;
 7642:   	}
 7643:  	if (exists $completedstudents{$uname}) {
 7644:  	    &scantron_add_delay(\@delayqueue,$line,
 7645:  				'Student '.$uname.' has multiple sheets',2);
 7646:  	    next;
 7647:  	}
 7648:   	($uname,$udom)=split(/:/,$uname);
 7649: 
 7650:         my (%partids_by_symb,$res_error);
 7651:         foreach my $resource (@resources) {
 7652:             my $ressymb;
 7653:             if (ref($resource)) {
 7654:                 $ressymb = $resource->symb();
 7655:             } else {
 7656:                 $res_error = 1;
 7657:                 last;
 7658:             }
 7659:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 7660:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 7661:                 my ($analysis,$parts) =
 7662:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
 7663:                 $partids_by_symb{$ressymb} = $parts;
 7664:             } else {
 7665:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 7666:             }
 7667:         }
 7668: 
 7669:         if ($res_error) {
 7670:             &scantron_add_delay(\@delayqueue,$line,
 7671:                                 'An error occurred while grading student '.$uname,2);
 7672:             next;
 7673:         }
 7674: 
 7675: 	&Apache::lonxml::clear_problem_counter();
 7676:   	&Apache::lonnet::appenv($scan_record);
 7677: 
 7678: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 7679: 	    &scantron_putfile($scanlines,$scan_data);
 7680: 	}
 7681: 	
 7682:         my $scancode;
 7683:         if ((exists($scan_record->{'scantron.CODE'})) &&
 7684:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 7685:             $scancode = $scan_record->{'scantron.CODE'};
 7686:         } else {
 7687:             $scancode = '';
 7688:         }
 7689: 
 7690:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7691:                                    \@resources,\%partids_by_symb) eq 'ssi_error') {
 7692:             $ssi_error = 0; # So end of handler error message does not trigger.
 7693:             $r->print("</form>");
 7694:             &ssi_print_error($r);
 7695:             &Apache::lonnet::remove_lock($lock);
 7696:             return '';      # Why return ''?  Beats me.
 7697:         }
 7698: 
 7699: 	$completedstudents{$uname}={'line'=>$line};
 7700:         if ($env{'form.verifyrecord'}) {
 7701:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 7702:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 7703:             chomp($studentdata);
 7704:             $studentdata =~ s/\r$//;
 7705:             my $studentrecord = '';
 7706:             my $counter = -1;
 7707:             foreach my $resource (@resources) {
 7708:                 my $ressymb = $resource->symb();
 7709:                 ($counter,my $recording) =
 7710:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7711:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 7712:                                              \%scantron_config,\%lettdig,$numletts);
 7713:                 $studentrecord .= $recording;
 7714:             }
 7715:             if ($studentrecord ne $studentdata) {
 7716:                 &Apache::lonxml::clear_problem_counter();
 7717:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7718:                                            \@resources,\%partids_by_symb) eq 'ssi_error') {
 7719:                     $ssi_error = 0; # So end of handler error message does not trigger.
 7720:                     $r->print("</form>");
 7721:                     &ssi_print_error($r);
 7722:                     &Apache::lonnet::remove_lock($lock);
 7723:                     delete($completedstudents{$uname});
 7724:                     return '';
 7725:                 }
 7726:                 $counter = -1;
 7727:                 $studentrecord = '';
 7728:                 foreach my $resource (@resources) {
 7729:                     my $ressymb = $resource->symb();
 7730:                     ($counter,my $recording) =
 7731:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7732:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 7733:                                                  \%scantron_config,\%lettdig,$numletts);
 7734:                     $studentrecord .= $recording;
 7735:                 }
 7736:                 if ($studentrecord ne $studentdata) {
 7737:                     $r->print('<p><span class="LC_error">');
 7738:                     if ($scancode eq '') {
 7739:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
 7740:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 7741:                     } else {
 7742:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
 7743:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 7744:                     }
 7745:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 7746:                               &Apache::loncommon::start_data_table_header_row()."\n".
 7747:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 7748:                               &Apache::loncommon::end_data_table_header_row()."\n".
 7749:                               &Apache::loncommon::start_data_table_row().
 7750:                               '<td>'.&mt('Bubble Sheet').'</td>'.
 7751:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
 7752:                               &Apache::loncommon::end_data_table_row().
 7753:                               &Apache::loncommon::start_data_table_row().
 7754:                               '<td>Stored submissions</td>'.
 7755:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
 7756:                               &Apache::loncommon::end_data_table_row().
 7757:                               &Apache::loncommon::end_data_table().'</p>');
 7758:                 } else {
 7759:                     $r->print('<br /><span class="LC_warning">'.
 7760:                              &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 />'.
 7761:                              &mt("As a consequence, this user's submission history records two tries.").
 7762:                                  '</span><br />');
 7763:                 }
 7764:             }
 7765:         }
 7766:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 7767:     } continue {
 7768: 	&Apache::lonxml::clear_problem_counter();
 7769: 	&Apache::lonnet::delenv('scantron.');
 7770:     }
 7771:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 7772:     &Apache::lonnet::remove_lock($lock);
 7773: #    my $lasttime = &Time::HiRes::time()-$start;
 7774: #    $r->print("<p>took $lasttime</p>");
 7775: 
 7776:     $r->print("</form>");
 7777:     return '';
 7778: }
 7779: 
 7780: sub graders_resources_pass {
 7781:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
 7782:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 7783:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 7784:         foreach my $resource (@{$resources}) {
 7785:             my $ressymb = $resource->symb();
 7786:             my ($analysis,$parts) =
 7787:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 7788:                                           $env{'user.name'},$env{'user.domain'},1);
 7789:             $grader_partids_by_symb->{$ressymb} = $parts;
 7790:             if (ref($analysis) eq 'HASH') {
 7791:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7792:                     $grader_randomlists_by_symb->{$ressymb} =
 7793:                         $analysis->{'parts_withrandomlist'};
 7794:                 }
 7795:             }
 7796:         }
 7797:     }
 7798:     return;
 7799: }
 7800: 
 7801: sub grade_student_bubbles {
 7802:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
 7803:     if (ref($resources) eq 'ARRAY') {
 7804:         my $count = 0;
 7805:         foreach my $resource (@{$resources}) {
 7806:             my $ressymb = $resource->symb();
 7807:             my %form = ('submitted'      => 'scantron',
 7808:                         'grade_target'   => 'grade',
 7809:                         'grade_username' => $uname,
 7810:                         'grade_domain'   => $udom,
 7811:                         'grade_courseid' => $env{'request.course.id'},
 7812:                         'grade_symb'     => $ressymb,
 7813:                         'CODE'           => $scancode
 7814:                        );
 7815:             if (ref($parts) eq 'HASH') {
 7816:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 7817:                     foreach my $part (@{$parts->{$ressymb}}) {
 7818:                         $form{'scantron_questnum_start.'.$part} =
 7819:                             1+$env{'form.scantron.first_bubble_line.'.$count};
 7820:                         $count++;
 7821:                     }
 7822:                 }
 7823:             }
 7824:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 7825:             return 'ssi_error' if ($ssi_error);
 7826:             last if (&Apache::loncommon::connection_aborted($r));
 7827:         }
 7828:     }
 7829:     return;
 7830: }
 7831: 
 7832: sub scantron_upload_scantron_data {
 7833:     my ($r,$symb)=@_;
 7834:     my $dom = $env{'request.role.domain'};
 7835:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 7836:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 7837:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 7838: 							  'domainid',
 7839: 							  'coursename',$dom);
 7840:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 7841:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
 7842:     my $default_form_data=&defaultFormData($symb);
 7843:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 7844:     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.");
 7845:     $r->print(&Apache::lonhtmlcommon::scripttag('
 7846:     function checkUpload(formname) {
 7847: 	if (formname.upfile.value == "") {
 7848: 	    alert("'.$nofile_alert.'");
 7849: 	    return false;
 7850: 	}
 7851:         if (formname.courseid.value == "") {
 7852:             alert("'.$nocourseid_alert.'");
 7853:             return false;
 7854:         }
 7855: 	formname.submit();
 7856:     }
 7857: 
 7858:     function ToSyllabus() {
 7859:         var cdom = '."'$dom'".';
 7860:         var cnum = document.rules.courseid.value;
 7861:         if (cdom == "" || cdom == null) {
 7862:             return;
 7863:         }
 7864:         if (cnum == "" || cnum == null) {
 7865:            return;
 7866:         }
 7867:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 7868:                             "height=350,width=350,scrollbars=yes,menubar=no");
 7869:         return;
 7870:     }
 7871: 
 7872: '));
 7873:     $r->print('
 7874: <h3>'.&mt('Send scanned bubblesheet data to a course').'</h3>
 7875: 
 7876: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 7877: '.$default_form_data.
 7878:   &Apache::lonhtmlcommon::start_pick_box().
 7879:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 7880:   '<input name="courseid" type="text" size="30" />'.$select_link.
 7881:   &Apache::lonhtmlcommon::row_closure().
 7882:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 7883:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 7884:   &Apache::lonhtmlcommon::row_closure().
 7885:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 7886:   '<input name="domainid" type="hidden" />'.$domdesc.
 7887:   &Apache::lonhtmlcommon::row_closure().
 7888:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 7889:   '<input type="file" name="upfile" size="50" />'.
 7890:   &Apache::lonhtmlcommon::row_closure(1).
 7891:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 7892: 
 7893: <input name="command" value="scantronupload_save" type="hidden" />
 7894: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 7895: </form>
 7896: ');
 7897:     return '';
 7898: }
 7899: 
 7900: 
 7901: sub scantron_upload_scantron_data_save {
 7902:     my($r,$symb)=@_;
 7903:     my $doanotherupload=
 7904: 	'<br /><form action="/adm/grades" method="post">'."\n".
 7905: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 7906: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 7907: 	'</form>'."\n";
 7908:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 7909: 	!&Apache::lonnet::allowed('usc',
 7910: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 7911: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 7912: 	unless ($symb) {
 7913: 	    $r->print($doanotherupload);
 7914: 	}
 7915: 	return '';
 7916:     }
 7917:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 7918:     my $uploadedfile;
 7919:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
 7920:     if (length($env{'form.upfile'}) < 2) {
 7921:         $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>'));
 7922:     } else {
 7923:         my $result = 
 7924:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
 7925:                                             $env{'form.courseid'},$env{'form.domainid'});
 7926: 	if ($result =~ m{^/uploaded/}) {
 7927: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
 7928:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
 7929: 			  '<span class="LC_filename">'.$result.'</span>'));
 7930:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 7931:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 7932:                                                        $env{'form.courseid'},$uploadedfile));
 7933: 	} else {
 7934: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
 7935:                           '<span class="LC_error">','</span>',$result,
 7936: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 7937: 	}
 7938:     }
 7939:     if ($symb) {
 7940: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
 7941:     } else {
 7942: 	$r->print($doanotherupload);
 7943:     }
 7944:     return '';
 7945: }
 7946: 
 7947: sub validate_uploaded_scantron_file {
 7948:     my ($cdom,$cname,$fname) = @_;
 7949:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 7950:     my @lines;
 7951:     if ($scanlines ne '-1') {
 7952:         @lines=split("\n",$scanlines,-1);
 7953:     }
 7954:     my $output;
 7955:     if (@lines) {
 7956:         my (%counts,$max_match_format);
 7957:         my ($max_match_count,$max_match_pct) = (0,0);
 7958:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 7959:         my %idmap = &username_to_idmap($classlist);
 7960:         foreach my $key (keys(%idmap)) {
 7961:             my $lckey = lc($key);
 7962:             $idmap{$lckey} = $idmap{$key};
 7963:         }
 7964:         my %unique_formats;
 7965:         my @formatlines = &get_scantronformat_file();
 7966:         foreach my $line (@formatlines) {
 7967:             chomp($line);
 7968:             my @config = split(/:/,$line);
 7969:             my $idstart = $config[5];
 7970:             my $idlength = $config[6];
 7971:             if (($idstart ne '') && ($idlength > 0)) {
 7972:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 7973:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 7974:                 } else {
 7975:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 7976:                 }
 7977:             }
 7978:         }
 7979:         foreach my $key (keys(%unique_formats)) {
 7980:             my ($idstart,$idlength) = split(':',$key);
 7981:             %{$counts{$key}} = (
 7982:                                'found'   => 0,
 7983:                                'total'   => 0,
 7984:                               );
 7985:             foreach my $line (@lines) {
 7986:                 next if ($line =~ /^#/);
 7987:                 next if ($line =~ /^[\s\cz]*$/);
 7988:                 my $id = substr($line,$idstart-1,$idlength);
 7989:                 $id = lc($id);
 7990:                 if (exists($idmap{$id})) {
 7991:                     $counts{$key}{'found'} ++;
 7992:                 }
 7993:                 $counts{$key}{'total'} ++;
 7994:             }
 7995:             if ($counts{$key}{'total'}) {
 7996:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 7997:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 7998:                     $max_match_pct = $percent_match;
 7999:                     $max_match_format = $key;
 8000:                     $max_match_count = $counts{$key}{'total'};
 8001:                 }
 8002:             }
 8003:         }
 8004:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 8005:             my $format_descs;
 8006:             my $numwithformat = @{$unique_formats{$max_match_format}};
 8007:             for (my $i=0; $i<$numwithformat; $i++) {
 8008:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 8009:                 if ($i<$numwithformat-2) {
 8010:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 8011:                 } elsif ($i==$numwithformat-2) {
 8012:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 8013:                 } elsif ($i==$numwithformat-1) {
 8014:                     $format_descs .= '"<i>'.$desc.'</i>"';
 8015:                 }
 8016:             }
 8017:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 8018:             $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).
 8019:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
 8020:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
 8021:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
 8022:                                   '<i>'.$cdom.'</i>').'</li>'.
 8023:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 8024:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
 8025:                        '</ul>';
 8026:         }
 8027:     } else {
 8028:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
 8029:     }
 8030:     return $output;
 8031: }
 8032: 
 8033: sub valid_file {
 8034:     my ($requested_file)=@_;
 8035:     foreach my $filename (sort(&scantron_filenames())) {
 8036: 	if ($requested_file eq $filename) { return 1; }
 8037:     }
 8038:     return 0;
 8039: }
 8040: 
 8041: sub scantron_download_scantron_data {
 8042:     my ($r,$symb)=@_;
 8043:     my $default_form_data=&defaultFormData($symb);
 8044:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8045:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8046:     my $file=$env{'form.scantron_selectfile'};
 8047:     if (! &valid_file($file)) {
 8048: 	$r->print('
 8049: 	<p>
 8050: 	    '.&mt('The requested file name was invalid.').'
 8051:         </p>
 8052: ');
 8053: 	return;
 8054:     }
 8055:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 8056:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 8057:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 8058:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 8059:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 8060:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 8061:     $r->print('
 8062:     <p>
 8063: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
 8064: 	      '<a href="'.$orig.'">','</a>').'
 8065:     </p>
 8066:     <p>
 8067: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 8068: 	      '<a href="'.$corrected.'">','</a>').'
 8069:     </p>
 8070:     <p>
 8071: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 8072: 	      '<a href="'.$skipped.'">','</a>').'
 8073:     </p>
 8074: ');
 8075:     return '';
 8076: }
 8077: 
 8078: sub checkscantron_results {
 8079:     my ($r,$symb) = @_;
 8080:     if (!$symb) {return '';}
 8081:     my $cid = $env{'request.course.id'};
 8082:     my %lettdig = &letter_to_digits();
 8083:     my $numletts = scalar(keys(%lettdig));
 8084:     my $cnum = $env{'course.'.$cid.'.num'};
 8085:     my $cdom = $env{'course.'.$cid.'.domain'};
 8086:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8087:     my %record;
 8088:     my %scantron_config =
 8089:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 8090:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 8091:     my $classlist=&Apache::loncoursedata::get_classlist();
 8092:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 8093:     my $navmap=Apache::lonnavmaps::navmap->new();
 8094:     unless (ref($navmap)) {
 8095:         $r->print(&navmap_errormsg());
 8096:         return '';
 8097:     }
 8098:     my $map=$navmap->getResourceByUrl($sequence);
 8099:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8100:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 8101:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
 8102: 
 8103:     my ($uname,$udom);
 8104:     my (%scandata,%lastname,%bylast);
 8105:     $r->print('
 8106: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 8107: 
 8108:     my @delayqueue;
 8109:     my %completedstudents;
 8110: 
 8111:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
 8112:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
 8113:                                     'Progress of Bubblesheet Data/Submission Records Comparison',$count,
 8114:                                     'inline',undef,'checkscantron');
 8115:     my ($username,$domain,$started);
 8116:     my $nav_error;
 8117:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
 8118:     if ($nav_error) {
 8119:         $r->print(&navmap_errormsg());
 8120:         return '';
 8121:     }
 8122: 
 8123:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 8124:                                           'Processing first student');
 8125:     my $start=&Time::HiRes::time();
 8126:     my $i=-1;
 8127: 
 8128:     while ($i<$scanlines->{'count'}) {
 8129:         ($username,$domain,$uname)=('','','');
 8130:         $i++;
 8131:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 8132:         if ($line=~/^[\s\cz]*$/) { next; }
 8133:         if ($started) {
 8134:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 8135:                                                      'last student');
 8136:         }
 8137:         $started=1;
 8138:         my $scan_record=
 8139:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 8140:                                                      $scan_data);
 8141:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
 8142:                                                               \%idmap,$i)) {
 8143:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8144:                                 'Unable to find a student that matches',1);
 8145:             next;
 8146:         }
 8147:         if (exists $completedstudents{$uname}) {
 8148:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8149:                                 'Student '.$uname.' has multiple sheets',2);
 8150:             next;
 8151:         }
 8152:         my $pid = $scan_record->{'scantron.ID'};
 8153:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 8154:         push(@{$bylast{$lastname{$pid}}},$pid);
 8155:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8156:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8157:         chomp($scandata{$pid});
 8158:         $scandata{$pid} =~ s/\r$//;
 8159:         ($username,$domain)=split(/:/,$uname);
 8160:         my $counter = -1;
 8161:         foreach my $resource (@resources) {
 8162:             my $parts;
 8163:             my $ressymb = $resource->symb();
 8164:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8165:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8166:                 (my $analysis,$parts) =
 8167:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
 8168:             } else {
 8169:                 $parts = $grader_partids_by_symb{$ressymb};
 8170:             }
 8171:             ($counter,my $recording) =
 8172:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 8173:                                          $scandata{$pid},$parts,
 8174:                                          \%scantron_config,\%lettdig,$numletts);
 8175:             $record{$pid} .= $recording;
 8176:         }
 8177:     }
 8178:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8179:     $r->print('<br />');
 8180:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 8181:     $passed = 0;
 8182:     $failed = 0;
 8183:     $numstudents = 0;
 8184:     foreach my $last (sort(keys(%bylast))) {
 8185:         if (ref($bylast{$last}) eq 'ARRAY') {
 8186:             foreach my $pid (sort(@{$bylast{$last}})) {
 8187:                 my $showscandata = $scandata{$pid};
 8188:                 my $showrecord = $record{$pid};
 8189:                 $showscandata =~ s/\s/&nbsp;/g;
 8190:                 $showrecord =~ s/\s/&nbsp;/g;
 8191:                 if ($scandata{$pid} eq $record{$pid}) {
 8192:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 8193:                     $okstudents .= '<tr class="'.$css_class.'">'.
 8194: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 8195: '</tr>'."\n".
 8196: '<tr class="'.$css_class.'">'."\n".
 8197: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
 8198:                     $passed ++;
 8199:                 } else {
 8200:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 8201:                     $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".
 8202: '</tr>'."\n".
 8203: '<tr class="'.$css_class.'">'."\n".
 8204: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 8205: '</tr>'."\n";
 8206:                     $failed ++;
 8207:                 }
 8208:                 $numstudents ++;
 8209:             }
 8210:         }
 8211:     }
 8212:     $r->print('<p>'.&mt('Comparison of bubblesheet data (including corrections) with corresponding submission records (most recent submission) for <b>[quant,_1,student]</b>  ([_2] scantron lines/student).',$numstudents,$env{'form.scantron_maxbubble'}).'</p>');
 8213:     $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>');
 8214:     if ($passed) {
 8215:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 8216:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8217:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8218:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8219:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8220:                  $okstudents."\n".
 8221:                  &Apache::loncommon::end_data_table().'<br />');
 8222:     }
 8223:     if ($failed) {
 8224:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 8225:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8226:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8227:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8228:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8229:                  $badstudents."\n".
 8230:                  &Apache::loncommon::end_data_table()).'<br />'.
 8231:                  &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.');  
 8232:     }
 8233:     $r->print('</form><br />');
 8234:     return;
 8235: }
 8236: 
 8237: sub verify_scantron_grading {
 8238:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 8239:         $scantron_config,$lettdig,$numletts) = @_;
 8240:     my ($record,%expected,%startpos);
 8241:     return ($counter,$record) if (!ref($resource));
 8242:     return ($counter,$record) if (!$resource->is_problem());
 8243:     my $symb = $resource->symb();
 8244:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 8245:     foreach my $part_id (@{$partids}) {
 8246:         $counter ++;
 8247:         $expected{$part_id} = 0;
 8248:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
 8249:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
 8250:             foreach my $item (@sub_lines) {
 8251:                 $expected{$part_id} += $item;
 8252:             }
 8253:         } else {
 8254:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
 8255:         }
 8256:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 8257:     }
 8258:     if ($symb) {
 8259:         my %recorded;
 8260:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 8261:         if ($returnhash{'version'}) {
 8262:             my %lasthash=();
 8263:             my $version;
 8264:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 8265:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 8266:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 8267:                 }
 8268:             }
 8269:             foreach my $key (keys(%lasthash)) {
 8270:                 if ($key =~ /\.scantron$/) {
 8271:                     my $value = &unescape($lasthash{$key});
 8272:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 8273:                     if ($value eq '') {
 8274:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 8275:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 8276:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8277:                             }
 8278:                         }
 8279:                     } else {
 8280:                         my @tocheck;
 8281:                         my @items = split(//,$value);
 8282:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 8283:                             ($scantron_config->{'Qon'} eq 'number')) {
 8284:                             if (@items < $expected{$part_id}) {
 8285:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 8286:                                 my @singles = split(//,$fragment);
 8287:                                 foreach my $pos (@singles) {
 8288:                                     if ($pos eq ' ') {
 8289:                                         push(@tocheck,$pos);
 8290:                                     } else {
 8291:                                         my $next = shift(@items);
 8292:                                         push(@tocheck,$next);
 8293:                                     }
 8294:                                 }
 8295:                             } else {
 8296:                                 @tocheck = @items;
 8297:                             }
 8298:                             foreach my $letter (@tocheck) {
 8299:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 8300:                                     if ($letter !~ /^[A-J]$/) {
 8301:                                         $letter = $scantron_config->{'Qoff'};
 8302:                                     }
 8303:                                     $recorded{$part_id} .= $letter;
 8304:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 8305:                                     my $digit;
 8306:                                     if ($letter !~ /^[A-J]$/) {
 8307:                                         $digit = $scantron_config->{'Qoff'};
 8308:                                     } else {
 8309:                                         $digit = $lettdig->{$letter};
 8310:                                     }
 8311:                                     $recorded{$part_id} .= $digit;
 8312:                                 }
 8313:                             }
 8314:                         } else {
 8315:                             @tocheck = @items;
 8316:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 8317:                                 my $curr_sub = shift(@tocheck);
 8318:                                 my $digit;
 8319:                                 if ($curr_sub =~ /^[A-J]$/) {
 8320:                                     $digit = $lettdig->{$curr_sub}-1;
 8321:                                 }
 8322:                                 if ($curr_sub eq 'J') {
 8323:                                     $digit += scalar($numletts);
 8324:                                 }
 8325:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8326:                                     if ($j == $digit) {
 8327:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 8328:                                     } else {
 8329:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8330:                                     }
 8331:                                 }
 8332:                             }
 8333:                         }
 8334:                     }
 8335:                 }
 8336:             }
 8337:         }
 8338:         foreach my $part_id (@{$partids}) {
 8339:             if ($recorded{$part_id} eq '') {
 8340:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 8341:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8342:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8343:                     }
 8344:                 }
 8345:             }
 8346:             $record .= $recorded{$part_id};
 8347:         }
 8348:     }
 8349:     return ($counter,$record);
 8350: }
 8351: 
 8352: sub letter_to_digits { 
 8353:     my %lettdig = (
 8354:                     A => 1,
 8355:                     B => 2,
 8356:                     C => 3,
 8357:                     D => 4,
 8358:                     E => 5,
 8359:                     F => 6,
 8360:                     G => 7,
 8361:                     H => 8,
 8362:                     I => 9,
 8363:                     J => 0,
 8364:                   );
 8365:     return %lettdig;
 8366: }
 8367: 
 8368: 
 8369: #-------- end of section for handling grading scantron forms -------
 8370: #
 8371: #-------------------------------------------------------------------
 8372: 
 8373: #-------------------------- Menu interface -------------------------
 8374: #
 8375: #--- Href with symb and command ---
 8376: 
 8377: sub href_symb_cmd {
 8378:     my ($symb,$cmd)=@_;
 8379:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&command='.$cmd;
 8380: }
 8381: 
 8382: sub grading_menu {
 8383:     my ($request,$symb) = @_;
 8384:     if (!$symb) {return '';}
 8385: 
 8386:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 8387:                   'command'=>'individual',
 8388:                   'gradingMenu'=>1,
 8389:                   'showgrading'=>"yes");
 8390:     
 8391:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8392: 
 8393:     $fields{'command'}='ungraded';
 8394:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8395: 
 8396:     $fields{'command'}='table';
 8397:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8398: 
 8399:     $fields{'command'}='all_for_one';
 8400:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8401: 
 8402:     $fields{'command'} = 'csvform';
 8403:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8404:     
 8405:     $fields{'command'} = 'processclicker';
 8406:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8407:     
 8408:     $fields{'command'} = 'scantron_selectphase';
 8409:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8410: 
 8411:     $fields{'command'} = 'initialverifyreceipt';
 8412:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8413:     
 8414:     my @menu = ({	categorytitle=>'Hand Grading',
 8415:             items =>[
 8416:                         {	linktext => 'Select individual students to grade',
 8417:                     		url => $url1a,
 8418:                     		permission => 'F',
 8419:                     		icon => 'edit-find-replace.png',
 8420:                     		linktitle => 'Grade current resource for a selection of students.'
 8421:                         }, 
 8422:                         {       linktext => 'Grade ungraded submissions.',
 8423:                                 url => $url1b,
 8424:                                 permission => 'F',
 8425:                                 icon => 'edit-find-replace.png',
 8426:                                 linktitle => 'Grade all submissions that have not been graded yet.'
 8427:                         },
 8428: 
 8429:                         {       linktext => 'Grading table',
 8430:                                 url => $url1c,
 8431:                                 permission => 'F',
 8432:                                 icon => 'edit-find-replace.png',
 8433:                                 linktitle => 'Grade current resource for all students.'
 8434:                         },
 8435:                         {       linktext => 'Grade page/folder for one student',
 8436:                                 url => $url1d,
 8437:                                 permission => 'F',
 8438:                                 icon => 'edit-find-replace.png',
 8439:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
 8440:                         }]},
 8441:                          { categorytitle=>'Automated Grading',
 8442:                items =>[
 8443: 
 8444:                 	    {	linktext => 'Upload Scores',
 8445:                     		url => $url2,
 8446:                     		permission => 'F',
 8447:                     		icon => 'uploadscores.png',
 8448:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 8449:                 	    },
 8450:                 	    {	linktext => 'Process Clicker',
 8451:                     		url => $url3,
 8452:                     		permission => 'F',
 8453:                     		icon => 'addClickerInfoFile.png',
 8454:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 8455:                 	    },
 8456:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
 8457:                     		url => $url4,
 8458:                     		permission => 'F',
 8459:                     		icon => 'stat.png',
 8460:                     		linktitle => 'Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.'
 8461:                 	    },
 8462:                             {   linktext => 'Verify Receipt Number',
 8463:                                 url => $url5,
 8464:                                 permission => 'F',
 8465:                                 icon => 'edit-find-replace.png',
 8466:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
 8467:                             }
 8468: 
 8469:                     ]
 8470:             });
 8471: 
 8472:     # Create the menu
 8473:     my $Str;
 8474:     $Str .= '<form method="post" action="" name="gradingMenu">';
 8475:     $Str .= '<input type="hidden" name="command" value="" />'.
 8476:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8477: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8478: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8479: 
 8480:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
 8481:     return $Str;    
 8482: }
 8483: 
 8484: 
 8485: sub ungraded {
 8486:     my ($request)=@_;
 8487:     &submit_options($request);
 8488: }
 8489: 
 8490: sub submit_options_sequence {
 8491:     my ($request,$symb) = @_;
 8492:     if (!$symb) {return '';}
 8493:     &commonJSfunctions($request);
 8494:     my $result;
 8495: 
 8496:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8497:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8498:         '<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8499:         '<input type="hidden" name="showgrading" value="yes" />'."\n";
 8500: 
 8501:     $result.='
 8502: <h2>
 8503:   '.&mt('Grade page/folder for one student').'
 8504: </h2>'.
 8505:             &selectfield(0).
 8506:             '<input type="hidden" name="command" value="pickStudentPage" />
 8507:             <div>
 8508:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 8509:             </div>
 8510:         </div>
 8511:   </form>';
 8512:     return $result;
 8513: }
 8514: 
 8515: sub submit_options_table {
 8516:     my ($request,$symb) = @_;
 8517:     if (!$symb) {return '';}
 8518:     &commonJSfunctions($request);
 8519:     my $result;
 8520: 
 8521:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8522:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8523:         '<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8524:         '<input type="hidden" name="showgrading" value="yes" />'."\n";
 8525: 
 8526:     $result.='
 8527: <h2>
 8528:   '.&mt('Grading table').'
 8529: </h2>'.
 8530:             &selectfield(0).
 8531:             '<input type="hidden" name="command" value="viewgrades" />
 8532:             <div>
 8533:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 8534:             </div>
 8535:         </div>
 8536:   </form>';
 8537:     return $result;
 8538: }
 8539: 
 8540: 
 8541: 
 8542: #--- Displays the submissions first page -------
 8543: sub submit_options {
 8544:     my ($request,$symb) = @_;
 8545:     if (!$symb) {return '';}
 8546: 
 8547:     &commonJSfunctions($request);
 8548:     my $result;
 8549: 
 8550:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8551: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8552: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8553: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8554: 
 8555:     $result.='
 8556: <h2>
 8557:   '.&mt('Select individual students to grade').'
 8558: </h2>'.&selectfield(1).'
 8559:                 <input type="hidden" name="command" value="submission" /> 
 8560: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
 8561:             </div>
 8562:           </div>
 8563: 
 8564: 
 8565:   </form>';
 8566:     return $result;
 8567: }
 8568: 
 8569: sub selectfield {
 8570:    my ($full)=@_;
 8571:    my $result='<div class="LC_columnSection">
 8572:   
 8573:     <fieldset>
 8574:       <legend>
 8575:        '.&mt('Sections').'
 8576:       </legend>
 8577:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
 8578:     </fieldset>
 8579:   
 8580:     <fieldset>
 8581:       <legend>
 8582:         '.&mt('Groups').'
 8583:       </legend>
 8584:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 8585:     </fieldset>
 8586:   
 8587:     <fieldset>
 8588:       <legend>
 8589:         '.&mt('Access Status').'
 8590:       </legend>
 8591:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
 8592:     </fieldset>';
 8593:     if ($full) {
 8594:        $result.='
 8595:     <fieldset>
 8596:       <legend>
 8597:         '.&mt('Submission Status').'
 8598:       </legend>'.
 8599:        &Apache::loncommon::select_form('all','submitonly',
 8600:           (&Apache::lonlocal::texthash(
 8601:              'yes'       => 'with submissions',
 8602:              'queued'    => 'in grading queue',
 8603:              'graded'    => 'with ungraded submissions',
 8604:              'incorrect' => 'with incorrect submissions',
 8605:              'all'       => 'with any status'),
 8606:              'select_form_order' => ['yes','queued','graded','incorrect','all'])).
 8607:    '</fieldset>';
 8608:     }
 8609:     $result.='</div><br />';
 8610:     return $result;
 8611: }
 8612: 
 8613: sub reset_perm {
 8614:     undef(%perm);
 8615: }
 8616: 
 8617: sub init_perm {
 8618:     &reset_perm();
 8619:     foreach my $test_perm ('vgr','mgr','opa') {
 8620: 
 8621: 	my $scope = $env{'request.course.id'};
 8622: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 8623: 
 8624: 	    $scope .= '/'.$env{'request.course.sec'};
 8625: 	    if ( $perm{$test_perm}=
 8626: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 8627: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 8628: 	    } else {
 8629: 		delete($perm{$test_perm});
 8630: 	    }
 8631: 	}
 8632:     }
 8633: }
 8634: 
 8635: sub gather_clicker_ids {
 8636:     my %clicker_ids;
 8637: 
 8638:     my $classlist = &Apache::loncoursedata::get_classlist();
 8639: 
 8640:     # Set up a couple variables.
 8641:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 8642:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 8643:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 8644: 
 8645:     foreach my $student (keys(%$classlist)) {
 8646:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 8647:         my $username = $classlist->{$student}->[$username_idx];
 8648:         my $domain   = $classlist->{$student}->[$domain_idx];
 8649:         my $clickers =
 8650: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 8651:         foreach my $id (split(/\,/,$clickers)) {
 8652:             $id=~s/^[\#0]+//;
 8653:             $id=~s/[\-\:]//g;
 8654:             if (exists($clicker_ids{$id})) {
 8655: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 8656:             } else {
 8657: 		$clicker_ids{$id}=$username.':'.$domain;
 8658:             }
 8659:         }
 8660:     }
 8661:     return %clicker_ids;
 8662: }
 8663: 
 8664: sub gather_adv_clicker_ids {
 8665:     my %clicker_ids;
 8666:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 8667:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8668:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 8669:     foreach my $element (sort(keys(%coursepersonnel))) {
 8670:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 8671:             my ($puname,$pudom)=split(/\:/,$person);
 8672:             my $clickers =
 8673: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 8674:             foreach my $id (split(/\,/,$clickers)) {
 8675: 		$id=~s/^[\#0]+//;
 8676:                 $id=~s/[\-\:]//g;
 8677: 		if (exists($clicker_ids{$id})) {
 8678: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 8679: 		} else {
 8680: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 8681: 		}
 8682:             }
 8683:         }
 8684:     }
 8685:     return %clicker_ids;
 8686: }
 8687: 
 8688: sub clicker_grading_parameters {
 8689:     return ('gradingmechanism' => 'scalar',
 8690:             'upfiletype' => 'scalar',
 8691:             'specificid' => 'scalar',
 8692:             'pcorrect' => 'scalar',
 8693:             'pincorrect' => 'scalar');
 8694: }
 8695: 
 8696: sub process_clicker {
 8697:     my ($r,$symb)=@_;
 8698:     if (!$symb) {return '';}
 8699:     my $result=&checkforfile_js();
 8700:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 8701:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 8702:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
 8703:         '</b></td></tr>'."\n";
 8704:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
 8705: # Attempt to restore parameters from last session, set defaults if not present
 8706:     my %Saveable_Parameters=&clicker_grading_parameters();
 8707:     &Apache::loncommon::restore_course_settings('grades_clicker',
 8708:                                                  \%Saveable_Parameters);
 8709:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 8710:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 8711:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 8712:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 8713: 
 8714:     my %checked;
 8715:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 8716:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 8717:           $checked{$gradingmechanism}=' checked="checked"';
 8718:        }
 8719:     }
 8720: 
 8721:     my $upload=&mt("Upload File");
 8722:     my $type=&mt("Type");
 8723:     my $attendance=&mt("Award points just for participation");
 8724:     my $personnel=&mt("Correctness determined from response by course personnel");
 8725:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 8726:     my $given=&mt("Correctness determined from given list of answers").' '.
 8727:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 8728:     my $pcorrect=&mt("Percentage points for correct solution");
 8729:     my $pincorrect=&mt("Percentage points for incorrect solution");
 8730:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 8731: 						   ('iclicker' => 'i>clicker',
 8732:                                                     'interwrite' => 'interwrite PRS'));
 8733:     $symb = &Apache::lonenc::check_encrypt($symb);
 8734:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
 8735: function sanitycheck() {
 8736: // Accept only integer percentages
 8737:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 8738:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 8739: // Find out grading choice
 8740:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8741:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 8742:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 8743:       }
 8744:    }
 8745: // By default, new choice equals user selection
 8746:    newgradingchoice=gradingchoice;
 8747: // Not good to give more points for false answers than correct ones
 8748:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 8749:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 8750:    }
 8751: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 8752:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 8753:       document.forms.gradesupload.pcorrect.value=100;
 8754:       document.forms.gradesupload.pincorrect.value=100;
 8755:    }
 8756: // If the values are different, cannot be attendance only
 8757:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 8758:        (gradingchoice=='attendance')) {
 8759:        newgradingchoice='personnel';
 8760:    }
 8761: // Change grading choice to new one
 8762:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8763:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 8764:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 8765:       } else {
 8766:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 8767:       }
 8768:    }
 8769: // Remember the old state
 8770:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 8771: }
 8772: ENDUPFORM
 8773:     $result.= <<ENDUPFORM;
 8774: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 8775: <input type="hidden" name="symb" value="$symb" />
 8776: <input type="hidden" name="command" value="processclickerfile" />
 8777: <input type="file" name="upfile" size="50" />
 8778: <br /><label>$type: $selectform</label>
 8779: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
 8780: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
 8781: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
 8782: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 8783: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
 8784: <br />&nbsp;&nbsp;&nbsp;
 8785: <input type="text" name="givenanswer" size="50" />
 8786: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 8787: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
 8788: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
 8789: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 8790: </form>'
 8791: ENDUPFORM
 8792:     $result.='</td></tr></table>'."\n".
 8793:              '</td></tr></table><br /><br />'."\n";
 8794:     return $result;
 8795: }
 8796: 
 8797: sub process_clicker_file {
 8798:     my ($r,$symb)=@_;
 8799:     if (!$symb) {return '';}
 8800: 
 8801:     my %Saveable_Parameters=&clicker_grading_parameters();
 8802:     &Apache::loncommon::store_course_settings('grades_clicker',
 8803:                                               \%Saveable_Parameters);
 8804:     my $result='';
 8805:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 8806: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 8807: 	return $result;
 8808:     }
 8809:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 8810:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 8811:         return $result;
 8812:     }
 8813:     my $foundgiven=0;
 8814:     if ($env{'form.gradingmechanism'} eq 'given') {
 8815:         $env{'form.givenanswer'}=~s/^\s*//gs;
 8816:         $env{'form.givenanswer'}=~s/\s*$//gs;
 8817:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
 8818:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 8819:         my @answers=split(/\,/,$env{'form.givenanswer'});
 8820:         $foundgiven=$#answers+1;
 8821:     }
 8822:     my %clicker_ids=&gather_clicker_ids();
 8823:     my %correct_ids;
 8824:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 8825: 	%correct_ids=&gather_adv_clicker_ids();
 8826:     }
 8827:     if ($env{'form.gradingmechanism'} eq 'specific') {
 8828: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 8829: 	   $correct_id=~tr/a-z/A-Z/;
 8830: 	   $correct_id=~s/\s//gs;
 8831: 	   $correct_id=~s/^[\#0]+//;
 8832:            $correct_id=~s/[\-\:]//g;
 8833:            if ($correct_id) {
 8834: 	      $correct_ids{$correct_id}='specified';
 8835:            }
 8836:         }
 8837:     }
 8838:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 8839: 	$result.=&mt('Score based on attendance only');
 8840:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
 8841:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
 8842:     } else {
 8843: 	my $number=0;
 8844: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 8845: 	foreach my $id (sort(keys(%correct_ids))) {
 8846: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 8847: 	    if ($correct_ids{$id} eq 'specified') {
 8848: 		$result.=&mt('specified');
 8849: 	    } else {
 8850: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 8851: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 8852: 	    }
 8853: 	    $number++;
 8854: 	}
 8855:         $result.="</p>\n";
 8856: 	if ($number==0) {
 8857: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
 8858: 	    return $result;
 8859: 	}
 8860:     }
 8861:     if (length($env{'form.upfile'}) < 2) {
 8862:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
 8863: 		     '<span class="LC_error">',
 8864: 		     '</span>',
 8865: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
 8866:         return $result;
 8867:     }
 8868: 
 8869: # Were able to get all the info needed, now analyze the file
 8870: 
 8871:     $result.=&Apache::loncommon::studentbrowser_javascript();
 8872:     $symb = &Apache::lonenc::check_encrypt($symb);
 8873:     my $heading=&mt('Scanning clicker file');
 8874:     $result.=(<<ENDHEADER);
 8875: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 8876: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 8877: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 8878: <form method="post" action="/adm/grades" name="clickeranalysis">
 8879: <input type="hidden" name="symb" value="$symb" />
 8880: <input type="hidden" name="command" value="assignclickergrades" />
 8881: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 8882: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 8883: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 8884: ENDHEADER
 8885:     if ($env{'form.gradingmechanism'} eq 'given') {
 8886:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
 8887:     } 
 8888:     my %responses;
 8889:     my @questiontitles;
 8890:     my $errormsg='';
 8891:     my $number=0;
 8892:     if ($env{'form.upfiletype'} eq 'iclicker') {
 8893: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 8894:     }
 8895:     if ($env{'form.upfiletype'} eq 'interwrite') {
 8896:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 8897:     }
 8898:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 8899:              '<input type="hidden" name="number" value="'.$number.'" />'.
 8900:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 8901:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 8902:              '<br />';
 8903:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
 8904:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
 8905:        return $result;
 8906:     } 
 8907: # Remember Question Titles
 8908: # FIXME: Possibly need delimiter other than ":"
 8909:     for (my $i=0;$i<$number;$i++) {
 8910:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 8911:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 8912:     }
 8913:     my $correct_count=0;
 8914:     my $student_count=0;
 8915:     my $unknown_count=0;
 8916: # Match answers with usernames
 8917: # FIXME: Possibly need delimiter other than ":"
 8918:     foreach my $id (keys(%responses)) {
 8919:        if ($correct_ids{$id}) {
 8920:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 8921:           $correct_count++;
 8922:        } elsif ($clicker_ids{$id}) {
 8923:           if ($clicker_ids{$id}=~/\,/) {
 8924: # More than one user with the same clicker!
 8925:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 8926:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 8927:                            "<select name='multi".$id."'>";
 8928:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 8929:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 8930:              }
 8931:              $result.='</select>';
 8932:              $unknown_count++;
 8933:           } else {
 8934: # Good: found one and only one user with the right clicker
 8935:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 8936:              $student_count++;
 8937:           }
 8938:        } else {
 8939:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 8940:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 8941:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 8942:                    "\n".&mt("Domain").": ".
 8943:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 8944:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
 8945:           $unknown_count++;
 8946:        }
 8947:     }
 8948:     $result.='<hr />'.
 8949:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 8950:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
 8951:        if ($correct_count==0) {
 8952:           $errormsg.="Found no correct answers answers for grading!";
 8953:        } elsif ($correct_count>1) {
 8954:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 8955:        }
 8956:     }
 8957:     if ($number<1) {
 8958:        $errormsg.="Found no questions.";
 8959:     }
 8960:     if ($errormsg) {
 8961:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 8962:     } else {
 8963:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 8964:     }
 8965:     $result.='</form></td></tr></table>'."\n".
 8966:              '</td></tr></table><br /><br />'."\n";
 8967:     return $result;
 8968: }
 8969: 
 8970: sub iclicker_eval {
 8971:     my ($questiontitles,$responses)=@_;
 8972:     my $number=0;
 8973:     my $errormsg='';
 8974:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 8975:         my %components=&Apache::loncommon::record_sep($line);
 8976:         my @entries=map {$components{$_}} (sort(keys(%components)));
 8977: 	if ($entries[0] eq 'Question') {
 8978: 	    for (my $i=3;$i<$#entries;$i+=6) {
 8979: 		$$questiontitles[$number]=$entries[$i];
 8980: 		$number++;
 8981: 	    }
 8982: 	}
 8983: 	if ($entries[0]=~/^\#/) {
 8984: 	    my $id=$entries[0];
 8985: 	    my @idresponses;
 8986: 	    $id=~s/^[\#0]+//;
 8987: 	    for (my $i=0;$i<$number;$i++) {
 8988: 		my $idx=3+$i*6;
 8989: 		push(@idresponses,$entries[$idx]);
 8990: 	    }
 8991: 	    $$responses{$id}=join(',',@idresponses);
 8992: 	}
 8993:     }
 8994:     return ($errormsg,$number);
 8995: }
 8996: 
 8997: sub interwrite_eval {
 8998:     my ($questiontitles,$responses)=@_;
 8999:     my $number=0;
 9000:     my $errormsg='';
 9001:     my $skipline=1;
 9002:     my $questionnumber=0;
 9003:     my %idresponses=();
 9004:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9005:         my %components=&Apache::loncommon::record_sep($line);
 9006:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9007:         if ($entries[1] eq 'Time') { $skipline=0; next; }
 9008:         if ($entries[1] eq 'Response') { $skipline=1; }
 9009:         next if $skipline;
 9010:         if ($entries[0]!=$questionnumber) {
 9011:            $questionnumber=$entries[0];
 9012:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
 9013:            $number++;
 9014:         }
 9015:         my $id=$entries[4];
 9016:         $id=~s/^[\#0]+//;
 9017:         $id=~s/^v\d*\://i;
 9018:         $id=~s/[\-\:]//g;
 9019:         $idresponses{$id}[$number]=$entries[6];
 9020:     }
 9021:     foreach my $id (keys(%idresponses)) {
 9022:        $$responses{$id}=join(',',@{$idresponses{$id}});
 9023:        $$responses{$id}=~s/^\s*\,//;
 9024:     }
 9025:     return ($errormsg,$number);
 9026: }
 9027: 
 9028: sub assign_clicker_grades {
 9029:     my ($r,$symb)=@_;
 9030:     if (!$symb) {return '';}
 9031: # See which part we are saving to
 9032:     my $res_error;
 9033:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 9034:     if ($res_error) {
 9035:         return &navmap_errormsg();
 9036:     }
 9037: # FIXME: This should probably look for the first handgradeable part
 9038:     my $part=$$partlist[0];
 9039: # Start screen output
 9040:     my $result='';
 9041: 
 9042:     my $heading=&mt('Assigning grades based on clicker file');
 9043:     $result.=(<<ENDHEADER);
 9044: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 9045: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 9046: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 9047: ENDHEADER
 9048: # Get correct result
 9049: # FIXME: Possibly need delimiter other than ":"
 9050:     my @correct=();
 9051:     my $gradingmechanism=$env{'form.gradingmechanism'};
 9052:     my $number=$env{'form.number'};
 9053:     if ($gradingmechanism ne 'attendance') {
 9054:        foreach my $key (keys(%env)) {
 9055:           if ($key=~/^form\.correct\:/) {
 9056:              my @input=split(/\,/,$env{$key});
 9057:              for (my $i=0;$i<=$#input;$i++) {
 9058:                  if (($correct[$i]) && ($input[$i]) &&
 9059:                      ($correct[$i] ne $input[$i])) {
 9060:                     $result.='<br /><span class="LC_warning">'.
 9061:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
 9062:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
 9063:                  } elsif ($input[$i]) {
 9064:                     $correct[$i]=$input[$i];
 9065:                  }
 9066:              }
 9067:           }
 9068:        }
 9069:        for (my $i=0;$i<$number;$i++) {
 9070:           if (!$correct[$i]) {
 9071:              $result.='<br /><span class="LC_error">'.
 9072:                       &mt('No correct result given for question "[_1]"!',
 9073:                           $env{'form.question:'.$i}).'</span>';
 9074:           }
 9075:        }
 9076:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
 9077:     }
 9078: # Start grading
 9079:     my $pcorrect=$env{'form.pcorrect'};
 9080:     my $pincorrect=$env{'form.pincorrect'};
 9081:     my $storecount=0;
 9082:     foreach my $key (keys(%env)) {
 9083:        my $user='';
 9084:        if ($key=~/^form\.student\:(.*)$/) {
 9085:           $user=$1;
 9086:        }
 9087:        if ($key=~/^form\.unknown\:(.*)$/) {
 9088:           my $id=$1;
 9089:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
 9090:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
 9091:           } elsif ($env{'form.multi'.$id}) {
 9092:              $user=$env{'form.multi'.$id};
 9093:           }
 9094:        }
 9095:        if ($user) { 
 9096:           my @answer=split(/\,/,$env{$key});
 9097:           my $sum=0;
 9098:           my $realnumber=$number;
 9099:           for (my $i=0;$i<$number;$i++) {
 9100:              if  ($correct[$i] eq '-') {
 9101:                 $realnumber--;
 9102:              } elsif ($answer[$i]) {
 9103:                 if ($gradingmechanism eq 'attendance') {
 9104:                    $sum+=$pcorrect;
 9105:                 } elsif ($correct[$i] eq '*') {
 9106:                    $sum+=$pcorrect;
 9107:                 } else {
 9108:                    if ($answer[$i] eq $correct[$i]) {
 9109:                       $sum+=$pcorrect;
 9110:                    } else {
 9111:                       $sum+=$pincorrect;
 9112:                    }
 9113:                 }
 9114:              }
 9115:           }
 9116:           my $ave=$sum/(100*$realnumber);
 9117: # Store
 9118:           my ($username,$domain)=split(/\:/,$user);
 9119:           my %grades=();
 9120:           $grades{"resource.$part.solved"}='correct_by_override';
 9121:           $grades{"resource.$part.awarded"}=$ave;
 9122:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 9123:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
 9124:                                                  $env{'request.course.id'},
 9125:                                                  $domain,$username);
 9126:           if ($returncode ne 'ok') {
 9127:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
 9128:           } else {
 9129:              $storecount++;
 9130:           }
 9131:        }
 9132:     }
 9133: # We are done
 9134:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
 9135:              '</td></tr></table>'."\n".
 9136:              '</td></tr></table><br /><br />'."\n";
 9137:     return $result;
 9138: }
 9139: 
 9140: sub navmap_errormsg {
 9141:     return '<div class="LC_error">'.
 9142:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
 9143:            &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>').
 9144:            '</div>';
 9145: }
 9146: 
 9147: sub startpage {
 9148:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag) = @_;
 9149:     unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
 9150:     $r->print(&Apache::loncommon::start_page('Grading',undef,
 9151:                                           {'bread_crumbs' => $crumbs}));
 9152:     unless ($nodisplayflag) {
 9153:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag));
 9154:     }
 9155: }
 9156: 
 9157: sub handler {
 9158:     my $request=$_[0];
 9159:     &reset_caches();
 9160:     if ($env{'browser.mathml'}) {
 9161: 	&Apache::loncommon::content_type($request,'text/xml');
 9162:     } else {
 9163: 	&Apache::loncommon::content_type($request,'text/html');
 9164:     }
 9165:     $request->send_http_header;
 9166:     return '' if $request->header_only;
 9167:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
 9168: 
 9169: # see what command we need to execute
 9170: 
 9171:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
 9172:     my $command=$commands[0];
 9173: 
 9174:     if ($#commands > 0) {
 9175: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
 9176:     }
 9177: 
 9178: # see what the symb is
 9179: 
 9180:     my $symb=$env{'form.symb'};
 9181:     unless ($symb) {
 9182:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
 9183:        $symb=&Apache::lonnet::symbread($url);
 9184:     }
 9185:     &Apache::lonenc::check_decrypt(\$symb);                             
 9186: 
 9187:     $ssi_error = 0;
 9188:     if ($symb eq '' && $command eq '') {
 9189: #
 9190: # Not called from a resource
 9191: #    
 9192: 
 9193:     } else {
 9194: 	&init_perm();
 9195: 	if ($command eq 'submission' && $perm{'vgr'}) {
 9196:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}]);
 9197: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
 9198: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
 9199:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
 9200:                                        {href=>'',text=>'Select student'}],1,1);
 9201: 	    &pickStudentPage($request,$symb);
 9202: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
 9203:             &startpage($request,$symb,
 9204:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
 9205:                                        {href=>'',text=>'Select student'},
 9206:                                        {href=>'',text=>'Grade student'}],1,1);
 9207: 	    &displayPage($request,$symb);
 9208: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
 9209:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
 9210:                                        {href=>'',text=>'Select student'},
 9211:                                        {href=>'',text=>'Grade student'},
 9212:                                        {href=>'',text=>'Store grades'}],1,1);
 9213: 	    &updateGradeByPage($request,$symb);
 9214: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
 9215:             &startpage($request,$symb);
 9216: 	    &processGroup($request,$symb);
 9217: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
 9218:             &startpage($request,$symb);
 9219: 	    $request->print(&grading_menu($request,$symb));
 9220: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
 9221:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
 9222: 	    $request->print(&submit_options($request,$symb));
 9223:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
 9224:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
 9225:             $request->print(&listStudents($request,$symb,'graded'));
 9226:         } elsif ($command eq 'table' && $perm{'vgr'}) {
 9227:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
 9228:             $request->print(&submit_options_table($request,$symb));
 9229:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
 9230:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
 9231:             $request->print(&submit_options_sequence($request,$symb));
 9232: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
 9233:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
 9234: 	    $request->print(&viewgrades($request,$symb));
 9235: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
 9236:             &startpage($request,$symb);
 9237: 	    $request->print(&processHandGrade($request,$symb));
 9238: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
 9239:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
 9240:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
 9241:                                                                              text=>"Modify grades"},
 9242:                                        {href=>'', text=>"Store grades"}]);
 9243: 	    $request->print(&editgrades($request,$symb));
 9244:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
 9245:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
 9246:             $request->print(&initialverifyreceipt($request,$symb));
 9247: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
 9248:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
 9249:                                        {href=>'',text=>'Verification Result'}]);
 9250: 	    $request->print(&verifyreceipt($request,$symb));
 9251:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
 9252:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
 9253:             $request->print(&process_clicker($request,$symb));
 9254:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
 9255:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
 9256:                                        {href=>'', text=>'Process clicker file'}]);
 9257:             $request->print(&process_clicker_file($request,$symb));
 9258:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
 9259:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
 9260:                                        {href=>'', text=>'Process clicker file'},
 9261:                                        {href=>'', text=>'Store grades'}]);
 9262:             $request->print(&assign_clicker_grades($request,$symb));
 9263: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
 9264:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9265: 	    $request->print(&upcsvScores_form($request,$symb));
 9266: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
 9267:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9268: 	    $request->print(&csvupload($request,$symb));
 9269: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
 9270:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9271: 	    $request->print(&csvuploadmap($request,$symb));
 9272: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
 9273: 	    if ($env{'form.associate'} ne 'Reverse Association') {
 9274:                 &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9275: 		$request->print(&csvuploadoptions($request,$symb));
 9276: 	    } else {
 9277: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
 9278: 		    $env{'form.upfile_associate'} = 'reverse';
 9279: 		} else {
 9280: 		    $env{'form.upfile_associate'} = 'forward';
 9281: 		}
 9282:                 &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9283: 		$request->print(&csvuploadmap($request,$symb));
 9284: 	    }
 9285: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
 9286:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9287: 	    $request->print(&csvuploadassign($request,$symb));
 9288: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
 9289:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9290: 	    $request->print(&scantron_selectphase($request,undef,$symb));
 9291:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
 9292:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9293:  	    $request->print(&scantron_do_warning($request,$symb));
 9294: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
 9295:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9296: 	    $request->print(&scantron_validate_file($request,$symb));
 9297: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
 9298:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9299: 	    $request->print(&scantron_process_students($request,$symb));
 9300:  	} elsif ($command eq 'scantronupload' && 
 9301:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9302: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9303:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9304:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
 9305:  	} elsif ($command eq 'scantronupload_save' &&
 9306:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9307: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9308:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9309:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
 9310:  	} elsif ($command eq 'scantron_download' &&
 9311: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 9312:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9313:  	    $request->print(&scantron_download_scantron_data($request,$symb));
 9314:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
 9315:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9316:             $request->print(&checkscantron_results($request,$symb));     
 9317: 	} elsif ($command) {
 9318:             &startpage($request,$symb);
 9319: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
 9320: 	}
 9321:     }
 9322:     if ($ssi_error) {
 9323: 	&ssi_print_error($request);
 9324:     }
 9325:     $request->print(&Apache::loncommon::end_page());
 9326:     &reset_caches();
 9327:     return '';
 9328: }
 9329: 
 9330: 1;
 9331: 
 9332: __END__;
 9333: 
 9334: 
 9335: =head1 NAME
 9336: 
 9337: Apache::grades
 9338: 
 9339: =head1 SYNOPSIS
 9340: 
 9341: Handles the viewing of grades.
 9342: 
 9343: This is part of the LearningOnline Network with CAPA project
 9344: described at http://www.lon-capa.org.
 9345: 
 9346: =head1 OVERVIEW
 9347: 
 9348: Do an ssi with retries:
 9349: While I'd love to factor out this with the vesrion in lonprintout,
 9350: 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
 9351: I'm not quite ready to invent (e.g. an ssi_with_retry object).
 9352: 
 9353: At least the logic that drives this has been pulled out into loncommon.
 9354: 
 9355: 
 9356: 
 9357: ssi_with_retries - Does the server side include of a resource.
 9358:                      if the ssi call returns an error we'll retry it up to
 9359:                      the number of times requested by the caller.
 9360:                      If we still have a proble, no text is appended to the
 9361:                      output and we set some global variables.
 9362:                      to indicate to the caller an SSI error occurred.  
 9363:                      All of this is supposed to deal with the issues described
 9364:                      in LonCAPA BZ 5631 see:
 9365:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
 9366:                      by informing the user that this happened.
 9367: 
 9368: Parameters:
 9369:   resource   - The resource to include.  This is passed directly, without
 9370:                interpretation to lonnet::ssi.
 9371:   form       - The form hash parameters that guide the interpretation of the resource
 9372:                
 9373:   retries    - Number of retries allowed before giving up completely.
 9374: Returns:
 9375:   On success, returns the rendered resource identified by the resource parameter.
 9376: Side Effects:
 9377:   The following global variables can be set:
 9378:    ssi_error                - If an unrecoverable error occurred this becomes true.
 9379:                               It is up to the caller to initialize this to false
 9380:                               if desired.
 9381:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
 9382:                               of the resource that could not be rendered by the ssi
 9383:                               call.
 9384:    ssi_error_message   - The error string fetched from the ssi response
 9385:                               in the event of an error.
 9386: 
 9387: 
 9388: =head1 HANDLER SUBROUTINE
 9389: 
 9390: ssi_with_retries()
 9391: 
 9392: =head1 SUBROUTINES
 9393: 
 9394: =over
 9395: 
 9396: =item scantron_get_correction() : 
 9397: 
 9398:    Builds the interface screen to interact with the operator to fix a
 9399:    specific error condition in a specific scanline
 9400: 
 9401:  Arguments:
 9402:     $r           - Apache request object
 9403:     $i           - number of the current scanline
 9404:     $scan_record - hash ref as returned from &scantron_parse_scanline()
 9405:     $scan_config - hash ref as returned from &get_scantron_config()
 9406:     $line        - full contents of the current scanline
 9407:     $error       - error condition, valid values are
 9408:                    'incorrectCODE', 'duplicateCODE',
 9409:                    'doublebubble', 'missingbubble',
 9410:                    'duplicateID', 'incorrectID'
 9411:     $arg         - extra information needed
 9412:        For errors:
 9413:          - duplicateID   - paper number that this studentID was seen before on
 9414:          - duplicateCODE - array ref of the paper numbers this CODE was
 9415:                            seen on before
 9416:          - incorrectCODE - current incorrect CODE 
 9417:          - doublebubble  - array ref of the bubble lines that have double
 9418:                            bubble errors
 9419:          - missingbubble - array ref of the bubble lines that have missing
 9420:                            bubble errors
 9421: 
 9422: =item  scantron_get_maxbubble() : 
 9423: 
 9424:    Arguments:
 9425:        $nav_error  - Reference to scalar which is a flag to indicate a
 9426:                       failure to retrieve a navmap object.
 9427:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
 9428:        calling routine should trap the error condition and display the warning
 9429:        found in &navmap_errormsg().
 9430: 
 9431:    Returns the maximum number of bubble lines that are expected to
 9432:    occur. Does this by walking the selected sequence rendering the
 9433:    resource and then checking &Apache::lonxml::get_problem_counter()
 9434:    for what the current value of the problem counter is.
 9435: 
 9436:    Caches the results to $env{'form.scantron_maxbubble'},
 9437:    $env{'form.scantron.bubble_lines.n'}, 
 9438:    $env{'form.scantron.first_bubble_line.n'} and
 9439:    $env{"form.scantron.sub_bubblelines.n"}
 9440:    which are the total number of bubble, lines, the number of bubble
 9441:    lines for response n and number of the first bubble line for response n,
 9442:    and a comma separated list of numbers of bubble lines for sub-questions
 9443:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
 9444: 
 9445: 
 9446: =item  scantron_validate_missingbubbles() : 
 9447: 
 9448:    Validates all scanlines in the selected file to not have any
 9449:     answers that don't have bubbles that have not been verified
 9450:     to be bubble free.
 9451: 
 9452: =item  scantron_process_students() : 
 9453: 
 9454:    Routine that does the actual grading of the bubble sheet information.
 9455: 
 9456:    The parsed scanline hash is added to %env 
 9457: 
 9458:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
 9459:    foreach resource , with the form data of
 9460: 
 9461: 	'submitted'     =>'scantron' 
 9462: 	'grade_target'  =>'grade',
 9463: 	'grade_username'=> username of student
 9464: 	'grade_domain'  => domain of student
 9465: 	'grade_courseid'=> of course
 9466: 	'grade_symb'    => symb of resource to grade
 9467: 
 9468:     This triggers a grading pass. The problem grading code takes care
 9469:     of converting the bubbled letter information (now in %env) into a
 9470:     valid submission.
 9471: 
 9472: =item  scantron_upload_scantron_data() :
 9473: 
 9474:     Creates the screen for adding a new bubble sheet data file to a course.
 9475: 
 9476: =item  scantron_upload_scantron_data_save() : 
 9477: 
 9478:    Adds a provided bubble information data file to the course if user
 9479:    has the correct privileges to do so. 
 9480: 
 9481: =item  valid_file() :
 9482: 
 9483:    Validates that the requested bubble data file exists in the course.
 9484: 
 9485: =item  scantron_download_scantron_data() : 
 9486: 
 9487:    Shows a list of the three internal files (original, corrected,
 9488:    skipped) for a specific bubble sheet data file that exists in the
 9489:    course.
 9490: 
 9491: =item  scantron_validate_ID() : 
 9492: 
 9493:    Validates all scanlines in the selected file to not have any
 9494:    invalid or underspecified student/employee IDs
 9495: 
 9496: =item navmap_errormsg() :
 9497: 
 9498:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
 9499:    Should be called whenever the request to instantiate a navmap object fails.  
 9500: 
 9501: =back
 9502: 
 9503: =cut

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