File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.621: download - view: text, annotated - select for diffs
Sat Apr 17 16:38:38 2010 UTC (14 years ago) by www
Branches: MAIN
CVS tags: HEAD
Move submissions downloading one level up.

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.621 2010/04/17 16:38:38 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: 
  821:     my $result='<h3><span class="LC_info">&nbsp;'
  822: 	.&mt("View/Grade/Regrade Submissions for a Student or a Group of Students")
  823: 	.'</span></h3>';
  824: 
  825:     my ($partlist,$handgrade,$responseType) = &response_type($symb
  826: #,$res_error
  827:     );
  828: 
  829:     my %lt = &Apache::lonlocal::texthash (
  830: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
  831: 		'single'   => 'Please select the student before clicking on the Next button.',
  832: 	     );
  833:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
  834:     function checkSelect(checkBox) {
  835: 	var ctr=0;
  836: 	var sense="";
  837: 	if (checkBox.length > 1) {
  838: 	    for (var i=0; i<checkBox.length; i++) {
  839: 		if (checkBox[i].checked) {
  840: 		    ctr++;
  841: 		}
  842: 	    }
  843: 	    sense = '$lt{'multiple'}';
  844: 	} else {
  845: 	    if (checkBox.checked) {
  846: 		ctr = 1;
  847: 	    }
  848: 	    sense = '$lt{'single'}';
  849: 	}
  850: 	if (ctr == 0) {
  851: 	    alert(sense);
  852: 	    return false;
  853: 	}
  854: 	document.gradesub.submit();
  855:     }
  856: 
  857:     function reLoadList(formname) {
  858: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  859: 	formname.command.value = 'submission';
  860: 	formname.submit();
  861:     }
  862: LISTJAVASCRIPT
  863: 
  864:     &commonJSfunctions($request);
  865:     $request->print($result);
  866: 
  867:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
  868:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
  869:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  870: 	"\n";
  871: 	
  872:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
  873:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
  874:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
  875:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
  876:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
  877:                   .&Apache::lonhtmlcommon::row_closure();
  878:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
  879:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
  880:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
  881:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
  882:                   .&Apache::lonhtmlcommon::row_closure();
  883: 
  884:     my $submission_options;
  885:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
  886: 	$submission_options.=
  887: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
  888:     }
  889:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  890:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  891:     $env{'form.Status'} = $saveStatus;
  892:     $submission_options.=
  893:         '<span class="LC_nobreak">'.
  894:         '<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.
  895:         &mt('last submission only').' </label></span>'."\n".
  896:         '<span class="LC_nobreak">'.
  897:         '<label><input type="radio" name="lastSub" value="last" /> '.
  898:         &mt('last submission &amp; parts info').' </label></span>'."\n".
  899:         '<span class="LC_nobreak">'.
  900:         '<label><input type="radio" name="lastSub" value="datesub" /> '.
  901:         &mt('by dates and submissions').'</label></span>'."\n".
  902:         '<span class="LC_nobreak">'.
  903:         '<label><input type="radio" name="lastSub" value="all" /> '.
  904:         &mt('all details').'</label></span>';
  905:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
  906:                   .$submission_options
  907:                   .&Apache::lonhtmlcommon::row_closure();
  908: 
  909:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
  910:                   .'<select name="increment">'
  911:                   .'<option value="1">'.&mt('Whole Points').'</option>'
  912:                   .'<option value=".5">'.&mt('Half Points').'</option>'
  913:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
  914:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
  915:                   .'</select>'
  916:                   .&Apache::lonhtmlcommon::row_closure();
  917: 
  918:     $gradeTable .= 
  919:         &build_section_inputs().
  920: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
  921: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
  922: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  923: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
  924: 
  925:     if (exists($env{'form.Status'})) {
  926: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
  927:     } else {
  928:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
  929:                       .&Apache::lonhtmlcommon::StatusOptions(
  930:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
  931:                       .&Apache::lonhtmlcommon::row_closure();
  932:     }
  933: 
  934:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
  935:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
  936:                   .&Apache::lonhtmlcommon::row_closure(1)
  937:                   .&Apache::lonhtmlcommon::end_pick_box();
  938: 
  939:     $gradeTable .= '<p>'
  940:                   .&mt("To view/grade/regrade a submission or a group of submissions, click on the check box(es) next to the student's name(s). Then click on the Next button.")."\n"
  941:                   .'<input type="hidden" name="command" value="processGroup" />'
  942:                   .'</p>';
  943: 
  944: # checkall buttons
  945:     $gradeTable.=&check_script('gradesub', 'stuinfo');
  946:     $gradeTable.='<input type="button" '."\n".
  947:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
  948:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
  949:     $gradeTable.=&check_buttons();
  950:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
  951:     $gradeTable.= &Apache::loncommon::start_data_table().
  952: 	&Apache::loncommon::start_data_table_header_row();
  953:     my $loop = 0;
  954:     while ($loop < 2) {
  955: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
  956: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
  957: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
  958: 	    foreach my $part (sort(@$partlist)) {
  959: 		my $display_part=
  960: 		    &get_display_part((split(/_/,$part))[0],$symb);
  961: 		$gradeTable.=
  962: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
  963: 	    }
  964: 	} elsif ($submitonly eq 'queued') {
  965: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
  966: 	}
  967: 	$loop++;
  968: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
  969:     }
  970:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
  971: 
  972:     my $ctr = 0;
  973:     foreach my $student (sort 
  974: 			 {
  975: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  976: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  977: 			     }
  978: 			     return $a cmp $b;
  979: 			 }
  980: 			 (keys(%$fullname))) {
  981: 	my ($uname,$udom) = split(/:/,$student);
  982: 
  983: 	my %status = ();
  984: 
  985: 	if ($submitonly eq 'queued') {
  986: 	    my %queue_status = 
  987: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
  988: 							$udom,$uname);
  989: 	    next if (!defined($queue_status{'gradingqueue'}));
  990: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
  991: 	}
  992: 
  993: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
  994: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
  995: 	    my $submitted = 0;
  996: 	    my $graded = 0;
  997: 	    my $incorrect = 0;
  998: 	    foreach (keys(%status)) {
  999: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1000: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1001: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1002: 		
 1003: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1004: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1005: 		    $submitted = 0;
 1006: 		    my ($part)=split(/\./,$partid);
 1007: 		    $gradeTable.='<input type="hidden" name="'.
 1008: 			$student.':'.$part.':submitted_by" value="'.
 1009: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1010: 		}
 1011: 	    }
 1012: 	    
 1013: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1014: 				     $submitonly eq 'incorrect' ||
 1015: 				     $submitonly eq 'graded'));
 1016: 	    next if (!$graded && ($submitonly eq 'graded'));
 1017: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1018: 	}
 1019: 
 1020: 	$ctr++;
 1021: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1022:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1023: 	if ( $perm{'vgr'} eq 'F' ) {
 1024: 	    if ($ctr%2 ==1) {
 1025: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1026: 	    }
 1027: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1028:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1029:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1030: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1031: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1032: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1033: 
 1034: 	    if ($submitonly ne 'all') {
 1035: 		foreach (sort(keys(%status))) {
 1036: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1037: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1038: 		}
 1039: 	    }
 1040: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1041: 	    if ($ctr%2 ==0) {
 1042: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1043: 	    }
 1044: 	}
 1045:     }
 1046:     if ($ctr%2 ==1) {
 1047: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1048: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1049: 		foreach (@$partlist) {
 1050: 		    $gradeTable.='<td>&nbsp;</td>';
 1051: 		}
 1052: 	    } elsif ($submitonly eq 'queued') {
 1053: 		$gradeTable.='<td>&nbsp;</td>';
 1054: 	    }
 1055: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1056:     }
 1057: 
 1058:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1059:         '<input type="button" '.
 1060:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
 1061:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1062:     if ($ctr == 0) {
 1063: 	my $num_students=(scalar(keys(%$fullname)));
 1064: 	if ($num_students eq 0) {
 1065: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1066: 	} else {
 1067: 	    my $submissions='submissions';
 1068: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1069: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1070: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1071: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1072: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
 1073: 		    $num_students).
 1074: 		'</span><br />';
 1075: 	}
 1076:     } elsif ($ctr == 1) {
 1077: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1078:     }
 1079:     $request->print($gradeTable);
 1080:     return '';
 1081: }
 1082: 
 1083: #---- Called from the listStudents routine
 1084: 
 1085: sub check_script {
 1086:     my ($form, $type)=@_;
 1087:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
 1088:     function checkall() {
 1089:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1090:             ele = document.forms.'.$form.'.elements[i];
 1091:             if (ele.name == "'.$type.'") {
 1092:             document.forms.'.$form.'.elements[i].checked=true;
 1093:                                        }
 1094:         }
 1095:     }
 1096: 
 1097:     function checksec() {
 1098:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1099:             ele = document.forms.'.$form.'.elements[i];
 1100:            string = document.forms.'.$form.'.chksec.value;
 1101:            if
 1102:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1103:               document.forms.'.$form.'.elements[i].checked=true;
 1104:             }
 1105:         }
 1106:     }
 1107: 
 1108: 
 1109:     function uncheckall() {
 1110:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1111:             ele = document.forms.'.$form.'.elements[i];
 1112:             if (ele.name == "'.$type.'") {
 1113:             document.forms.'.$form.'.elements[i].checked=false;
 1114:                                        }
 1115:         }
 1116:     }
 1117: 
 1118: '."\n");
 1119:     return $chkallscript;
 1120: }
 1121: 
 1122: sub check_buttons {
 1123:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1124:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1125:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1126:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1127:     return $buttons;
 1128: }
 1129: 
 1130: #     Displays the submissions for one student or a group of students
 1131: sub processGroup {
 1132:     my ($request,$symb)  = @_;
 1133:     my $ctr        = 0;
 1134:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1135:     my $total      = scalar(@stuchecked)-1;
 1136: 
 1137:     foreach my $student (@stuchecked) {
 1138: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1139: 	$env{'form.student'}        = $uname;
 1140: 	$env{'form.userdom'}        = $udom;
 1141: 	$env{'form.fullname'}       = $fullname;
 1142: 	&submission($request,$ctr,$total,$symb);
 1143: 	$ctr++;
 1144:     }
 1145:     return '';
 1146: }
 1147: 
 1148: #------------------------------------------------------------------------------------
 1149: #
 1150: #-------------------------- Next few routines handles grading by student, essentially
 1151: #                           handles essay response type problem/part
 1152: #
 1153: #--- Javascript to handle the submission page functionality ---
 1154: sub sub_page_js {
 1155:     my $request = shift;
 1156: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1157:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1158:     function updateRadio(formname,id,weight) {
 1159: 	var gradeBox = formname["GD_BOX"+id];
 1160: 	var radioButton = formname["RADVAL"+id];
 1161: 	var oldpts = formname["oldpts"+id].value;
 1162: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1163: 	gradeBox.value = pts;
 1164: 	var resetbox = false;
 1165: 	if (isNaN(pts) || pts < 0) {
 1166: 	    alert("$alertmsg"+pts);
 1167: 	    for (var i=0; i<radioButton.length; i++) {
 1168: 		if (radioButton[i].checked) {
 1169: 		    gradeBox.value = i;
 1170: 		    resetbox = true;
 1171: 		}
 1172: 	    }
 1173: 	    if (!resetbox) {
 1174: 		formtextbox.value = "";
 1175: 	    }
 1176: 	    return;
 1177: 	}
 1178: 
 1179: 	if (pts > weight) {
 1180: 	    var resp = confirm("You entered a value ("+pts+
 1181: 			       ") greater than the weight for the part. Accept?");
 1182: 	    if (resp == false) {
 1183: 		gradeBox.value = oldpts;
 1184: 		return;
 1185: 	    }
 1186: 	}
 1187: 
 1188: 	for (var i=0; i<radioButton.length; i++) {
 1189: 	    radioButton[i].checked=false;
 1190: 	    if (pts == i && pts != "") {
 1191: 		radioButton[i].checked=true;
 1192: 	    }
 1193: 	}
 1194: 	updateSelect(formname,id);
 1195: 	formname["stores"+id].value = "0";
 1196:     }
 1197: 
 1198:     function writeBox(formname,id,pts) {
 1199: 	var gradeBox = formname["GD_BOX"+id];
 1200: 	if (checkSolved(formname,id) == 'update') {
 1201: 	    gradeBox.value = pts;
 1202: 	} else {
 1203: 	    var oldpts = formname["oldpts"+id].value;
 1204: 	    gradeBox.value = oldpts;
 1205: 	    var radioButton = formname["RADVAL"+id];
 1206: 	    for (var i=0; i<radioButton.length; i++) {
 1207: 		radioButton[i].checked=false;
 1208: 		if (i == oldpts) {
 1209: 		    radioButton[i].checked=true;
 1210: 		}
 1211: 	    }
 1212: 	}
 1213: 	formname["stores"+id].value = "0";
 1214: 	updateSelect(formname,id);
 1215: 	return;
 1216:     }
 1217: 
 1218:     function clearRadBox(formname,id) {
 1219: 	if (checkSolved(formname,id) == 'noupdate') {
 1220: 	    updateSelect(formname,id);
 1221: 	    return;
 1222: 	}
 1223: 	gradeSelect = formname["GD_SEL"+id];
 1224: 	for (var i=0; i<gradeSelect.length; i++) {
 1225: 	    if (gradeSelect[i].selected) {
 1226: 		var selectx=i;
 1227: 	    }
 1228: 	}
 1229: 	var stores = formname["stores"+id];
 1230: 	if (selectx == stores.value) { return };
 1231: 	var gradeBox = formname["GD_BOX"+id];
 1232: 	gradeBox.value = "";
 1233: 	var radioButton = formname["RADVAL"+id];
 1234: 	for (var i=0; i<radioButton.length; i++) {
 1235: 	    radioButton[i].checked=false;
 1236: 	}
 1237: 	stores.value = selectx;
 1238:     }
 1239: 
 1240:     function checkSolved(formname,id) {
 1241: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1242: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1243: 	    if (!reply) {return "noupdate";}
 1244: 	    formname.overRideScore.value = 'yes';
 1245: 	}
 1246: 	return "update";
 1247:     }
 1248: 
 1249:     function updateSelect(formname,id) {
 1250: 	formname["GD_SEL"+id][0].selected = true;
 1251: 	return;
 1252:     }
 1253: 
 1254: //=========== Check that a point is assigned for all the parts  ============
 1255:     function checksubmit(formname,val,total,parttot) {
 1256: 	formname.gradeOpt.value = val;
 1257: 	if (val == "Save & Next") {
 1258: 	    for (i=0;i<=total;i++) {
 1259: 		for (j=0;j<parttot;j++) {
 1260: 		    var partid = formname["partid"+i+"_"+j].value;
 1261: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1262: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1263: 			if (points == "") {
 1264: 			    var name = formname["name"+i].value;
 1265: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1266: 			    var resp = confirm("You did not assign a score for "+studentID+
 1267: 					       ", part "+partid+". Continue?");
 1268: 			    if (resp == false) {
 1269: 				formname["GD_BOX"+i+"_"+partid].focus();
 1270: 				return false;
 1271: 			    }
 1272: 			}
 1273: 		    }
 1274: 		    
 1275: 		}
 1276: 	    }
 1277: 	    
 1278: 	}
 1279: 	if (val == "Grade Student") {
 1280: 	    if (formname.Status.value == "") {
 1281: 		formname.Status.value = "Active";
 1282: 	    }
 1283: 	    formname.studentNo.value = total;
 1284: 	}
 1285: 	formname.submit();
 1286:     }
 1287: 
 1288: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1289:     function checkSubmitPage(formname,total) {
 1290: 	noscore = new Array(100);
 1291: 	var ptr = 0;
 1292: 	for (i=1;i<total;i++) {
 1293: 	    var partid = formname["q_"+i].value;
 1294: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1295: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1296: 		var status = formname["solved"+i+"_"+partid].value;
 1297: 		if (points == "" && status != "correct_by_student") {
 1298: 		    noscore[ptr] = i;
 1299: 		    ptr++;
 1300: 		}
 1301: 	    }
 1302: 	}
 1303: 	if (ptr != 0) {
 1304: 	    var sense = ptr == 1 ? ": " : "s: ";
 1305: 	    var prolist = "";
 1306: 	    if (ptr == 1) {
 1307: 		prolist = noscore[0];
 1308: 	    } else {
 1309: 		var i = 0;
 1310: 		while (i < ptr-1) {
 1311: 		    prolist += noscore[i]+", ";
 1312: 		    i++;
 1313: 		}
 1314: 		prolist += "and "+noscore[i];
 1315: 	    }
 1316: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1317: 	    if (resp == false) {
 1318: 		return false;
 1319: 	    }
 1320: 	}
 1321: 
 1322: 	formname.submit();
 1323:     }
 1324: SUBJAVASCRIPT
 1325: }
 1326: 
 1327: #--- javascript for essay type problem --
 1328: sub sub_page_kw_js {
 1329:     my $request = shift;
 1330:     my $iconpath = $request->dir_config('lonIconsURL');
 1331:     &commonJSfunctions($request);
 1332: 
 1333:     my $inner_js_msg_central= &Apache::lonhtmlcommon::scripttag(<<INNERJS);
 1334:     function checkInput() {
 1335:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1336:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1337:       var usrctr = document.msgcenter.usrctr.value;
 1338:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1339:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1340: 
 1341:       var msgchk = "";
 1342:       if (document.msgcenter.subchk.checked) {
 1343:          msgchk = "msgsub,";
 1344:       }
 1345:       var includemsg = 0;
 1346:       for (var i=1; i<=nmsg; i++) {
 1347:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1348:           var frmmsg = document.msgcenter["msg"+i];
 1349:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1350:           var showflg = opener.document.SCORE["shownOnce"+i];
 1351:           showflg.value = "1";
 1352:           var chkbox = document.msgcenter["msgn"+i];
 1353:           if (chkbox.checked) {
 1354:              msgchk += "savemsg"+i+",";
 1355:              includemsg = 1;
 1356:           }
 1357:       }
 1358:       if (document.msgcenter.newmsgchk.checked) {
 1359:          msgchk += "newmsg"+usrctr;
 1360:          includemsg = 1;
 1361:       }
 1362:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1363:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1364:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1365:       includemsg.value = msgchk;
 1366: 
 1367:       self.close()
 1368: 
 1369:     }
 1370: INNERJS
 1371: 
 1372:     my $inner_js_highlight_central= &Apache::lonhtmlcommon::scripttag(<<INNERJS);
 1373:     function updateChoice(flag) {
 1374:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1375:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1376:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1377:       opener.document.SCORE.refresh.value = "on";
 1378:       if (opener.document.SCORE.keywords.value!=""){
 1379:          opener.document.SCORE.submit();
 1380:       }
 1381:       self.close()
 1382:     }
 1383: INNERJS
 1384: 
 1385:     my $start_page_msg_central = 
 1386:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1387: 				       {'js_ready'  => 1,
 1388: 					'only_body' => 1,
 1389: 					'bgcolor'   =>'#FFFFFF',});
 1390:     my $end_page_msg_central = 
 1391: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1392: 
 1393: 
 1394:     my $start_page_highlight_central = 
 1395:         &Apache::loncommon::start_page('Highlight Central',
 1396: 				       $inner_js_highlight_central,
 1397: 				       {'js_ready'  => 1,
 1398: 					'only_body' => 1,
 1399: 					'bgcolor'   =>'#FFFFFF',});
 1400:     my $end_page_highlight_central = 
 1401: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1402: 
 1403:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1404:     $docopen=~s/^document\.//;
 1405:     my $alertmsg = &mt('Please select a word or group of words from document and then click this link.');
 1406:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1407: 
 1408: //===================== Show list of keywords ====================
 1409:   function keywords(formname) {
 1410:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
 1411:     if (nret==null) return;
 1412:     formname.keywords.value = nret;
 1413: 
 1414:     if (formname.keywords.value != "") {
 1415: 	formname.refresh.value = "on";
 1416: 	formname.submit();
 1417:     }
 1418:     return;
 1419:   }
 1420: 
 1421: //===================== Script to view submitted by ==================
 1422:   function viewSubmitter(submitter) {
 1423:     document.SCORE.refresh.value = "on";
 1424:     document.SCORE.NCT.value = "1";
 1425:     document.SCORE.unamedom0.value = submitter;
 1426:     document.SCORE.submit();
 1427:     return;
 1428:   }
 1429: 
 1430: //===================== Script to add keyword(s) ==================
 1431:   function getSel() {
 1432:     if (document.getSelection) txt = document.getSelection();
 1433:     else if (document.selection) txt = document.selection.createRange().text;
 1434:     else return;
 1435:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1436:     if (cleantxt=="") {
 1437: 	alert("$alertmsg");
 1438: 	return;
 1439:     }
 1440:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
 1441:     if (nret==null) return;
 1442:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1443:     if (document.SCORE.keywords.value != "") {
 1444: 	document.SCORE.refresh.value = "on";
 1445: 	document.SCORE.submit();
 1446:     }
 1447:     return;
 1448:   }
 1449: 
 1450: //====================== Script for composing message ==============
 1451:    // preload images
 1452:    img1 = new Image();
 1453:    img1.src = "$iconpath/mailbkgrd.gif";
 1454:    img2 = new Image();
 1455:    img2.src = "$iconpath/mailto.gif";
 1456: 
 1457:   function msgCenter(msgform,usrctr,fullname) {
 1458:     var Nmsg  = msgform.savemsgN.value;
 1459:     savedMsgHeader(Nmsg,usrctr,fullname);
 1460:     var subject = msgform.msgsub.value;
 1461:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1462:     re = /msgsub/;
 1463:     var shwsel = "";
 1464:     if (re.test(msgchk)) { shwsel = "checked" }
 1465:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1466:     displaySubject(checkEntities(subject),shwsel);
 1467:     for (var i=1; i<=Nmsg; i++) {
 1468: 	var testmsg = "savemsg"+i+",";
 1469: 	re = new RegExp(testmsg,"g");
 1470: 	shwsel = "";
 1471: 	if (re.test(msgchk)) { shwsel = "checked" }
 1472: 	var message = document.SCORE["savemsg"+i].value;
 1473: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1474: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1475: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1476:     }
 1477:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1478:     shwsel = "";
 1479:     re = /newmsg/;
 1480:     if (re.test(msgchk)) { shwsel = "checked" }
 1481:     newMsg(newmsg,shwsel);
 1482:     msgTail(); 
 1483:     return;
 1484:   }
 1485: 
 1486:   function checkEntities(strx) {
 1487:     if (strx.length == 0) return strx;
 1488:     var orgStr = ["&", "<", ">", '"']; 
 1489:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1490:     var counter = 0;
 1491:     while (counter < 4) {
 1492: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1493: 	counter++;
 1494:     }
 1495:     return strx;
 1496:   }
 1497: 
 1498:   function strReplace(strx, orgStr, newStr) {
 1499:     return strx.split(orgStr).join(newStr);
 1500:   }
 1501: 
 1502:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1503:     var height = 70*Nmsg+250;
 1504:     var scrollbar = "no";
 1505:     if (height > 600) {
 1506: 	height = 600;
 1507: 	scrollbar = "yes";
 1508:     }
 1509:     var xpos = (screen.width-600)/2;
 1510:     xpos = (xpos < 0) ? '0' : xpos;
 1511:     var ypos = (screen.height-height)/2-30;
 1512:     ypos = (ypos < 0) ? '0' : ypos;
 1513: 
 1514:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
 1515:     pWin.focus();
 1516:     pDoc = pWin.document;
 1517:     pDoc.$docopen;
 1518:     pDoc.write('$start_page_msg_central');
 1519: 
 1520:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1521:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1522:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
 1523: 
 1524:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1525:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1526:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
 1527: }
 1528:     function displaySubject(msg,shwsel) {
 1529:     pDoc = pWin.document;
 1530:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1531:     pDoc.write("<td>Subject<\\/td>");
 1532:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1533:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1534: }
 1535: 
 1536:   function displaySavedMsg(ctr,msg,shwsel) {
 1537:     pDoc = pWin.document;
 1538:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1539:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1540:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1541:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1542: }
 1543: 
 1544:   function newMsg(newmsg,shwsel) {
 1545:     pDoc = pWin.document;
 1546:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1547:     pDoc.write("<td align=\\"center\\">New<\\/td>");
 1548:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1549:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1550: }
 1551: 
 1552:   function msgTail() {
 1553:     pDoc = pWin.document;
 1554:     pDoc.write("<\\/table>");
 1555:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1556:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1557:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
 1558:     pDoc.write("<\\/form>");
 1559:     pDoc.write('$end_page_msg_central');
 1560:     pDoc.close();
 1561: }
 1562: 
 1563: //====================== Script for keyword highlight options ==============
 1564:   function kwhighlight() {
 1565:     var kwclr    = document.SCORE.kwclr.value;
 1566:     var kwsize   = document.SCORE.kwsize.value;
 1567:     var kwstyle  = document.SCORE.kwstyle.value;
 1568:     var redsel = "";
 1569:     var grnsel = "";
 1570:     var blusel = "";
 1571:     if (kwclr=="red")   {var redsel="checked"};
 1572:     if (kwclr=="green") {var grnsel="checked"};
 1573:     if (kwclr=="blue")  {var blusel="checked"};
 1574:     var sznsel = "";
 1575:     var sz1sel = "";
 1576:     var sz2sel = "";
 1577:     if (kwsize=="0")  {var sznsel="checked"};
 1578:     if (kwsize=="+1") {var sz1sel="checked"};
 1579:     if (kwsize=="+2") {var sz2sel="checked"};
 1580:     var synsel = "";
 1581:     var syisel = "";
 1582:     var sybsel = "";
 1583:     if (kwstyle=="")    {var synsel="checked"};
 1584:     if (kwstyle=="<i>") {var syisel="checked"};
 1585:     if (kwstyle=="<b>") {var sybsel="checked"};
 1586:     highlightCentral();
 1587:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
 1588:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
 1589:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
 1590:     highlightend();
 1591:     return;
 1592:   }
 1593: 
 1594:   function highlightCentral() {
 1595: //    if (window.hwdWin) window.hwdWin.close();
 1596:     var xpos = (screen.width-400)/2;
 1597:     xpos = (xpos < 0) ? '0' : xpos;
 1598:     var ypos = (screen.height-330)/2-30;
 1599:     ypos = (ypos < 0) ? '0' : ypos;
 1600: 
 1601:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1602:     hwdWin.focus();
 1603:     var hDoc = hwdWin.document;
 1604:     hDoc.$docopen;
 1605:     hDoc.write('$start_page_highlight_central');
 1606:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1607:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
 1608: 
 1609:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1610:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1611:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
 1612:   }
 1613: 
 1614:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1615:     var hDoc = hwdWin.document;
 1616:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1617:     hDoc.write("<td align=\\"left\\">");
 1618:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
 1619:     hDoc.write("<td align=\\"left\\">");
 1620:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
 1621:     hDoc.write("<td align=\\"left\\">");
 1622:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
 1623:     hDoc.write("<\\/tr>");
 1624:   }
 1625: 
 1626:   function highlightend() { 
 1627:     var hDoc = hwdWin.document;
 1628:     hDoc.write("<\\/table>");
 1629:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1630:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
 1631:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
 1632:     hDoc.write("<\\/form>");
 1633:     hDoc.write('$end_page_highlight_central');
 1634:     hDoc.close();
 1635:   }
 1636: 
 1637: SUBJAVASCRIPT
 1638: }
 1639: 
 1640: sub get_increment {
 1641:     my $increment = $env{'form.increment'};
 1642:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1643:         $increment != .1) {
 1644:         $increment = 1;
 1645:     }
 1646:     return $increment;
 1647: }
 1648: 
 1649: sub gradeBox_start {
 1650:     return (
 1651:         &Apache::loncommon::start_data_table()
 1652:        .&Apache::loncommon::start_data_table_header_row()
 1653:        .'<th>'.&mt('Part').'</th>'
 1654:        .'<th>'.&mt('Points').'</th>'
 1655:        .'<th>&nbsp;</th>'
 1656:        .'<th>'.&mt('Assign Grade').'</th>'
 1657:        .'<th>'.&mt('Weight').'</th>'
 1658:        .'<th>'.&mt('Grade Status').'</th>'
 1659:        .&Apache::loncommon::end_data_table_header_row()
 1660:     );
 1661: }
 1662: 
 1663: sub gradeBox_end {
 1664:     return (
 1665:         &Apache::loncommon::end_data_table()
 1666:     );
 1667: }
 1668: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1669: sub gradeBox {
 1670:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1671:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1672: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1673:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1674:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1675:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1676:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1677:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1678: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1679:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1680:     my $display_part= &get_display_part($partid,$symb);
 1681:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1682: 				       [$partid]);
 1683:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1684:     if ($last_resets{$partid}) {
 1685:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1686:     }
 1687:     $result.=&Apache::loncommon::start_data_table_row();
 1688:     my $ctr = 0;
 1689:     my $thisweight = 0;
 1690:     my $increment = &get_increment();
 1691: 
 1692:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1693:     while ($thisweight<=$wgt) {
 1694: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1695:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1696: 	    $thisweight.')" value="'.$thisweight.'" '.
 1697: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1698: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1699:         $thisweight += $increment;
 1700: 	$ctr++;
 1701:     }
 1702:     $radio.='</tr></table>';
 1703: 
 1704:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1705: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1706: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1707: 	$wgt.')" /></td>'."\n";
 1708:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1709: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1710: 	' </td>'."\n";
 1711:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1712: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1713:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1714: 	$line.='<option></option>'.
 1715: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1716:     } else {
 1717: 	$line.='<option selected="selected"></option>'.
 1718: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1719:     }
 1720:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1721: 
 1722: 
 1723:     $result .= 
 1724: 	    '<td>'.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 1725:     $result.=&Apache::loncommon::end_data_table_row();
 1726:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1727: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1728: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1729: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1730:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1731:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1732:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1733:         $aggtries.'" />'."\n";
 1734:     my $res_error;
 1735:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 1736:     if ($res_error) {
 1737:         return &navmap_errormsg();
 1738:     }
 1739:     return $result;
 1740: }
 1741: 
 1742: sub handback_box {
 1743:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error) = @_;
 1744:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
 1745:     my (@respids);
 1746:      my @part_response_id = &flatten_responseType($responseType);
 1747:     foreach my $part_response_id (@part_response_id) {
 1748:     	my ($part,$resp) = @{ $part_response_id };
 1749:         if ($part eq $partid) {
 1750:             push(@respids,$resp);
 1751:         }
 1752:     }
 1753:     my $result;
 1754:     foreach my $respid (@respids) {
 1755: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1756: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1757: 	next if (!@$files);
 1758: 	my $file_counter = 1;
 1759: 	foreach my $file (@$files) {
 1760: 	    if ($file =~ /\/portfolio\//) {
 1761:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1762:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1763:     	        $file_disp = "$name.$ext";
 1764:     	        $file = $file_path.$file_disp;
 1765:     	        $result.=&mt('Return commented version of [_1] to student.',
 1766:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1767:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1768:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
 1769:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
 1770:     	        $file_counter++;
 1771: 	    }
 1772: 	}
 1773:     }
 1774:     return $result;    
 1775: }
 1776: 
 1777: sub show_problem {
 1778:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1779:     my $rendered;
 1780:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1781:     &Apache::lonxml::remember_problem_counter();
 1782:     if ($mode eq 'both' or $mode eq 'text') {
 1783: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1784: 						       $env{'request.course.id'},
 1785: 						       undef,\%form);
 1786:     }
 1787:     if ($removeform) {
 1788: 	$rendered=~s|<form(.*?)>||g;
 1789: 	$rendered=~s|</form>||g;
 1790: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1791:     }
 1792:     my $companswer;
 1793:     if ($mode eq 'both' or $mode eq 'answer') {
 1794: 	&Apache::lonxml::restore_problem_counter();
 1795: 	$companswer=
 1796: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1797: 						    $env{'request.course.id'},
 1798: 						    %form);
 1799:     }
 1800:     if ($removeform) {
 1801: 	$companswer=~s|<form(.*?)>||g;
 1802: 	$companswer=~s|</form>||g;
 1803: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1804:     }
 1805:     $rendered=
 1806:         '<div class="LC_Box">'
 1807:        .'<h3 class="LC_hcell">'.&mt('View of the problem').'</h3>'
 1808:        .$rendered
 1809:        .'</div>';
 1810:     $companswer=
 1811:         '<div class="LC_Box">'
 1812:        .'<h3 class="LC_hcell">'.&mt('Correct answer').'</h3>'
 1813:        .$companswer
 1814:        .'</div>';
 1815:     my $result;
 1816:     if ($mode eq 'both') {
 1817:         $result=$rendered.$companswer;
 1818:     } elsif ($mode eq 'text') {
 1819:         $result=$rendered;
 1820:     } elsif ($mode eq 'answer') {
 1821:         $result=$companswer;
 1822:     }
 1823:     return $result;
 1824: }
 1825: 
 1826: sub files_exist {
 1827:     my ($r, $symb) = @_;
 1828:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1829: 
 1830:     foreach my $student (@students) {
 1831:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1832:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1833: 					      $udom,$uname);
 1834:         my ($string,$timestamp)= &get_last_submission(\%record);
 1835:         foreach my $submission (@$string) {
 1836:             my ($partid,$respid) =
 1837: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1838:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1839: 					   \%record);
 1840:             return 1 if (@$files);
 1841:         }
 1842:     }
 1843:     return 0;
 1844: }
 1845: 
 1846: sub download_all_link {
 1847:     my ($r,$symb) = @_;
 1848:     unless (&files_exist($r, $symb)) {
 1849:        $r->print(&mt('There are currently no submitted documents.'));
 1850:        return;
 1851:     }
 1852: 
 1853:     my $all_students = 
 1854: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1855: 
 1856:     my $parts =
 1857: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1858: 
 1859:     my $identifier = &Apache::loncommon::get_cgi_id();
 1860:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 1861:                              'cgi.'.$identifier.'.symb' => $symb,
 1862:                              'cgi.'.$identifier.'.parts' => $parts,});
 1863:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1864: 	      &mt('Download All Submitted Documents').'</a>');
 1865:     return;
 1866: }
 1867: 
 1868: sub submit_download_link {
 1869:     my ($request,$symb) = @_;
 1870:     if (!$symb) { return ''; }
 1871: #FIXME: Figure out which type of problem this is and provide appropriate download
 1872:     &download_all_link($request,$symb);
 1873: }
 1874: 
 1875: sub build_section_inputs {
 1876:     my $section_inputs;
 1877:     if ($env{'form.section'} eq '') {
 1878:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 1879:     } else {
 1880:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 1881:         foreach my $section (@sections) {
 1882:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 1883:         }
 1884:     }
 1885:     return $section_inputs;
 1886: }
 1887: 
 1888: # --------------------------- show submissions of a student, option to grade 
 1889: sub submission {
 1890:     my ($request,$counter,$total,$symb) = @_;
 1891:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 1892:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 1893:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 1894:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 1895: 
 1896:     my $probtitle=&Apache::lonnet::gettitle($symb); 
 1897:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 1898: 
 1899:     if (!&canview($usec)) {
 1900: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
 1901: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
 1902: 			$env{'request.course.id'}.')</span>');
 1903: 	return;
 1904:     }
 1905: 
 1906:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 1907:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 1908:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 1909:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 1910:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1911: 	'" src="'.$request->dir_config('lonIconsURL').
 1912: 	'/check.gif" height="16" border="0" />';
 1913: 
 1914:     my %old_essays;
 1915:     # header info
 1916:     if ($counter == 0) {
 1917: 	&sub_page_js($request);
 1918: 	&sub_page_kw_js($request);
 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="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 1964: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 1965: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 1966: 			&build_section_inputs().
 1967: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 1968: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
 1969: 			'<input type="hidden" name="NCT"'.
 1970: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 1971: 	if ($env{'form.handgrade'} eq 'yes') {
 1972: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 1973: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 1974: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 1975: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 1976: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 1977: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 1978: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 1979: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 1980: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 1981: 	    }
 1982: 	}
 1983: 	
 1984: 	my ($cts,$prnmsg) = (1,'');
 1985: 	while ($cts <= $env{'form.savemsgN'}) {
 1986: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 1987: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 1988: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 1989: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 1990: 		'" />'."\n".
 1991: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 1992: 	    $cts++;
 1993: 	}
 1994: 	$request->print($prnmsg);
 1995: 
 1996: 	if ($env{'form.handgrade'} eq 'yes') {
 1997: #
 1998: # Print out the keyword options line
 1999: #
 2000: 	    $request->print(<<KEYWORDS);
 2001: &nbsp;<b>Keyword Options:</b>&nbsp;
 2002: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
 2003: <a href="#" onmousedown="javascript:getSel(); return false"
 2004:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
 2005: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
 2006: KEYWORDS
 2007: #
 2008: # Load the other essays for similarity check
 2009: #
 2010:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2011: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2012: 	    $apath=&escape($apath);
 2013: 	    $apath=~s/\W/\_/gs;
 2014: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 2015:         }
 2016:     }
 2017: 
 2018: # This is where output for one specific student would start
 2019:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2020:     $request->print(
 2021:         "\n\n"
 2022:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2023:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2024:        ."\n"
 2025:     );
 2026: 
 2027:     # Show additional functions if allowed
 2028:     if ($perm{'vgr'}) {
 2029:         $request->print(
 2030:             &Apache::loncommon::track_student_link(
 2031:                 &mt('View recent activity'),
 2032:                 $uname,$udom,'check')
 2033:            .' '
 2034:         );
 2035:     }
 2036:     if ($perm{'opa'}) {
 2037:         $request->print(
 2038:             &Apache::loncommon::pprmlink(
 2039:                 &mt('Set/Change parameters'),
 2040:                 $uname,$udom,$symb,'check'));
 2041:     }
 2042: 
 2043:     # Show Problem
 2044:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2045: 	my $mode;
 2046: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2047: 	    $mode='both';
 2048: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2049: 	    $mode='text';
 2050: 	} elsif ($env{'form.vAns'} eq 'all') {
 2051: 	    $mode='answer';
 2052: 	}
 2053: 	&Apache::lonxml::clear_problem_counter();
 2054: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2055:     }
 2056: 
 2057:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2058:     my $res_error;
 2059:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2060:     if ($res_error) {
 2061:         $request->print(&navmap_errormsg());
 2062:         return;
 2063:     }
 2064: 
 2065:     # Display student info
 2066:     $request->print(($counter == 0 ? '' : '<br />'));
 2067: 
 2068:     my $result='<div class="LC_Box">'
 2069:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
 2070:     $result.='<input type="hidden" name="name'.$counter.
 2071:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2072:     if ($env{'form.handgrade'} eq 'no') {
 2073:         $result.='<p class="LC_info">'
 2074:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2075:                 ."</p>\n";
 2076:     }
 2077: 
 2078:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2079:     my $fullname;
 2080:     my $col_fullnames = [];
 2081:     if ($env{'form.handgrade'} eq 'yes') {
 2082: 	(my $sub_result,$fullname,$col_fullnames)=
 2083: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2084: 				 $counter);
 2085: 	$result.=$sub_result;
 2086:     }
 2087:     $request->print($result."\n");
 2088: 
 2089:     # print student answer/submission
 2090:     # Options are (1) Handgraded submission only
 2091:     #             (2) Last submission, includes submission that is not handgraded 
 2092:     #                  (for multi-response type part)
 2093:     #             (3) Last submission plus the parts info
 2094:     #             (4) The whole record for this student
 2095:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
 2096: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2097: 	
 2098: 	my $lastsubonly;
 2099: 
 2100:         if ($$timestamp eq '') {
 2101:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2102:         } else {
 2103:             $lastsubonly =
 2104:                 '<div class="LC_grade_submissions_body">'
 2105:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
 2106: 
 2107: 	    my %seenparts;
 2108: 	    my @part_response_id = &flatten_responseType($responseType);
 2109: 	    foreach my $part (@part_response_id) {
 2110: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2111: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2112: 
 2113: 		my ($partid,$respid) = @{ $part };
 2114: 		my $display_part=&get_display_part($partid,$symb);
 2115: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2116: 		    if (exists($seenparts{$partid})) { next; }
 2117: 		    $seenparts{$partid}=1;
 2118: 		    my $submitby='<b>Part:</b> '.$display_part.
 2119: 			' <b>Collaborative submission by:</b> '.
 2120: 			'<a href="javascript:viewSubmitter(\''.
 2121: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
 2122: 			'\');" target="_self">'.
 2123: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
 2124: 		    $request->print($submitby);
 2125: 		    next;
 2126: 		}
 2127: 		my $responsetype = $responseType->{$partid}->{$respid};
 2128: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2129:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2130:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2131:                         ' <span class="LC_internal_info">'.
 2132:                         '('.&mt('Part ID: [_1]',$respid).')'.
 2133:                         '</span>&nbsp; &nbsp;'.
 2134: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2135: 		    next;
 2136: 		}
 2137: 		foreach my $submission (@$string) {
 2138: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2139: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2140: 		    my ($ressub,$hide,$subval) = split(/:/,$submission,3);
 2141: 		    # Similarity check
 2142: 		    my $similar='';
 2143: 		    if($env{'form.checkPlag'}){
 2144: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2145: 			    &most_similar($uname,$udom,$subval,\%old_essays);
 2146: 			if ($osim) {
 2147: 			    $osim=int($osim*100.0);
 2148: 			    my %old_course_desc = 
 2149: 				&Apache::lonnet::coursedescription($ocrsid,
 2150: 								   {'one_time' => 1});
 2151: 
 2152:                             if ($hide) {
 2153:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2154:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2155:                             } else {
 2156: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
 2157: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2158: 				        $osim,
 2159: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2160: 				        $old_course_desc{'description'},
 2161: 				        $old_course_desc{'num'},
 2162: 				        $old_course_desc{'domain'}).
 2163: 				    '</span></h3><blockquote><i>'.
 2164: 				    &keywords_highlight($oessay).
 2165: 				    '</i></blockquote><hr />';
 2166:                             }
 2167: 			}
 2168: 		    }
 2169: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
 2170: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
 2171: 			($env{'form.lastSub'} eq 'hdgrade' && 
 2172: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2173: 			my $display_part=&get_display_part($partid,$symb);
 2174:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
 2175:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2176:                             ' <span class="LC_internal_info">'.
 2177:                             '('.&mt('Part ID: [_1]',$respid).')'.
 2178:                             '</span>&nbsp; &nbsp;';
 2179: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2180: 			if (@$files) {
 2181:                             if ($hide) {
 2182:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2183:                             } else {
 2184:                                 $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
 2185:                                 foreach my $file (@$files) {
 2186:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2187:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
 2188:                                 }
 2189:                             }
 2190: 			    $lastsubonly.='<br />';
 2191: 			}
 2192:                         if ($hide) {
 2193:                             $lastsubonly.='<b>'.&mt('Anonymous Survey').'</b>'; 
 2194:                         } else {
 2195: 			    $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
 2196: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
 2197: 					     $respid,\%record,$order,undef,$uname,$udom);
 2198:                         }
 2199: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2200: 			$lastsubonly.='</div>';
 2201: 		    }
 2202: 		}
 2203: 	    }
 2204: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2205: 	}
 2206: 	$request->print($lastsubonly);
 2207:    } elsif ($env{'form.lastSub'} eq 'datesub') {
 2208:         my ($parts,$handgrade,$responseType) = &response_type($symb);
 2209: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2210:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2211: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2212: 								 $env{'request.course.id'},
 2213: 								 $last,'.submission',
 2214: 								 'Apache::grades::keywords_highlight'));
 2215:     }
 2216: 
 2217:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2218: 	.$udom.'" />'."\n");
 2219:     # return if view submission with no grading option
 2220: # FIXME: the logic seems off here. Why show the grade button if you cannot grade?
 2221:     if (!&canmodify($usec)) {
 2222: 	my $toGrade.='<input type="button" value="Grade Student" '.
 2223: 	    'onclick="javascript:checksubmit(this.form,\'Grade Student\',\''
 2224: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
 2225: 	$toGrade.='</div>'."\n";
 2226: 	$request->print($toGrade);
 2227: 	return;
 2228:     } else {
 2229: 	$request->print('</div>'."\n");
 2230:     }
 2231: 
 2232:     # essay grading message center
 2233:     if ($env{'form.handgrade'} eq 'yes') {
 2234: 	my $result='<div class="LC_grade_message_center">';
 2235:     
 2236: 	$result.='<div class="LC_grade_message_center_header">'.
 2237: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2238: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2239: 	my $msgfor = $givenn.' '.$lastname;
 2240: 	if (scalar(@$col_fullnames) > 0) {
 2241: 	    my $lastone = pop(@$col_fullnames);
 2242: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2243: 	}
 2244: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2245: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2246: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2247: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2248: 	    ',\''.$msgfor.'\');" target="_self">'.
 2249: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
 2250: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2251: 	    '<img src="'.$request->dir_config('lonIconsURL').
 2252: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2253: 	    '<br />&nbsp;('.
 2254: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2255: 	$result.='</div></div>';
 2256: 	$request->print($result);
 2257:     }
 2258: 
 2259:     my %seen = ();
 2260:     my @partlist;
 2261:     my @gradePartRespid;
 2262:     my @part_response_id = &flatten_responseType($responseType);
 2263:     $request->print(
 2264:         '<div class="LC_Box">'
 2265:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2266:     );
 2267:     $request->print(&gradeBox_start());
 2268:     foreach my $part_response_id (@part_response_id) {
 2269:     	my ($partid,$respid) = @{ $part_response_id };
 2270: 	my $part_resp = join('_',@{ $part_response_id });
 2271: 	next if ($seen{$partid} > 0);
 2272: 	$seen{$partid}++;
 2273: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2274: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2275: 	push(@partlist,$partid);
 2276: 	push(@gradePartRespid,$partid.'.'.$respid);
 2277: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2278:     }
 2279:     $request->print(&gradeBox_end()); # </div>
 2280:     $request->print('</div>');
 2281: 
 2282:     $request->print('<div class="LC_grade_info_links">');
 2283:     $request->print('</div>');
 2284: 
 2285:     $result='<input type="hidden" name="partlist'.$counter.
 2286: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2287:     $result.='<input type="hidden" name="gradePartRespid'.
 2288: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2289:     my $ctr = 0;
 2290:     while ($ctr < scalar(@partlist)) {
 2291: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2292: 	    $partlist[$ctr].'" />'."\n";
 2293: 	$ctr++;
 2294:     }
 2295:     $request->print($result.''."\n");
 2296: 
 2297: # Done with printing info for one student
 2298: 
 2299:     $request->print('</div>');#LC_grade_show_user
 2300: 
 2301: 
 2302:     # print end of form
 2303:     if ($counter == $total) {
 2304:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2305: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2306: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2307: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2308: 	my $ntstu ='<select name="NTSTU">'.
 2309: 	    '<option>1</option><option>2</option>'.
 2310: 	    '<option>3</option><option>5</option>'.
 2311: 	    '<option>7</option><option>10</option></select>'."\n";
 2312: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2313: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2314:         $endform.=&mt('[_1]student(s)',$ntstu);
 2315: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2316: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2317: 	    '<input type="button" value="'.&mt('Next').'" '.
 2318: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2319:         $endform.='<span class="LC_warning">'.
 2320:                   &mt('(Next and Previous (student) do not save the scores.)').
 2321:                   '</span>'."\n" ;
 2322:         $endform.="<input type='hidden' value='".&get_increment().
 2323:             "' name='increment' />";
 2324: 	$endform.='</td></tr></table></form>';
 2325: 	$request->print($endform);
 2326:     }
 2327:     return '';
 2328: }
 2329: 
 2330: sub check_collaborators {
 2331:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2332:     my ($result,@col_fullnames);
 2333:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2334:     foreach my $part (keys(%$handgrade)) {
 2335: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2336: 					'.maxcollaborators',
 2337: 					$symb,$udom,$uname);
 2338: 	next if ($ncol <= 0);
 2339: 	$part =~ s/\_/\./g;
 2340: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2341: 	my (@good_collaborators, @bad_collaborators);
 2342: 	foreach my $possible_collaborator
 2343: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2344: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2345: 	    next if ($possible_collaborator eq '');
 2346: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
 2347: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2348: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2349: 	    # Doing this grep allows 'fuzzy' specification
 2350: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2351: 			       keys(%$classlist));
 2352: 	    if (! scalar(@matches)) {
 2353: 		push(@bad_collaborators, $possible_collaborator);
 2354: 	    } else {
 2355: 		push(@good_collaborators, @matches);
 2356: 	    }
 2357: 	}
 2358: 	if (scalar(@good_collaborators) != 0) {
 2359: 	    $result.='<br />'.&mt('Collaborators: ');
 2360: 	    foreach my $name (@good_collaborators) {
 2361: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2362: 		push(@col_fullnames, $givenn.' '.$lastname);
 2363: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
 2364: 	    }
 2365: 	    $result.='<br />'."\n";
 2366: 	    my ($part)=split(/\./,$part);
 2367: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2368: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2369: 		"\n";
 2370: 	}
 2371: 	if (scalar(@bad_collaborators) > 0) {
 2372: 	    $result.='<div class="LC_warning">';
 2373: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2374: 	    $result .= '</div>';
 2375: 	}         
 2376: 	if (scalar(@bad_collaborators > $ncol)) {
 2377: 	    $result .= '<div class="LC_warning">';
 2378: 	    $result .= &mt('This student has submitted too many '.
 2379: 		'collaborators.  Maximum is [_1].',$ncol);
 2380: 	    $result .= '</div>';
 2381: 	}
 2382:     }
 2383:     return ($result,$fullname,\@col_fullnames);
 2384: }
 2385: 
 2386: #--- Retrieve the last submission for all the parts
 2387: sub get_last_submission {
 2388:     my ($returnhash)=@_;
 2389:     my (@string,$timestamp,%lasthidden);
 2390:     if ($$returnhash{'version'}) {
 2391: 	my %lasthash=();
 2392: 	my ($version);
 2393: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2394: 	    foreach my $key (sort(split(/\:/,
 2395: 					$$returnhash{$version.':keys'}))) {
 2396: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2397: 		$timestamp = 
 2398: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2399: 	    }
 2400: 	}
 2401:         my %typeparts;
 2402:         my $showsurv = 
 2403:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2404:         foreach my $key (sort(keys(%lasthash))) {
 2405:             if ($key =~ /\.type$/) {
 2406:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2407:                     ($lasthash{$key} eq 'anonsurveycred')) {
 2408:                     my ($ign,@parts) = split(/\./,$key);
 2409:                     pop(@parts);
 2410:                     unless ($showsurv) {
 2411:                         my $id = join(',',@parts);
 2412:                         $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2413:                     }
 2414:                     delete($lasthash{$key});
 2415:                 }
 2416:             }
 2417:         }
 2418:         my @hidden = keys(%typeparts);
 2419: 	foreach my $key (keys(%lasthash)) {
 2420: 	    next if ($key !~ /\.submission$/);
 2421:             my $hide;
 2422:             if (@hidden) {
 2423:                 foreach my $id (@hidden) {
 2424:                     if ($key =~ /^\Q$id\E/) {
 2425:                         $hide = 1;
 2426:                         last;
 2427:                     }
 2428:                 }
 2429:             }
 2430: 	    my ($partid,$foo) = split(/submission$/,$key);
 2431: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 2432: 		'<span class="LC_warning">Draft Copy</span> ' : '';
 2433: 	    push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
 2434: 	}
 2435:     }
 2436:     if (!@string) {
 2437: 	$string[0] =
 2438: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2439:     }
 2440:     return (\@string,\$timestamp);
 2441: }
 2442: 
 2443: #--- High light keywords, with style choosen by user.
 2444: sub keywords_highlight {
 2445:     my $string    = shift;
 2446:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2447:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2448:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2449:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2450:     foreach my $keyword (@keylist) {
 2451: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2452:     }
 2453:     return $string;
 2454: }
 2455: 
 2456: #--- Called from submission routine
 2457: sub processHandGrade {
 2458:     my ($request,$symb) = @_;
 2459:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2460:     my $button = $env{'form.gradeOpt'};
 2461:     my $ngrade = $env{'form.NCT'};
 2462:     my $ntstu  = $env{'form.NTSTU'};
 2463:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2464:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2465: 
 2466:     if ($button eq 'Save & Next') {
 2467: 	my $ctr = 0;
 2468: 	while ($ctr < $ngrade) {
 2469: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2470: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2471: 	    if ($errorflag eq 'no_score') {
 2472: 		$ctr++;
 2473: 		next;
 2474: 	    }
 2475: 	    if ($errorflag eq 'not_allowed') {
 2476: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
 2477: 		$ctr++;
 2478: 		next;
 2479: 	    }
 2480: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2481: 	    my ($subject,$message,$msgstatus) = ('','','');
 2482: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2483:             my ($feedurl,$showsymb) =
 2484: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2485: 	    my $messagetail;
 2486: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2487: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2488: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2489: 		$subject.=' ['.$restitle.']';
 2490: 		my (@msgnum) = split(/,/,$includemsg);
 2491: 		foreach (@msgnum) {
 2492: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2493: 		}
 2494: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2495: 		if ($env{'form.withgrades'.$ctr}) {
 2496: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2497: 		    $messagetail = " for <a href=\"".
 2498: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
 2499: 		}
 2500: 		$msgstatus = 
 2501:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2502: 						     $message.$messagetail,
 2503:                                                      undef,$feedurl,undef,
 2504:                                                      undef,undef,$showsymb,
 2505:                                                      $restitle);
 2506: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 2507: 				$msgstatus);
 2508: 	    }
 2509: 	    if ($env{'form.collaborator'.$ctr}) {
 2510: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2511: 		foreach my $collabstr (@collabstrs) {
 2512: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2513: 		    foreach my $collaborator (@collaborators) {
 2514: 			my ($errorflag,$pts,$wgt) = 
 2515: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2516: 					   $env{'form.unamedom'.$ctr},$part);
 2517: 			if ($errorflag eq 'not_allowed') {
 2518: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2519: 			    next;
 2520: 			} elsif ($message ne '') {
 2521: 			    my ($baseurl,$showsymb) = 
 2522: 				&get_feedurl_and_symb($symb,$collaborator,
 2523: 						      $udom);
 2524: 			    if ($env{'form.withgrades'.$ctr}) {
 2525: 				$messagetail = " for <a href=\"".
 2526:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
 2527: 			    }
 2528: 			    $msgstatus = 
 2529: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2530: 			}
 2531: 		    }
 2532: 		}
 2533: 	    }
 2534: 	    $ctr++;
 2535: 	}
 2536:     }
 2537: 
 2538:     if ($env{'form.handgrade'} eq 'yes') {
 2539: 	# Keywords sorted in alphabatical order
 2540: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2541: 	my %keyhash = ();
 2542: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2543: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2544: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2545: 	$env{'form.keywords'} = join(' ',@keywords);
 2546: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2547: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2548: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2549: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2550: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2551: 
 2552: 	# message center - Order of message gets changed. Blank line is eliminated.
 2553: 	# New messages are saved in env for the next student.
 2554: 	# All messages are saved in nohist_handgrade.db
 2555: 	my ($ctr,$idx) = (1,1);
 2556: 	while ($ctr <= $env{'form.savemsgN'}) {
 2557: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2558: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2559: 		$idx++;
 2560: 	    }
 2561: 	    $ctr++;
 2562: 	}
 2563: 	$ctr = 0;
 2564: 	while ($ctr < $ngrade) {
 2565: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2566: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2567: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2568: 		$idx++;
 2569: 	    }
 2570: 	    $ctr++;
 2571: 	}
 2572: 	$env{'form.savemsgN'} = --$idx;
 2573: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2574: 	my $putresult = &Apache::lonnet::put
 2575: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2576:     }
 2577:     # Called by Save & Refresh from Highlight Attribute Window
 2578:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2579:     if ($env{'form.refresh'} eq 'on') {
 2580: 	my ($ctr,$total) = (0,0);
 2581: 	while ($ctr < $ngrade) {
 2582: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2583: 	    $ctr++;
 2584: 	}
 2585: 	$env{'form.NTSTU'}=$ngrade;
 2586: 	$ctr = 0;
 2587: 	while ($ctr < $total) {
 2588: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2589: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2590: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2591: 	    &submission($request,$ctr,$total-1);
 2592: 	    $ctr++;
 2593: 	}
 2594: 	return '';
 2595:     }
 2596: 
 2597: # Go directly to grade student - from submission or link from chart page
 2598:     if ($button eq 'Grade Student') {
 2599: #	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
 2600: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
 2601: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2602: 	$env{'form.fullname'} = $$fullname{$processUser};
 2603: 	&submission($request,0,0);
 2604: 	return '';
 2605:     }
 2606: 
 2607:     # Get the next/previous one or group of students
 2608:     my $firststu = $env{'form.unamedom0'};
 2609:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2610:     my $ctr = 2;
 2611:     while ($laststu eq '') {
 2612: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2613: 	$ctr++;
 2614: 	$laststu = $firststu if ($ctr > $ngrade);
 2615:     }
 2616: 
 2617:     my (@parsedlist,@nextlist);
 2618:     my ($nextflg) = 0;
 2619:     foreach my $item (sort 
 2620: 	     {
 2621: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2622: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2623: 		 }
 2624: 		 return $a cmp $b;
 2625: 	     } (keys(%$fullname))) {
 2626: # FIXME: this is fishy, looks like the button label
 2627: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2628: 	    push(@parsedlist,$item);
 2629: 	}
 2630: 	$nextflg = 1 if ($item eq $laststu);
 2631: 	if ($button eq 'Previous') {
 2632: 	    last if ($item eq $firststu);
 2633: 	    push(@parsedlist,$item);
 2634: 	}
 2635:     }
 2636:     $ctr = 0;
 2637: # FIXME: this is fishy, looks like the button label
 2638:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2639:     my $res_error;
 2640:     my ($partlist) = &response_type($symb,\$res_error);
 2641:     if ($res_error) {
 2642:         $request->print(&navmap_errormsg());
 2643:         return;
 2644:     }
 2645:     foreach my $student (@parsedlist) {
 2646: 	my $submitonly=$env{'form.submitonly'};
 2647: 	my ($uname,$udom) = split(/:/,$student);
 2648: 	
 2649: 	if ($submitonly eq 'queued') {
 2650: 	    my %queue_status = 
 2651: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2652: 							$udom,$uname);
 2653: 	    next if (!defined($queue_status{'gradingqueue'}));
 2654: 	}
 2655: 
 2656: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2657: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2658: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2659: 	    my $submitted = 0;
 2660: 	    my $ungraded = 0;
 2661: 	    my $incorrect = 0;
 2662: 	    foreach my $item (keys(%status)) {
 2663: 		$submitted = 1 if ($status{$item} ne 'nothing');
 2664: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 2665: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 2666: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 2667: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2668: 		    $submitted = 0;
 2669: 		}
 2670: 	    }
 2671: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2672: 				     $submitonly eq 'incorrect' ||
 2673: 				     $submitonly eq 'graded'));
 2674: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2675: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2676: 	}
 2677: 	push(@nextlist,$student) if ($ctr < $ntstu);
 2678: 	last if ($ctr == $ntstu);
 2679: 	$ctr++;
 2680:     }
 2681: 
 2682:     $ctr = 0;
 2683:     my $total = scalar(@nextlist)-1;
 2684: 
 2685:     foreach (sort(@nextlist)) {
 2686: 	my ($uname,$udom,$submitter) = split(/:/);
 2687: 	$env{'form.student'}  = $uname;
 2688: 	$env{'form.userdom'}  = $udom;
 2689: 	$env{'form.fullname'} = $$fullname{$_};
 2690: 	&submission($request,$ctr,$total);
 2691: 	$ctr++;
 2692:     }
 2693:     if ($total < 0) {
 2694: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
 2695: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
 2696: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
 2697: 	$request->print($the_end);
 2698:     }
 2699:     return '';
 2700: }
 2701: 
 2702: #---- Save the score and award for each student, if changed
 2703: sub saveHandGrade {
 2704:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 2705:     my @version_parts;
 2706:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 2707: 					   $env{'request.course.id'});
 2708:     if (!&canmodify($usec)) { return('not_allowed'); }
 2709:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 2710:     my @parts_graded;
 2711:     my %newrecord  = ();
 2712:     my ($pts,$wgt) = ('','');
 2713:     my %aggregate = ();
 2714:     my $aggregateflag = 0;
 2715:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 2716:     foreach my $new_part (@parts) {
 2717: 	#collaborator ($submi may vary for different parts
 2718: 	if ($submitter && $new_part ne $part) { next; }
 2719: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 2720: 	if ($dropMenu eq 'excused') {
 2721: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 2722: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 2723: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 2724: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 2725: 		}
 2726: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 2727: 	    }
 2728: 	} elsif ($dropMenu eq 'reset status'
 2729: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 2730: 	    foreach my $key (keys(%record)) {
 2731: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 2732: 	    }
 2733: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2734: 		"$env{'user.name'}:$env{'user.domain'}";
 2735:             my $totaltries = $record{'resource.'.$part.'.tries'};
 2736: 
 2737:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2738: 					       [$new_part]);
 2739:             my $aggtries =$totaltries;
 2740:             if ($last_resets{$new_part}) {
 2741:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 2742: 					   $new_part);
 2743:             }
 2744: 
 2745:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 2746:             if ($aggtries > 0) {
 2747:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 2748:                 $aggregateflag = 1;
 2749:             }
 2750: 	} elsif ($dropMenu eq '') {
 2751: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 2752: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 2753: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 2754: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 2755: 		next;
 2756: 	    }
 2757: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 2758: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 2759: 	    my $partial= $pts/$wgt;
 2760: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 2761: 		#do not update score for part if not changed.
 2762:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 2763: 		next;
 2764: 	    } else {
 2765: 	        push(@parts_graded,$new_part);
 2766: 	    }
 2767: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 2768: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 2769: 	    }
 2770: 	    my $reckey = 'resource.'.$new_part.'.solved';
 2771: 	    if ($partial == 0) {
 2772: 		if ($record{$reckey} ne 'incorrect_by_override') {
 2773: 		    $newrecord{$reckey} = 'incorrect_by_override';
 2774: 		}
 2775: 	    } else {
 2776: 		if ($record{$reckey} ne 'correct_by_override') {
 2777: 		    $newrecord{$reckey} = 'correct_by_override';
 2778: 		}
 2779: 	    }	    
 2780: 	    if ($submitter && 
 2781: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 2782: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 2783: 	    }
 2784: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2785: 		"$env{'user.name'}:$env{'user.domain'}";
 2786: 	}
 2787: 	# unless problem has been graded, set flag to version the submitted files
 2788: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 2789: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 2790: 	        $dropMenu eq 'reset status')
 2791: 	   {
 2792: 	    push(@version_parts,$new_part);
 2793: 	}
 2794:     }
 2795:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2796:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2797: 
 2798:     if (%newrecord) {
 2799:         if (@version_parts) {
 2800:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 2801:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 2802: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 2803: 	    foreach my $new_part (@version_parts) {
 2804: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 2805: 				$new_part,\%newrecord);
 2806: 	    }
 2807:         }
 2808: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 2809: 				$env{'request.course.id'},$domain,$stuname);
 2810: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 2811: 				     $cdom,$cnum,$domain,$stuname);
 2812:     }
 2813:     if ($aggregateflag) {
 2814:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 2815: 			      $cdom,$cnum);
 2816:     }
 2817:     return ('',$pts,$wgt);
 2818: }
 2819: 
 2820: sub check_and_remove_from_queue {
 2821:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 2822:     my @ungraded_parts;
 2823:     foreach my $part (@{$parts}) {
 2824: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 2825: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 2826: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 2827: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 2828: 		) {
 2829: 	    push(@ungraded_parts, $part);
 2830: 	}
 2831:     }
 2832:     if ( !@ungraded_parts ) {
 2833: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 2834: 					       $cnum,$domain,$stuname);
 2835:     }
 2836: }
 2837: 
 2838: sub handback_files {
 2839:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 2840:     my $portfolio_root = '/userfiles/portfolio';
 2841:     my $res_error;
 2842:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2843:     if ($res_error) {
 2844:         $request->print('<br />'.&navmap_errormsg().'<br />');
 2845:         return;
 2846:     }
 2847:     my @part_response_id = &flatten_responseType($responseType);
 2848:     foreach my $part_response_id (@part_response_id) {
 2849:     	my ($part_id,$resp_id) = @{ $part_response_id };
 2850: 	my $part_resp = join('_',@{ $part_response_id });
 2851:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
 2852:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 2853:                 my $file_counter = 1;
 2854: 		my $file_msg;
 2855:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
 2856:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
 2857:                     my ($directory,$answer_file) = 
 2858:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
 2859:                     my ($answer_name,$answer_ver,$answer_ext) =
 2860: 		        &file_name_version_ext($answer_file);
 2861: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 2862:                     my $getpropath = 1;
 2863: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
 2864: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2865:                     # fix file name
 2866:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 2867:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 2868:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
 2869:             	                                $save_file_name);
 2870:                     if ($result !~ m|^/uploaded/|) {
 2871:                         $request->print('<br /><span class="LC_error">'.
 2872:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 2873:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
 2874:                                         '</span>');
 2875:                     } else {
 2876:                         # mark the file as read only
 2877:                         my @files = ($save_file_name);
 2878:                         my @what = ($symb,$env{'request.course.id'},'handback');
 2879:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
 2880: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 2881: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 2882: 			}
 2883:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 2884: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
 2885: 
 2886:                     }
 2887:                     $request->print("<br />".$fname." will be the uploaded file name");
 2888:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
 2889:                     $file_counter++;
 2890:                 }
 2891: 		my $subject = "File Handed Back by Instructor ";
 2892: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
 2893: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
 2894: 		$message .= ' The returned file(s) are named: '. $file_msg;
 2895: 		$message .= " and can be found in your portfolio space.";
 2896: 		my ($feedurl,$showsymb) = 
 2897: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
 2898:                 my $restitle = &Apache::lonnet::gettitle($symb);
 2899: 		my $msgstatus = 
 2900:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
 2901: 			 ' (File Returned) ['.$restitle.']',$message,undef,
 2902:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
 2903:             }
 2904:         }
 2905:     return;
 2906: }
 2907: 
 2908: sub get_feedurl_and_symb {
 2909:     my ($symb,$uname,$udom) = @_;
 2910:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2911:     $url = &Apache::lonnet::clutter($url);
 2912:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 2913: 					$symb,$udom,$uname);
 2914:     if ($encrypturl =~ /^yes$/i) {
 2915: 	&Apache::lonenc::encrypted(\$url,1);
 2916: 	&Apache::lonenc::encrypted(\$symb,1);
 2917:     }
 2918:     return ($url,$symb);
 2919: }
 2920: 
 2921: sub get_submitted_files {
 2922:     my ($udom,$uname,$partid,$respid,$record) = @_;
 2923:     my @files;
 2924:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 2925:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 2926:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 2927:     	    push(@files,$file_url.$file);
 2928:         }
 2929:     }
 2930:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 2931:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 2932:     }
 2933:     return (\@files);
 2934: }
 2935: 
 2936: # ----------- Provides number of tries since last reset.
 2937: sub get_num_tries {
 2938:     my ($record,$last_reset,$part) = @_;
 2939:     my $timestamp = '';
 2940:     my $num_tries = 0;
 2941:     if ($$record{'version'}) {
 2942:         for (my $version=$$record{'version'};$version>=1;$version--) {
 2943:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 2944:                 $timestamp = $$record{$version.':timestamp'};
 2945:                 if ($timestamp > $last_reset) {
 2946:                     $num_tries ++;
 2947:                 } else {
 2948:                     last;
 2949:                 }
 2950:             }
 2951:         }
 2952:     }
 2953:     return $num_tries;
 2954: }
 2955: 
 2956: # ----------- Determine decrements required in aggregate totals 
 2957: sub decrement_aggs {
 2958:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 2959:     my %decrement = (
 2960:                         attempts => 0,
 2961:                         users => 0,
 2962:                         correct => 0
 2963:                     );
 2964:     $decrement{'attempts'} = $aggtries;
 2965:     if ($solvedstatus =~ /^correct/) {
 2966:         $decrement{'correct'} = 1;
 2967:     }
 2968:     if ($aggtries == $totaltries) {
 2969:         $decrement{'users'} = 1;
 2970:     }
 2971:     foreach my $type (keys(%decrement)) {
 2972:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 2973:     }
 2974:     return;
 2975: }
 2976: 
 2977: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 2978: sub get_last_resets {
 2979:     my ($symb,$courseid,$partids) =@_;
 2980:     my %last_resets;
 2981:     my $cdom = $env{'course.'.$courseid.'.domain'};
 2982:     my $cname = $env{'course.'.$courseid.'.num'};
 2983:     my @keys;
 2984:     foreach my $part (@{$partids}) {
 2985: 	push(@keys,"$symb\0$part\0resettime");
 2986:     }
 2987:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 2988: 				     $cdom,$cname);
 2989:     foreach my $part (@{$partids}) {
 2990: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 2991:     }
 2992:     return %last_resets;
 2993: }
 2994: 
 2995: # ----------- Handles creating versions for portfolio files as answers
 2996: sub version_portfiles {
 2997:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 2998:     my $version_parts = join('|',@$v_flag);
 2999:     my @returned_keys;
 3000:     my $parts = join('|', @$parts_graded);
 3001:     my $portfolio_root = '/userfiles/portfolio';
 3002:     foreach my $key (keys(%$record)) {
 3003:         my $new_portfiles;
 3004:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3005:             my @versioned_portfiles;
 3006:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3007:             foreach my $file (@portfiles) {
 3008:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 3009:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 3010: 		my ($answer_name,$answer_ver,$answer_ext) =
 3011: 		    &file_name_version_ext($answer_file);
 3012:                 my $getpropath = 1;    
 3013:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
 3014:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 3015:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 3016:                 if ($new_answer ne 'problem getting file') {
 3017:                     push(@versioned_portfiles, $directory.$new_answer);
 3018:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 3019:                         [$directory.$new_answer],
 3020:                         [$symb,$env{'request.course.id'},'graded']);
 3021:                 }
 3022:             }
 3023:             $$record{$key} = join(',',@versioned_portfiles);
 3024:             push(@returned_keys,$key);
 3025:         }
 3026:     } 
 3027:     return (@returned_keys);   
 3028: }
 3029: 
 3030: sub get_next_version {
 3031:     my ($answer_name, $answer_ext, $dir_list) = @_;
 3032:     my $version;
 3033:     foreach my $row (@$dir_list) {
 3034:         my ($file) = split(/\&/,$row,2);
 3035:         my ($file_name,$file_version,$file_ext) =
 3036: 	    &file_name_version_ext($file);
 3037:         if (($file_name eq $answer_name) && 
 3038: 	    ($file_ext eq $answer_ext)) {
 3039:                 # gets here if filename and extension match, regardless of version
 3040:                 if ($file_version ne '') {
 3041:                 # a versioned file is found  so save it for later
 3042:                 if ($file_version > $version) {
 3043: 		    $version = $file_version;
 3044: 	        }
 3045:             }
 3046:         }
 3047:     } 
 3048:     $version ++;
 3049:     return($version);
 3050: }
 3051: 
 3052: sub version_selected_portfile {
 3053:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3054:     my ($answer_name,$answer_ver,$answer_ext) =
 3055:         &file_name_version_ext($file_name);
 3056:     my $new_answer;
 3057:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3058:     if($env{'form.copy'} eq '-1') {
 3059:         $new_answer = 'problem getting file';
 3060:     } else {
 3061:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3062:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3063:                             $stu_name,$domain,'copy',
 3064: 		        '/portfolio'.$directory.$new_answer);
 3065:     }    
 3066:     return ($new_answer);
 3067: }
 3068: 
 3069: sub file_name_version_ext {
 3070:     my ($file)=@_;
 3071:     my @file_parts = split(/\./, $file);
 3072:     my ($name,$version,$ext);
 3073:     if (@file_parts > 1) {
 3074: 	$ext=pop(@file_parts);
 3075: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3076: 	    $version=pop(@file_parts);
 3077: 	}
 3078: 	$name=join('.',@file_parts);
 3079:     } else {
 3080: 	$name=join('.',@file_parts);
 3081:     }
 3082:     return($name,$version,$ext);
 3083: }
 3084: 
 3085: #--------------------------------------------------------------------------------------
 3086: #
 3087: #-------------------------- Next few routines handles grading by section or whole class
 3088: #
 3089: #--- Javascript to handle grading by section or whole class
 3090: sub viewgrades_js {
 3091:     my ($request) = shift;
 3092: 
 3093:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3094:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
 3095:    function writePoint(partid,weight,point) {
 3096: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3097: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3098: 	if (point == "textval") {
 3099: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3100: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3101: 		alert("$alertmsg"+parseFloat(point));
 3102: 		var resetbox = false;
 3103: 		for (var i=0; i<radioButton.length; i++) {
 3104: 		    if (radioButton[i].checked) {
 3105: 			textbox.value = i;
 3106: 			resetbox = true;
 3107: 		    }
 3108: 		}
 3109: 		if (!resetbox) {
 3110: 		    textbox.value = "";
 3111: 		}
 3112: 		return;
 3113: 	    }
 3114: 	    if (parseFloat(point) > parseFloat(weight)) {
 3115: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3116: 				   ") greater than the weight for the part. Accept?");
 3117: 		if (resp == false) {
 3118: 		    textbox.value = "";
 3119: 		    return;
 3120: 		}
 3121: 	    }
 3122: 	    for (var i=0; i<radioButton.length; i++) {
 3123: 		radioButton[i].checked=false;
 3124: 		if (parseFloat(point) == i) {
 3125: 		    radioButton[i].checked=true;
 3126: 		}
 3127: 	    }
 3128: 
 3129: 	} else {
 3130: 	    textbox.value = parseFloat(point);
 3131: 	}
 3132: 	for (i=0;i<document.classgrade.total.value;i++) {
 3133: 	    var user = document.classgrade["ctr"+i].value;
 3134: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3135: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3136: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3137: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3138: 	    if (saveval != "correct") {
 3139: 		scorename.value = point;
 3140: 		if (selname[0].selected != true) {
 3141: 		    selname[0].selected = true;
 3142: 		}
 3143: 	    }
 3144: 	}
 3145: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3146:     }
 3147: 
 3148:     function writeRadText(partid,weight) {
 3149: 	var selval   = document.classgrade["SELVAL_"+partid];
 3150: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3151:         var override = document.classgrade["FORCE_"+partid].checked;
 3152: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3153: 	if (selval[1].selected || selval[2].selected) {
 3154: 	    for (var i=0; i<radioButton.length; i++) {
 3155: 		radioButton[i].checked=false;
 3156: 
 3157: 	    }
 3158: 	    textbox.value = "";
 3159: 
 3160: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3161: 		var user = document.classgrade["ctr"+i].value;
 3162: 		user = user.replace(new RegExp(':', 'g'),"_");
 3163: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3164: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3165: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3166: 		if ((saveval != "correct") || override) {
 3167: 		    scorename.value = "";
 3168: 		    if (selval[1].selected) {
 3169: 			selname[1].selected = true;
 3170: 		    } else {
 3171: 			selname[2].selected = true;
 3172: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3173: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3174: 		    }
 3175: 		}
 3176: 	    }
 3177: 	} else {
 3178: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3179: 		var user = document.classgrade["ctr"+i].value;
 3180: 		user = user.replace(new RegExp(':', 'g'),"_");
 3181: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3182: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3183: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3184: 		if ((saveval != "correct") || override) {
 3185: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3186: 		    selname[0].selected = true;
 3187: 		}
 3188: 	    }
 3189: 	}	    
 3190:     }
 3191: 
 3192:     function changeSelect(partid,user) {
 3193: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3194: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3195: 	var point  = textbox.value;
 3196: 	var weight = document.classgrade["weight_"+partid].value;
 3197: 
 3198: 	if (isNaN(point) || parseFloat(point) < 0) {
 3199: 	    alert("$alertmsg"+parseFloat(point));
 3200: 	    textbox.value = "";
 3201: 	    return;
 3202: 	}
 3203: 	if (parseFloat(point) > parseFloat(weight)) {
 3204: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3205: 			       ") greater than the weight of the part. Accept?");
 3206: 	    if (resp == false) {
 3207: 		textbox.value = "";
 3208: 		return;
 3209: 	    }
 3210: 	}
 3211: 	selval[0].selected = true;
 3212:     }
 3213: 
 3214:     function changeOneScore(partid,user) {
 3215: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3216: 	if (selval[1].selected || selval[2].selected) {
 3217: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3218: 	    if (selval[2].selected) {
 3219: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3220: 	    }
 3221:         }
 3222:     }
 3223: 
 3224:     function resetEntry(numpart) {
 3225: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3226: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3227: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3228: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3229: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3230: 	    for (var i=0; i<radioButton.length; i++) {
 3231: 		radioButton[i].checked=false;
 3232: 
 3233: 	    }
 3234: 	    textbox.value = "";
 3235: 	    selval[0].selected = true;
 3236: 
 3237: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3238: 		var user = document.classgrade["ctr"+i].value;
 3239: 		user = user.replace(new RegExp(':', 'g'),"_");
 3240: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3241: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3242: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3243: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3244: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3245: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3246: 		if (saveselval == "excused") {
 3247: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3248: 		} else {
 3249: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3250: 		}
 3251: 	    }
 3252: 	}
 3253:     }
 3254: 
 3255: VIEWJAVASCRIPT
 3256: }
 3257: 
 3258: #--- show scores for a section or whole class w/ option to change/update a score
 3259: sub viewgrades {
 3260:     my ($request,$symb) = @_;
 3261:     &viewgrades_js($request);
 3262: 
 3263:     #need to make sure we have the correct data for later EXT calls, 
 3264:     #thus invalidate the cache
 3265:     &Apache::lonnet::devalidatecourseresdata(
 3266:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3267:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3268:     &Apache::lonnet::clear_EXT_cache_status();
 3269: 
 3270:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3271: 
 3272:     #view individual student submission form - called using Javascript viewOneStudent
 3273:     $result.=&jscriptNform($symb);
 3274: 
 3275:     #beginning of class grading form
 3276:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3277:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3278: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3279: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3280: 	&build_section_inputs().
 3281: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3282: 
 3283:     my ($common_header,$specific_header);
 3284:     if ($env{'form.section'} eq 'all') {
 3285: 	$common_header = &mt('Assign Common Grade to Class');
 3286:         $specific_header = &mt('Assign Grade to Specific Students in Class');
 3287:     } elsif ($env{'form.section'} eq 'none') {
 3288:         $common_header = &mt('Assign Common Grade to Students in no Section');
 3289: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
 3290:     } else {
 3291:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3292:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3293: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3294:     }
 3295:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
 3296:     #radio buttons/text box for assigning points for a section or class.
 3297:     #handles different parts of a problem
 3298:     my $res_error;
 3299:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3300:     if ($res_error) {
 3301:         return &navmap_errormsg();
 3302:     }
 3303:     my %weight = ();
 3304:     my $ctsparts = 0;
 3305:     my %seen = ();
 3306:     my @part_response_id = &flatten_responseType($responseType);
 3307:     foreach my $part_response_id (@part_response_id) {
 3308:     	my ($partid,$respid) = @{ $part_response_id };
 3309: 	my $part_resp = join('_',@{ $part_response_id });
 3310: 	next if $seen{$partid};
 3311: 	$seen{$partid}++;
 3312: 	my $handgrade=$$handgrade{$part_resp};
 3313: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3314: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3315: 
 3316: 	my $display_part=&get_display_part($partid,$symb);
 3317: 	my $radio.='<table border="0"><tr>';  
 3318: 	my $ctr = 0;
 3319: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3320: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3321: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3322: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3323: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3324: 	    $ctr++;
 3325: 	}
 3326: 	$radio.='</tr></table>';
 3327: 	my $line = '<input type="text" name="TEXTVAL_'.
 3328: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 3329: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3330: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3331: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
 3332: 	    'onchange="javascript:writeRadText(\''.$partid.'\','.
 3333: 		$weight{$partid}.')"> '.
 3334: 	    '<option selected="selected"> </option>'.
 3335: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3336: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3337: 	    '</select></td>'.
 3338:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3339: 	$line.='<input type="hidden" name="partid_'.
 3340: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3341: 	$line.='<input type="hidden" name="weight_'.
 3342: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3343: 
 3344: 	$result.=
 3345: 	    &Apache::loncommon::start_data_table_row()."\n".
 3346: 	    '<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>'.
 3347: 	    &Apache::loncommon::end_data_table_row()."\n";
 3348: 	$ctsparts++;
 3349:     }
 3350:     $result.=&Apache::loncommon::end_data_table()."\n".
 3351: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3352:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3353: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 3354: 
 3355:     #table listing all the students in a section/class
 3356:     #header of table
 3357:     $result.= '<h3>'.$specific_header.'</h3>'.
 3358:               &Apache::loncommon::start_data_table().
 3359: 	      &Apache::loncommon::start_data_table_header_row().
 3360: 	      '<th>'.&mt('No.').'</th>'.
 3361: 	      '<th>'.&nameUserString('header')."</th>\n";
 3362:     my $partserror;
 3363:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3364:     if ($partserror) {
 3365:         return &navmap_errormsg();
 3366:     }
 3367:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3368:     my @partids = ();
 3369:     foreach my $part (@parts) {
 3370: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3371:         my $narrowtext = &mt('Tries');
 3372: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3373: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3374: 	my ($partid) = &split_part_type($part);
 3375:         push(@partids,$partid);
 3376: 	my $display_part=&get_display_part($partid,$symb);
 3377: 	if ($display =~ /^Partial Credit Factor/) {
 3378: 	    $result.='<th>'.
 3379: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
 3380: 		    $display_part,$weight{$partid}).'</th>'."\n";
 3381: 	    next;
 3382: 	    
 3383: 	} else {
 3384: 	    if ($display =~ /Problem Status/) {
 3385: 		my $grade_status_mt = &mt('Grade Status');
 3386: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3387: 	    }
 3388: 	    my $part_mt = &mt('Part:');
 3389: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3390: 	}
 3391: 
 3392: 	$result.='<th>'.$display.'</th>'."\n";
 3393:     }
 3394:     $result.=&Apache::loncommon::end_data_table_header_row();
 3395: 
 3396:     my %last_resets = 
 3397: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3398: 
 3399:     #get info for each student
 3400:     #list all the students - with points and grade status
 3401:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3402:     my $ctr = 0;
 3403:     foreach (sort 
 3404: 	     {
 3405: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3406: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3407: 		 }
 3408: 		 return $a cmp $b;
 3409: 	     } (keys(%$fullname))) {
 3410: 	$ctr++;
 3411: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3412: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3413:     }
 3414:     $result.=&Apache::loncommon::end_data_table();
 3415:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3416:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3417: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 3418:     if (scalar(%$fullname) eq 0) {
 3419: 	my $colspan=3+scalar(@parts);
 3420: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3421:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3422: 	$result='<span class="LC_warning">'.
 3423: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3424: 	        $section_display, $stu_status).
 3425: 	    '</span>';
 3426:     }
 3427:     return $result;
 3428: }
 3429: 
 3430: #--- call by previous routine to display each student
 3431: sub viewstudentgrade {
 3432:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3433:     my ($uname,$udom) = split(/:/,$student);
 3434:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3435:     my %aggregates = (); 
 3436:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3437: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3438: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3439: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3440: 	'\');" target="_self">'.$fullname.'</a> '.
 3441: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3442:     $student=~s/:/_/; # colon doen't work in javascript for names
 3443:     foreach my $apart (@$parts) {
 3444: 	my ($part,$type) = &split_part_type($apart);
 3445: 	my $score=$record{"resource.$part.$type"};
 3446:         $result.='<td align="center">';
 3447:         my ($aggtries,$totaltries);
 3448:         unless (exists($aggregates{$part})) {
 3449: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3450: 
 3451: 	    $aggtries = $totaltries;
 3452:             if ($$last_resets{$part}) {  
 3453:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3454: 					   $part);
 3455:             }
 3456:             $result.='<input type="hidden" name="'.
 3457:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3458:             $result.='<input type="hidden" name="'.
 3459:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3460:             $aggregates{$part} = 1;
 3461:         }
 3462: 	if ($type eq 'awarded') {
 3463: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3464: 	    $result.='<input type="hidden" name="'.
 3465: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3466: 	    $result.='<input type="text" name="'.
 3467: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3468:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3469: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3470: 	} elsif ($type eq 'solved') {
 3471: 	    my ($status,$foo)=split(/_/,$score,2);
 3472: 	    $status = 'nothing' if ($status eq '');
 3473: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3474: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3475: 	    $result.='&nbsp;<select name="'.
 3476: 		'GD_'.$student.'_'.$part.'_solved" '.
 3477:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3478: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3479: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3480: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3481: 	    $result.="</select>&nbsp;</td>\n";
 3482: 	} else {
 3483: 	    $result.='<input type="hidden" name="'.
 3484: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3485: 		    "\n";
 3486: 	    $result.='<input type="text" name="'.
 3487: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3488: 		'value="'.$score.'" size="4" /></td>'."\n";
 3489: 	}
 3490:     }
 3491:     $result.=&Apache::loncommon::end_data_table_row();
 3492:     return $result;
 3493: }
 3494: 
 3495: #--- change scores for all the students in a section/class
 3496: #    record does not get update if unchanged
 3497: sub editgrades {
 3498:     my ($request,$symb) = @_;
 3499: 
 3500:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3501:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3502:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3503: 
 3504:     my $result= &Apache::loncommon::start_data_table().
 3505: 	&Apache::loncommon::start_data_table_header_row().
 3506: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3507: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3508:     my %scoreptr = (
 3509: 		    'correct'  =>'correct_by_override',
 3510: 		    'incorrect'=>'incorrect_by_override',
 3511: 		    'excused'  =>'excused',
 3512: 		    'ungraded' =>'ungraded_attempted',
 3513:                     'credited' =>'credit_attempted',
 3514: 		    'nothing'  => '',
 3515: 		    );
 3516:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3517: 
 3518:     my (@partid);
 3519:     my %weight = ();
 3520:     my %columns = ();
 3521:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3522: 
 3523:     my $partserror;
 3524:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3525:     if ($partserror) {
 3526:         return &navmap_errormsg();
 3527:     }
 3528:     my $header;
 3529:     while ($ctr < $env{'form.totalparts'}) {
 3530: 	my $partid = $env{'form.partid_'.$ctr};
 3531: 	push(@partid,$partid);
 3532: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3533: 	$ctr++;
 3534:     }
 3535:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3536:     foreach my $partid (@partid) {
 3537: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3538: 	    '<th align="center">'.&mt('New Score').'</th>';
 3539: 	$columns{$partid}=2;
 3540: 	foreach my $stores (@parts) {
 3541: 	    my ($part,$type) = &split_part_type($stores);
 3542: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3543: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3544: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3545: 	    $display =~ s/\[Part: \Q$part\E\]//;
 3546:             my $narrowtext = &mt('Tries');
 3547: 	    $display =~ s/Number of Attempts/$narrowtext/;
 3548: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 3549: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 3550: 	    $columns{$partid}+=2;
 3551: 	}
 3552:     }
 3553:     foreach my $partid (@partid) {
 3554: 	my $display_part=&get_display_part($partid,$symb);
 3555: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3556: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3557: 	    '</th>';
 3558: 
 3559:     }
 3560:     $result .= &Apache::loncommon::end_data_table_header_row().
 3561: 	&Apache::loncommon::start_data_table_header_row().
 3562: 	$header.
 3563: 	&Apache::loncommon::end_data_table_header_row();
 3564:     my @noupdate;
 3565:     my ($updateCtr,$noupdateCtr) = (1,1);
 3566:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3567: 	my $line;
 3568: 	my $user = $env{'form.ctr'.$i};
 3569: 	my ($uname,$udom)=split(/:/,$user);
 3570: 	my %newrecord;
 3571: 	my $updateflag = 0;
 3572: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3573: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3574: 	if (!&canmodify($usec)) {
 3575: 	    my $numcols=scalar(@partid)*4+2;
 3576: 	    push(@noupdate,
 3577: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 3578: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 3579: 	    next;
 3580: 	}
 3581:         my %aggregate = ();
 3582:         my $aggregateflag = 0;
 3583: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3584: 	foreach (@partid) {
 3585: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3586: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3587: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3588: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3589: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3590: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3591: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3592: 	    my $score;
 3593: 	    if ($partial eq '') {
 3594: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3595: 	    } elsif ($partial > 0) {
 3596: 		$score = 'correct_by_override';
 3597: 	    } elsif ($partial == 0) {
 3598: 		$score = 'incorrect_by_override';
 3599: 	    }
 3600: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3601: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3602: 
 3603: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3604: 		"$env{'user.name'}:$env{'user.domain'}";
 3605: 	    if ($dropMenu eq 'reset status' &&
 3606: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3607: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3608: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3609: 		$newrecord{'resource.'.$_.'.award'} = '';
 3610: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3611: 		$updateflag = 1;
 3612:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3613:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3614:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3615:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3616:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3617:                     $aggregateflag = 1;
 3618:                 }
 3619: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3620: 		$updateflag = 1;
 3621: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3622: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3623: 		$rec_update++;
 3624: 	    }
 3625: 
 3626: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3627: 		'<td align="center">'.$awarded.
 3628: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3629: 
 3630: 
 3631: 	    my $partid=$_;
 3632: 	    foreach my $stores (@parts) {
 3633: 		my ($part,$type) = &split_part_type($stores);
 3634: 		if ($part !~ m/^\Q$partid\E/) { next;}
 3635: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 3636: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 3637: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 3638: 		if ($awarded ne '' && $awarded ne $old_aw) {
 3639: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 3640: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3641: 		    $updateflag=1;
 3642: 		}
 3643: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3644: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 3645: 	    }
 3646: 	}
 3647: 	$line.="\n";
 3648: 
 3649: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3650: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3651: 
 3652: 	if ($updateflag) {
 3653: 	    $count++;
 3654: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 3655: 				    $udom,$uname);
 3656: 
 3657: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 3658: 					      $cnum,$udom,$uname)) {
 3659: 		# need to figure out if should be in queue.
 3660: 		my %record =  
 3661: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3662: 					     $udom,$uname);
 3663: 		my $all_graded = 1;
 3664: 		my $none_graded = 1;
 3665: 		foreach my $part (@parts) {
 3666: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 3667: 			$all_graded = 0;
 3668: 		    } else {
 3669: 			$none_graded = 0;
 3670: 		    }
 3671: 		}
 3672: 
 3673: 		if ($all_graded || $none_graded) {
 3674: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 3675: 							   $symb,$cdom,$cnum,
 3676: 							   $udom,$uname);
 3677: 		}
 3678: 	    }
 3679: 
 3680: 	    $result.=&Apache::loncommon::start_data_table_row().
 3681: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 3682: 		&Apache::loncommon::end_data_table_row();
 3683: 	    $updateCtr++;
 3684: 	} else {
 3685: 	    push(@noupdate,
 3686: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 3687: 	    $noupdateCtr++;
 3688: 	}
 3689:         if ($aggregateflag) {
 3690:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3691: 				  $cdom,$cnum);
 3692:         }
 3693:     }
 3694:     if (@noupdate) {
 3695: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 3696: 	my $numcols=scalar(@partid)*4+2;
 3697: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 3698: 	    '<td align="center" colspan="'.$numcols.'">'.
 3699: 	    &mt('No Changes Occurred For the Students Below').
 3700: 	    '</td>'.
 3701: 	    &Apache::loncommon::end_data_table_row();
 3702: 	foreach my $line (@noupdate) {
 3703: 	    $result.=
 3704: 		&Apache::loncommon::start_data_table_row().
 3705: 		$line.
 3706: 		&Apache::loncommon::end_data_table_row();
 3707: 	}
 3708:     }
 3709:     $result .= &Apache::loncommon::end_data_table();
 3710:     my $msg = '<p><b>'.
 3711: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 3712: 	    $rec_update,$count).'</b><br />'.
 3713: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 3714: 	'</b></p>';
 3715:     return $title.$msg.$result;
 3716: }
 3717: 
 3718: sub split_part_type {
 3719:     my ($partstr) = @_;
 3720:     my ($temp,@allparts)=split(/_/,$partstr);
 3721:     my $type=pop(@allparts);
 3722:     my $part=join('_',@allparts);
 3723:     return ($part,$type);
 3724: }
 3725: 
 3726: #------------- end of section for handling grading by section/class ---------
 3727: #
 3728: #----------------------------------------------------------------------------
 3729: 
 3730: 
 3731: #----------------------------------------------------------------------------
 3732: #
 3733: #-------------------------- Next few routines handles grading by csv upload
 3734: #
 3735: #--- Javascript to handle csv upload
 3736: sub csvupload_javascript_reverse_associate {
 3737:     my $error1=&mt('You need to specify the username or the student/employee ID');
 3738:     my $error2=&mt('You need to specify at least one grading field');
 3739:   return(<<ENDPICK);
 3740:   function verify(vf) {
 3741:     var foundsomething=0;
 3742:     var founduname=0;
 3743:     var foundID=0;
 3744:     for (i=0;i<=vf.nfields.value;i++) {
 3745:       tw=eval('vf.f'+i+'.selectedIndex');
 3746:       if (i==0 && tw!=0) { foundID=1; }
 3747:       if (i==1 && tw!=0) { founduname=1; }
 3748:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 3749:     }
 3750:     if (founduname==0 && foundID==0) {
 3751: 	alert('$error1');
 3752: 	return;
 3753:     }
 3754:     if (foundsomething==0) {
 3755: 	alert('$error2');
 3756: 	return;
 3757:     }
 3758:     vf.submit();
 3759:   }
 3760:   function flip(vf,tf) {
 3761:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3762:     var i;
 3763:     for (i=0;i<=vf.nfields.value;i++) {
 3764:       //can not pick the same destination field for both name and domain
 3765:       if (((i ==0)||(i ==1)) && 
 3766:           ((tf==0)||(tf==1)) && 
 3767:           (i!=tf) &&
 3768:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3769:         eval('vf.f'+i+'.selectedIndex=0;')
 3770:       }
 3771:     }
 3772:   }
 3773: ENDPICK
 3774: }
 3775: 
 3776: sub csvupload_javascript_forward_associate {
 3777:     my $error1=&mt('You need to specify the username or the student/employee ID');
 3778:     my $error2=&mt('You need to specify at least one grading field');
 3779:   return(<<ENDPICK);
 3780:   function verify(vf) {
 3781:     var foundsomething=0;
 3782:     var founduname=0;
 3783:     var foundID=0;
 3784:     for (i=0;i<=vf.nfields.value;i++) {
 3785:       tw=eval('vf.f'+i+'.selectedIndex');
 3786:       if (tw==1) { foundID=1; }
 3787:       if (tw==2) { founduname=1; }
 3788:       if (tw>3) { foundsomething=1; }
 3789:     }
 3790:     if (founduname==0 && foundID==0) {
 3791: 	alert('$error1');
 3792: 	return;
 3793:     }
 3794:     if (foundsomething==0) {
 3795: 	alert('$error2');
 3796: 	return;
 3797:     }
 3798:     vf.submit();
 3799:   }
 3800:   function flip(vf,tf) {
 3801:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3802:     var i;
 3803:     //can not pick the same destination field twice
 3804:     for (i=0;i<=vf.nfields.value;i++) {
 3805:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3806:         eval('vf.f'+i+'.selectedIndex=0;')
 3807:       }
 3808:     }
 3809:   }
 3810: ENDPICK
 3811: }
 3812: 
 3813: sub csvuploadmap_header {
 3814:     my ($request,$symb,$datatoken,$distotal)= @_;
 3815:     my $javascript;
 3816:     if ($env{'form.upfile_associate'} eq 'reverse') {
 3817: 	$javascript=&csvupload_javascript_reverse_associate();
 3818:     } else {
 3819: 	$javascript=&csvupload_javascript_forward_associate();
 3820:     }
 3821: 
 3822:     my $result='';
 3823:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 3824:     my $ignore=&mt('Ignore First Line');
 3825:     $symb = &Apache::lonenc::check_encrypt($symb);
 3826:     $request->print(<<ENDPICK);
 3827: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3828: <h3><span class="LC_info">Uploading Class Grades</span></h3>
 3829: $result
 3830: <hr />
 3831: <h3>Identify fields</h3>
 3832: Total number of records found in file: $distotal <hr />
 3833: Enter as many fields as you can. The system will inform you and bring you back
 3834: to this page if the data selected is insufficient to run your class.<hr />
 3835: <input type="button" value="Reverse Association" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 3836: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 3837: <input type="hidden" name="associate"  value="" />
 3838: <input type="hidden" name="phase"      value="three" />
 3839: <input type="hidden" name="datatoken"  value="$datatoken" />
 3840: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 3841: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 3842: <input type="hidden" name="upfile_associate" 
 3843:                                        value="$env{'form.upfile_associate'}" />
 3844: <input type="hidden" name="symb"       value="$symb" />
 3845: <input type="hidden" name="command"    value="csvuploadoptions" />
 3846: <hr />
 3847: ENDPICK
 3848:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
 3849:     return '';
 3850: 
 3851: }
 3852: 
 3853: sub csvupload_fields {
 3854:     my ($symb,$errorref) = @_;
 3855:     my (@parts) = &getpartlist($symb,$errorref);
 3856:     if (ref($errorref)) {
 3857:         if ($$errorref) {
 3858:             return;
 3859:         }
 3860:     }
 3861: 
 3862:     my @fields=(['ID','Student/Employee ID'],
 3863: 		['username','Student Username'],
 3864: 		['domain','Student Domain']);
 3865:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3866:     foreach my $part (sort(@parts)) {
 3867: 	my @datum;
 3868: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3869: 	my $name=$part;
 3870: 	if  (!$display) { $display = $name; }
 3871: 	@datum=($name,$display);
 3872: 	if ($name=~/^stores_(.*)_awarded/) {
 3873: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 3874: 	}
 3875: 	push(@fields,\@datum);
 3876:     }
 3877:     return (@fields);
 3878: }
 3879: 
 3880: sub csvuploadmap_footer {
 3881:     my ($request,$i,$keyfields) =@_;
 3882:     $request->print(<<ENDPICK);
 3883: </table>
 3884: <input type="hidden" name="nfields" value="$i" />
 3885: <input type="hidden" name="keyfields" value="$keyfields" />
 3886: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
 3887: </form>
 3888: ENDPICK
 3889: }
 3890: 
 3891: sub checkforfile_js {
 3892:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 3893:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
 3894:     function checkUpload(formname) {
 3895: 	if (formname.upfile.value == "") {
 3896: 	    alert("$alertmsg");
 3897: 	    return false;
 3898: 	}
 3899: 	formname.submit();
 3900:     }
 3901: CSVFORMJS
 3902:     return $result;
 3903: }
 3904: 
 3905: sub upcsvScores_form {
 3906:     my ($request,$symb) = @_;
 3907:     if (!$symb) {return '';}
 3908:     my $result=&checkforfile_js();
 3909:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 3910:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 3911:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
 3912: 	'</b></td></tr>'."\n";
 3913:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 3914:     my $upload=&mt("Upload Scores");
 3915:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 3916:     my $ignore=&mt('Ignore First Line');
 3917:     $symb = &Apache::lonenc::check_encrypt($symb);
 3918:     $result.=<<ENDUPFORM;
 3919: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3920: <input type="hidden" name="symb" value="$symb" />
 3921: <input type="hidden" name="command" value="csvuploadmap" />
 3922: $upfile_select
 3923: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 3924: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 3925: </form>
 3926: ENDUPFORM
 3927:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 3928:                            &mt("How do I create a CSV file from a spreadsheet"))
 3929:     .'</td></tr></table>'."\n";
 3930:     $result.='</td></tr></table><br /><br />'."\n";
 3931:     return $result;
 3932: }
 3933: 
 3934: 
 3935: sub csvuploadmap {
 3936:     my ($request,$symb)= @_;
 3937:     if (!$symb) {return '';}
 3938: 
 3939:     my $datatoken;
 3940:     if (!$env{'form.datatoken'}) {
 3941: 	$datatoken=&Apache::loncommon::upfile_store($request);
 3942:     } else {
 3943: 	$datatoken=$env{'form.datatoken'};
 3944: 	&Apache::loncommon::load_tmp_file($request);
 3945:     }
 3946:     my @records=&Apache::loncommon::upfile_record_sep();
 3947:     if ($env{'form.noFirstLine'}) { shift(@records); }
 3948:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 3949:     my ($i,$keyfields);
 3950:     if (@records) {
 3951:         my $fieldserror;
 3952: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 3953:         if ($fieldserror) {
 3954:             $request->print(&navmap_errormsg());
 3955:             return;
 3956:         }
 3957: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 3958: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 3959: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 3960: 							  \@fields);
 3961: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 3962: 	    chop($keyfields);
 3963: 	} else {
 3964: 	    unshift(@fields,['none','']);
 3965: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 3966: 							    \@fields);
 3967:             foreach my $rec (@records) {
 3968:                 my %temp = &Apache::loncommon::record_sep($rec);
 3969:                 if (%temp) {
 3970:                     $keyfields=join(',',sort(keys(%temp)));
 3971:                     last;
 3972:                 }
 3973:             }
 3974: 	}
 3975:     }
 3976:     &csvuploadmap_footer($request,$i,$keyfields);
 3977: 
 3978:     return '';
 3979: }
 3980: 
 3981: sub csvuploadoptions {
 3982:     my ($request,$symb)= @_;
 3983:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 3984:     my $ignore=&mt('Ignore First Line');
 3985:     $request->print(<<ENDPICK);
 3986: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3987: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
 3988: <input type="hidden" name="command"    value="csvuploadassign" />
 3989: <!--
 3990: <p>
 3991: <label>
 3992:    <input type="checkbox" name="show_full_results" />
 3993:    Show a table of all changes
 3994: </label>
 3995: </p>
 3996: -->
 3997: <p>
 3998: <label>
 3999:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4000:    Overwrite any existing score
 4001: </label>
 4002: </p>
 4003: ENDPICK
 4004:     my %fields=&get_fields();
 4005:     if (!defined($fields{'domain'})) {
 4006: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4007: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
 4008:     }
 4009:     foreach my $key (sort(keys(%env))) {
 4010: 	if ($key !~ /^form\.(.*)$/) { next; }
 4011: 	my $cleankey=$1;
 4012: 	if ($cleankey eq 'command') { next; }
 4013: 	$request->print('<input type="hidden" name="'.$cleankey.
 4014: 			'"  value="'.$env{$key}.'" />'."\n");
 4015:     }
 4016:     # FIXME do a check for any duplicated user ids...
 4017:     # FIXME do a check for any invalid user ids?...
 4018:     $request->print('<input type="submit" value="Assign Grades" /><br />
 4019: <hr /></form>'."\n");
 4020:     return '';
 4021: }
 4022: 
 4023: sub get_fields {
 4024:     my %fields;
 4025:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4026:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4027: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4028: 	    if ($env{'form.f'.$i} ne 'none') {
 4029: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4030: 	    }
 4031: 	} else {
 4032: 	    if ($env{'form.f'.$i} ne 'none') {
 4033: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4034: 	    }
 4035: 	}
 4036:     }
 4037:     return %fields;
 4038: }
 4039: 
 4040: sub csvuploadassign {
 4041:     my ($request,$symb)= @_;
 4042:     if (!$symb) {return '';}
 4043:     my $error_msg = '';
 4044:     &Apache::loncommon::load_tmp_file($request);
 4045:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4046:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 4047:     my %fields=&get_fields();
 4048:     $request->print('<h3>Assigning Grades</h3>');
 4049:     my $courseid=$env{'request.course.id'};
 4050:     my ($classlist) = &getclasslist('all',0);
 4051:     my @notallowed;
 4052:     my @skipped;
 4053:     my $countdone=0;
 4054:     foreach my $grade (@gradedata) {
 4055: 	my %entries=&Apache::loncommon::record_sep($grade);
 4056: 	my $domain;
 4057: 	if ($entries{$fields{'domain'}}) {
 4058: 	    $domain=$entries{$fields{'domain'}};
 4059: 	} else {
 4060: 	    $domain=$env{'form.default_domain'};
 4061: 	}
 4062: 	$domain=~s/\s//g;
 4063: 	my $username=$entries{$fields{'username'}};
 4064: 	$username=~s/\s//g;
 4065: 	if (!$username) {
 4066: 	    my $id=$entries{$fields{'ID'}};
 4067: 	    $id=~s/\s//g;
 4068: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4069: 	    $username=$ids{$id};
 4070: 	}
 4071: 	if (!exists($$classlist{"$username:$domain"})) {
 4072: 	    my $id=$entries{$fields{'ID'}};
 4073: 	    $id=~s/\s//g;
 4074: 	    if ($id) {
 4075: 		push(@skipped,"$id:$domain");
 4076: 	    } else {
 4077: 		push(@skipped,"$username:$domain");
 4078: 	    }
 4079: 	    next;
 4080: 	}
 4081: 	my $usec=$classlist->{"$username:$domain"}[5];
 4082: 	if (!&canmodify($usec)) {
 4083: 	    push(@notallowed,"$username:$domain");
 4084: 	    next;
 4085: 	}
 4086: 	my %points;
 4087: 	my %grades;
 4088: 	foreach my $dest (keys(%fields)) {
 4089: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4090: 		$dest eq 'domain') { next; }
 4091: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4092: 	    if ($dest=~/stores_(.*)_points/) {
 4093: 		my $part=$1;
 4094: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4095: 					      $symb,$domain,$username);
 4096:                 if ($wgt) {
 4097:                     $entries{$fields{$dest}}=~s/\s//g;
 4098:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4099:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4100:                                           : 'correct_by_override';
 4101:                     $grades{"resource.$part.awarded"}=$pcr;
 4102:                     $grades{"resource.$part.solved"}=$award;
 4103:                     $points{$part}=1;
 4104:                 } else {
 4105:                     $error_msg = "<br />" .
 4106:                         &mt("Some point values were assigned"
 4107:                             ." for problems with a weight "
 4108:                             ."of zero. These values were "
 4109:                             ."ignored.");
 4110:                 }
 4111: 	    } else {
 4112: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4113: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4114: 		my $store_key=$dest;
 4115: 		$store_key=~s/^stores/resource/;
 4116: 		$store_key=~s/_/\./g;
 4117: 		$grades{$store_key}=$entries{$fields{$dest}};
 4118: 	    }
 4119: 	}
 4120: 	if (! %grades) { 
 4121:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4122:         } else {
 4123: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4124: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4125: 					   $env{'request.course.id'},
 4126: 					   $domain,$username);
 4127: 	   if ($result eq 'ok') {
 4128: 	      $request->print('.');
 4129: 	   } else {
 4130: 	      $request->print("<p><span class=\"LC_error\">".
 4131:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4132:                                   "$username:$domain",$result)."</span></p>");
 4133: 	   }
 4134: 	   $request->rflush();
 4135: 	   $countdone++;
 4136:         }
 4137:     }
 4138:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 4139:     if (@skipped) {
 4140: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 4141:         $request->print(join(', ',@skipped));
 4142:     }
 4143:     if (@notallowed) {
 4144: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 4145: 	$request->print(join(', ',@notallowed));
 4146:     }
 4147:     $request->print("<br />\n");
 4148:     return $error_msg;
 4149: }
 4150: #------------- end of section for handling csv file upload ---------
 4151: #
 4152: #-------------------------------------------------------------------
 4153: #
 4154: #-------------- Next few routines handle grading by page/sequence
 4155: #
 4156: #--- Select a page/sequence and a student to grade
 4157: sub pickStudentPage {
 4158:     my ($request,$symb) = @_;
 4159: 
 4160:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4161:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
 4162: 
 4163: function checkPickOne(formname) {
 4164:     if (radioSelection(formname.student) == null) {
 4165: 	alert("$alertmsg");
 4166: 	return;
 4167:     }
 4168:     ptr = pullDownSelection(formname.selectpage);
 4169:     formname.page.value = formname["page"+ptr].value;
 4170:     formname.title.value = formname["title"+ptr].value;
 4171:     formname.submit();
 4172: }
 4173: 
 4174: LISTJAVASCRIPT
 4175:     &commonJSfunctions($request);
 4176: 
 4177:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4178:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4179:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4180: 
 4181:     my $result='<h3><span class="LC_info">&nbsp;'.
 4182: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4183: 
 4184:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4185:     my $map_error;
 4186:     my ($titles,$symbx) = &getSymbMap($map_error);
 4187:     if ($map_error) {
 4188:         $request->print(&navmap_errormsg());
 4189:         return; 
 4190:     }
 4191:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4192: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4193: #    my $type=($curpage =~ /\.(page|sequence)/);
 4194:     my $select = '<select name="selectpage">'."\n";
 4195:     my $ctr=0;
 4196:     foreach (@$titles) {
 4197: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4198: 	$select.='<option value="'.$ctr.'" '.
 4199: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4200: 	    '>'.$showtitle.'</option>'."\n";
 4201: 	$ctr++;
 4202:     }
 4203:     $select.= '</select>';
 4204:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
 4205: 
 4206:     $ctr=0;
 4207:     foreach (@$titles) {
 4208: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4209: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4210: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4211: 	$ctr++;
 4212:     }
 4213:     $result.='<input type="hidden" name="page" />'."\n".
 4214: 	'<input type="hidden" name="title" />'."\n";
 4215: 
 4216:     my $options =
 4217: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
 4218: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
 4219:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
 4220: 
 4221:     $options =
 4222: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
 4223: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
 4224: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
 4225:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
 4226:     
 4227:     $result.=&build_section_inputs();
 4228:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4229:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4230: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4231: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."<br />\n";
 4232: 
 4233:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
 4234: 
 4235:     $result.='&nbsp;<input type="button" '.
 4236:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4237: 
 4238:     $request->print($result);
 4239: 
 4240:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4241: 	&Apache::loncommon::start_data_table().
 4242: 	&Apache::loncommon::start_data_table_header_row().
 4243: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4244: 	'<th>'.&nameUserString('header').'</th>'.
 4245: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4246: 	'<th>'.&nameUserString('header').'</th>'.
 4247: 	&Apache::loncommon::end_data_table_header_row();
 4248:  
 4249:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4250:     my $ptr = 1;
 4251:     foreach my $student (sort 
 4252: 			 {
 4253: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4254: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4255: 			     }
 4256: 			     return $a cmp $b;
 4257: 			 } (keys(%$fullname))) {
 4258: 	my ($uname,$udom) = split(/:/,$student);
 4259: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4260:                                   : '</td>');
 4261: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4262: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4263: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4264: 	$studentTable.=
 4265: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4266:                          : '');
 4267: 	$ptr++;
 4268:     }
 4269:     if ($ptr%2 == 0) {
 4270: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4271: 	    &Apache::loncommon::end_data_table_row();
 4272:     }
 4273:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4274:     $studentTable.='<input type="button" '.
 4275:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4276: 
 4277:     $request->print($studentTable);
 4278: 
 4279:     return '';
 4280: }
 4281: 
 4282: sub getSymbMap {
 4283:     my ($map_error) = @_;
 4284:     my $navmap = Apache::lonnavmaps::navmap->new();
 4285:     unless (ref($navmap)) {
 4286:         if (ref($map_error)) {
 4287:             $$map_error = 'navmap';
 4288:         }
 4289:         return;
 4290:     }
 4291:     my %symbx = ();
 4292:     my @titles = ();
 4293:     my $minder = 0;
 4294: 
 4295:     # Gather every sequence that has problems.
 4296:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4297: 					       1,0,1);
 4298:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4299: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4300: 	    my $title = $minder.'.'.
 4301: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4302: 	    push(@titles, $title); # minder in case two titles are identical
 4303: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4304: 	    $minder++;
 4305: 	}
 4306:     }
 4307:     return \@titles,\%symbx;
 4308: }
 4309: 
 4310: #
 4311: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4312: sub displayPage {
 4313:     my ($request,$symb) = @_;
 4314:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4315:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4316:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4317:     my $pageTitle = $env{'form.page'};
 4318:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4319:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4320:     my $usec=$classlist->{$env{'form.student'}}[5];
 4321: 
 4322:     #need to make sure we have the correct data for later EXT calls, 
 4323:     #thus invalidate the cache
 4324:     &Apache::lonnet::devalidatecourseresdata(
 4325:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4326:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4327:     &Apache::lonnet::clear_EXT_cache_status();
 4328: 
 4329:     if (!&canview($usec)) {
 4330: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
 4331: 	return;
 4332:     }
 4333:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4334:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4335: 	'</h3>'."\n";
 4336:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4337:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4338: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4339:     } else {
 4340: 	delete($env{'form.CODE'});
 4341:     }
 4342:     &sub_page_js($request);
 4343:     $request->print($result);
 4344: 
 4345:     my $navmap = Apache::lonnavmaps::navmap->new();
 4346:     unless (ref($navmap)) {
 4347:         $request->print(&navmap_errormsg());
 4348:         return;
 4349:     }
 4350:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4351:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4352:     if (!$map) {
 4353: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4354: 	return; 
 4355:     }
 4356:     my $iterator = $navmap->getIterator($map->map_start(),
 4357: 					$map->map_finish());
 4358: 
 4359:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4360: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4361: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4362: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4363: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4364: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4365: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4366: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
 4367: 
 4368:     if (defined($env{'form.CODE'})) {
 4369: 	$studentTable.=
 4370: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4371:     }
 4372:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4373: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4374: 
 4375:     $studentTable.='&nbsp;<span class="LC_info">'.
 4376:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 4377:         '</span>'."\n".
 4378: 	&Apache::loncommon::start_data_table().
 4379: 	&Apache::loncommon::start_data_table_header_row().
 4380: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
 4381: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4382: 	&Apache::loncommon::end_data_table_header_row();
 4383: 
 4384:     &Apache::lonxml::clear_problem_counter();
 4385:     my ($depth,$question,$prob) = (1,1,1);
 4386:     $iterator->next(); # skip the first BEGIN_MAP
 4387:     my $curRes = $iterator->next(); # for "current resource"
 4388:     while ($depth > 0) {
 4389:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4390:         if($curRes == $iterator->END_MAP) { $depth--; }
 4391: 
 4392:         if (ref($curRes) && $curRes->is_problem()) {
 4393: 	    my $parts = $curRes->parts();
 4394:             my $title = $curRes->compTitle();
 4395: 	    my $symbx = $curRes->symb();
 4396: 	    $studentTable.=
 4397: 		&Apache::loncommon::start_data_table_row().
 4398: 		'<td align="center" valign="top" >'.$prob.
 4399: 		(scalar(@{$parts}) == 1 ? '' 
 4400: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
 4401: 							scalar(@{$parts}))
 4402: 		 ).
 4403: 		 '</td>';
 4404: 	    $studentTable.='<td valign="top">';
 4405: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4406: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4407: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4408: 					     undef,'both',\%form);
 4409: 	    } else {
 4410: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4411: 		$companswer =~ s|<form(.*?)>||g;
 4412: 		$companswer =~ s|</form>||g;
 4413: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4414: #		    $companswer =~ s/$1/ /ms;
 4415: #		    $request->print('match='.$1."<br />\n");
 4416: #		}
 4417: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4418: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 4419: 	    }
 4420: 
 4421: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4422: 
 4423: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4424: 		if ($record{'version'} eq '') {
 4425: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4426: 		} else {
 4427: 		    my %responseType = ();
 4428: 		    foreach my $partid (@{$parts}) {
 4429: 			my @responseIds =$curRes->responseIds($partid);
 4430: 			my @responseType =$curRes->responseType($partid);
 4431: 			my %responseIds;
 4432: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4433: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4434: 			}
 4435: 			$responseType{$partid} = \%responseIds;
 4436: 		    }
 4437: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4438: 
 4439: 		}
 4440: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4441: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4442: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4443: 									$env{'request.course.id'},
 4444: 									'','.submission');
 4445:  
 4446: 	    }
 4447: 	    if (&canmodify($usec)) {
 4448:             $studentTable.=&gradeBox_start();
 4449: 		foreach my $partid (@{$parts}) {
 4450: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4451: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4452: 		    $question++;
 4453: 		}
 4454:             $studentTable.=&gradeBox_end();
 4455: 		$prob++;
 4456: 	    }
 4457: 	    $studentTable.='</td></tr>';
 4458: 
 4459: 	}
 4460:         $curRes = $iterator->next();
 4461:     }
 4462: 
 4463:     $studentTable.=
 4464:         '</table>'."\n".
 4465:         '<input type="button" value="'.&mt('Save').'" '.
 4466:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4467:         '</form>'."\n";
 4468:     $request->print($studentTable);
 4469: 
 4470:     return '';
 4471: }
 4472: 
 4473: sub displaySubByDates {
 4474:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4475:     my $isCODE=0;
 4476:     my $isTask = ($symb =~/\.task$/);
 4477:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4478:     my $studentTable=&Apache::loncommon::start_data_table().
 4479: 	&Apache::loncommon::start_data_table_header_row().
 4480: 	'<th>'.&mt('Date/Time').'</th>'.
 4481: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4482: 	'<th>'.&mt('Submission').'</th>'.
 4483: 	'<th>'.&mt('Status').'</th>'.
 4484: 	&Apache::loncommon::end_data_table_header_row();
 4485:     my ($version);
 4486:     my %mark;
 4487:     my %orders;
 4488:     $mark{'correct_by_student'} = $checkIcon;
 4489:     if (!exists($$record{'1:timestamp'})) {
 4490: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 4491:     }
 4492: 
 4493:     my $interaction;
 4494:     my $no_increment = 1;
 4495:     for ($version=1;$version<=$$record{'version'};$version++) {
 4496: 	my $timestamp = 
 4497: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4498: 	if (exists($$record{$version.':resource.0.version'})) {
 4499: 	    $interaction = $$record{$version.':resource.0.version'};
 4500: 	}
 4501: 
 4502: 	my $where = ($isTask ? "$version:resource.$interaction"
 4503: 		             : "$version:resource");
 4504: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4505: 	    '<td>'.$timestamp.'</td>';
 4506: 	if ($isCODE) {
 4507: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4508: 	}
 4509: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4510: 	my @displaySub = ();
 4511: 	foreach my $partid (@{$parts}) {
 4512:             my $hidden;
 4513:             if (($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurvey') ||
 4514:                 ($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurveycred')) {
 4515:                 $hidden = 1;
 4516:             }
 4517: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4518: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4519: 	    
 4520: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4521: 	    my $display_part=&get_display_part($partid,$symb);
 4522: 	    foreach my $matchKey (@matchKey) {
 4523: 		if (exists($$record{$version.':'.$matchKey}) &&
 4524: 		    $$record{$version.':'.$matchKey} ne '') {
 4525:                     
 4526: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4527: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4528:                     $displaySub[0].='<span class="LC_nobreak"';
 4529:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 4530:                                    .' <span class="LC_internal_info">'
 4531:                                    .'('.&mt('Part ID: [_1]',$responseId).')'
 4532:                                    .'</span>'
 4533:                                    .' <b>';
 4534:                     if ($hidden) {
 4535:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
 4536:                     } else {
 4537: 		        if ($$record{"$where.$partid.tries"} eq '') {
 4538: 			    $displaySub[0].=&mt('Trial not counted');
 4539: 		        } else {
 4540: 			    $displaySub[0].=&mt('Trial: [_1]',
 4541: 					    $$record{"$where.$partid.tries"});
 4542: 		        }
 4543: 		        my $responseType=($isTask ? 'Task'
 4544:                                               : $responseType->{$partid}->{$responseId});
 4545: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4546: 		        if (!exists($orders{$partid}->{$responseId})) {
 4547: 			    $orders{$partid}->{$responseId}=
 4548: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
 4549:                                            $no_increment);
 4550: 		        }
 4551: 		        $displaySub[0].='</b></span>'; # /nobreak
 4552: 		        $displaySub[0].='&nbsp; '.
 4553: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
 4554:                     }
 4555: 		}
 4556: 	    }
 4557: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4558: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 4559: 				    $$record{"$where.$partid.checkedin"},
 4560: 				    $$record{"$where.$partid.checkedin.slot"}).
 4561: 					'<br />';
 4562: 	    }
 4563: 	    if (exists $$record{"$where.$partid.award"}) {
 4564: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 4565: 		    lc($$record{"$where.$partid.award"}).' '.
 4566: 		    $mark{$$record{"$where.$partid.solved"}}.
 4567: 		    '<br />';
 4568: 	    }
 4569: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4570: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4571: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4572: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4573: 		$displaySub[2].=
 4574: 		    $$record{"$version:resource.$partid.regrader"}.
 4575: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4576: 	    }
 4577: 	}
 4578: 	# needed because old essay regrader has not parts info
 4579: 	if (exists $$record{"$version:resource.regrader"}) {
 4580: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 4581: 	}
 4582: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 4583: 	if ($displaySub[2]) {
 4584: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 4585: 	}
 4586: 	$studentTable.='&nbsp;</td>'.
 4587: 	    &Apache::loncommon::end_data_table_row();
 4588:     }
 4589:     $studentTable.=&Apache::loncommon::end_data_table();
 4590:     return $studentTable;
 4591: }
 4592: 
 4593: sub updateGradeByPage {
 4594:     my ($request,$symb) = @_;
 4595: 
 4596:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4597:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4598:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4599:     my $pageTitle = $env{'form.page'};
 4600:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4601:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4602:     my $usec=$classlist->{$env{'form.student'}}[5];
 4603:     if (!&canmodify($usec)) {
 4604: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 4605: 	return;
 4606:     }
 4607:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4608:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 4609: 	'</h3>'."\n";
 4610: 
 4611:     $request->print($result);
 4612: 
 4613: 
 4614:     my $navmap = Apache::lonnavmaps::navmap->new();
 4615:     unless (ref($navmap)) {
 4616:         $request->print(&navmap_errormsg());
 4617:         return;
 4618:     }
 4619:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 4620:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4621:     if (!$map) {
 4622: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 4623: 	return; 
 4624:     }
 4625:     my $iterator = $navmap->getIterator($map->map_start(),
 4626: 					$map->map_finish());
 4627: 
 4628:     my $studentTable=
 4629: 	&Apache::loncommon::start_data_table().
 4630: 	&Apache::loncommon::start_data_table_header_row().
 4631: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 4632: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 4633: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 4634: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 4635: 	&Apache::loncommon::end_data_table_header_row();
 4636: 
 4637:     $iterator->next(); # skip the first BEGIN_MAP
 4638:     my $curRes = $iterator->next(); # for "current resource"
 4639:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 4640:     while ($depth > 0) {
 4641:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4642:         if($curRes == $iterator->END_MAP) { $depth--; }
 4643: 
 4644:         if (ref($curRes) && $curRes->is_problem()) {
 4645: 	    my $parts = $curRes->parts();
 4646:             my $title = $curRes->compTitle();
 4647: 	    my $symbx = $curRes->symb();
 4648: 	    $studentTable.=
 4649: 		&Apache::loncommon::start_data_table_row().
 4650: 		'<td align="center" valign="top" >'.$prob.
 4651: 		(scalar(@{$parts}) == 1 ? '' 
 4652:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
 4653: 		.')').'</td>';
 4654: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 4655: 
 4656: 	    my %newrecord=();
 4657: 	    my @displayPts=();
 4658:             my %aggregate = ();
 4659:             my $aggregateflag = 0;
 4660: 	    foreach my $partid (@{$parts}) {
 4661: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 4662: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 4663: 
 4664: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 4665: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 4666: 		my $partial = $newpts/$wgt;
 4667: 		my $score;
 4668: 		if ($partial > 0) {
 4669: 		    $score = 'correct_by_override';
 4670: 		} elsif ($newpts ne '') { #empty is taken as 0
 4671: 		    $score = 'incorrect_by_override';
 4672: 		}
 4673: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 4674: 		if ($dropMenu eq 'excused') {
 4675: 		    $partial = '';
 4676: 		    $score = 'excused';
 4677: 		} elsif ($dropMenu eq 'reset status'
 4678: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 4679: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 4680: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 4681: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 4682: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 4683: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 4684: 		    $changeflag++;
 4685: 		    $newpts = '';
 4686:                     
 4687:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 4688:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 4689:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 4690:                     if ($aggtries > 0) {
 4691:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4692:                         $aggregateflag = 1;
 4693:                     }
 4694: 		}
 4695: 		my $display_part=&get_display_part($partid,$curRes->symb());
 4696: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 4697: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4698: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 4699: 		    '&nbsp;<br />';
 4700: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4701: 		     (($score eq 'excused') ? 'excused' : $newpts).
 4702: 		    '&nbsp;<br />';
 4703: 		$question++;
 4704: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 4705: 
 4706: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 4707: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 4708: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 4709: 		    if (scalar(keys(%newrecord)) > 0);
 4710: 
 4711: 		$changeflag++;
 4712: 	    }
 4713: 	    if (scalar(keys(%newrecord)) > 0) {
 4714: 		my %record = 
 4715: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 4716: 					     $udom,$uname);
 4717: 
 4718: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 4719: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 4720: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 4721: 		    $newrecord{'resource.CODE'} = '';
 4722: 		}
 4723: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 4724: 					$udom,$uname);
 4725: 		%record = &Apache::lonnet::restore($symbx,
 4726: 						   $env{'request.course.id'},
 4727: 						   $udom,$uname);
 4728: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 4729: 					     $cdom,$cnum,$udom,$uname);
 4730: 	    }
 4731: 	    
 4732:             if ($aggregateflag) {
 4733:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4734:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 4735:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 4736:             }
 4737: 
 4738: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 4739: 		'<td valign="top">'.$displayPts[1].'</td>'.
 4740: 		&Apache::loncommon::end_data_table_row();
 4741: 
 4742: 	    $prob++;
 4743: 	}
 4744:         $curRes = $iterator->next();
 4745:     }
 4746: 
 4747:     $studentTable.=&Apache::loncommon::end_data_table();
 4748:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 4749: 		  &mt('The scores were changed for [quant,_1,problem].',
 4750: 		  $changeflag));
 4751:     $request->print($grademsg.$studentTable);
 4752: 
 4753:     return '';
 4754: }
 4755: 
 4756: #-------- end of section for handling grading by page/sequence ---------
 4757: #
 4758: #-------------------------------------------------------------------
 4759: 
 4760: #-------------------- Bubblesheet (Scantron) Grading -------------------
 4761: #
 4762: #------ start of section for handling grading by page/sequence ---------
 4763: 
 4764: =pod
 4765: 
 4766: =head1 Bubble sheet grading routines
 4767: 
 4768:   For this documentation:
 4769: 
 4770:    'scanline' refers to the full line of characters
 4771:    from the file that we are parsing that represents one entire sheet
 4772: 
 4773:    'bubble line' refers to the data
 4774:    representing the line of bubbles that are on the physical bubble sheet
 4775: 
 4776: 
 4777: The overall process is that a scanned in bubble sheet data is uploaded
 4778: into a course. When a user wants to grade, they select a
 4779: sequence/folder of resources, a file of bubble sheet info, and pick
 4780: one of the predefined configurations for what each scanline looks
 4781: like.
 4782: 
 4783: Next each scanline is checked for any errors of either 'missing
 4784: bubbles' (it's an error because it may have been mis-scanned
 4785: because too light bubbling), 'double bubble' (each bubble line should
 4786: have no more that one letter picked), invalid or duplicated CODE,
 4787: invalid student/employee ID
 4788: 
 4789: If the CODE option is used that determines the randomization of the
 4790: homework problems, either way the student/employee ID is looked up into a
 4791: username:domain.
 4792: 
 4793: During the validation phase the instructor can choose to skip scanlines. 
 4794: 
 4795: After the validation phase, there are now 3 bubble sheet files
 4796: 
 4797:   scantron_original_filename (unmodified original file)
 4798:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 4799:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 4800: 
 4801: Also there is a separate hash nohist_scantrondata that contains extra
 4802: correction information that isn't representable in the bubble sheet
 4803: file (see &scantron_getfile() for more information)
 4804: 
 4805: After all scanlines are either valid, marked as valid or skipped, then
 4806: foreach line foreach problem in the picked sequence, an ssi request is
 4807: made that simulates a user submitting their selected letter(s) against
 4808: the homework problem.
 4809: 
 4810: =over 4
 4811: 
 4812: 
 4813: 
 4814: =item defaultFormData
 4815: 
 4816:   Returns html hidden inputs used to hold context/default values.
 4817: 
 4818:  Arguments:
 4819:   $symb - $symb of the current resource 
 4820: 
 4821: =cut
 4822: 
 4823: sub defaultFormData {
 4824:     my ($symb)=@_;
 4825:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
 4826: }
 4827: 
 4828: 
 4829: =pod 
 4830: 
 4831: =item getSequenceDropDown
 4832: 
 4833:    Return html dropdown of possible sequences to grade
 4834:  
 4835:  Arguments:
 4836:    $symb - $symb of the current resource
 4837:    $map_error - ref to scalar which will container error if
 4838:                 $navmap object is unavailable in &getSymbMap().
 4839: 
 4840: =cut
 4841: 
 4842: sub getSequenceDropDown {
 4843:     my ($symb,$map_error)=@_;
 4844:     my $result='<select name="selectpage">'."\n";
 4845:     my ($titles,$symbx) = &getSymbMap($map_error);
 4846:     if (ref($map_error)) {
 4847:         return if ($$map_error);
 4848:     }
 4849:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 4850:     my $ctr=0;
 4851:     foreach (@$titles) {
 4852: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4853: 	$result.='<option value="'.$$symbx{$_}.'" '.
 4854: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4855: 	    '>'.$showtitle.'</option>'."\n";
 4856: 	$ctr++;
 4857:     }
 4858:     $result.= '</select>';
 4859:     return $result;
 4860: }
 4861: 
 4862: my %bubble_lines_per_response;     # no. bubble lines for each response.
 4863:                                    # key is zero-based index - 0, 1, 2 ...
 4864: 
 4865: my %first_bubble_line;             # First bubble line no. for each bubble.
 4866: 
 4867: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 4868:                                    # matchresponse or rankresponse, where 
 4869:                                    # an individual response can have multiple 
 4870:                                    # lines
 4871: 
 4872: my %responsetype_per_response;     # responsetype for each response
 4873: 
 4874: # Save and restore the bubble lines array to the form env.
 4875: 
 4876: 
 4877: sub save_bubble_lines {
 4878:     foreach my $line (keys(%bubble_lines_per_response)) {
 4879: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 4880: 	$env{"form.scantron.first_bubble_line.$line"} =
 4881: 	    $first_bubble_line{$line};
 4882:         $env{"form.scantron.sub_bubblelines.$line"} = 
 4883:             $subdivided_bubble_lines{$line};
 4884:         $env{"form.scantron.responsetype.$line"} =
 4885:             $responsetype_per_response{$line};
 4886:     }
 4887: }
 4888: 
 4889: 
 4890: sub restore_bubble_lines {
 4891:     my $line = 0;
 4892:     %bubble_lines_per_response = ();
 4893:     while ($env{"form.scantron.bubblelines.$line"}) {
 4894: 	my $value = $env{"form.scantron.bubblelines.$line"};
 4895: 	$bubble_lines_per_response{$line} = $value;
 4896: 	$first_bubble_line{$line}  =
 4897: 	    $env{"form.scantron.first_bubble_line.$line"};
 4898:         $subdivided_bubble_lines{$line} =
 4899:             $env{"form.scantron.sub_bubblelines.$line"};
 4900:         $responsetype_per_response{$line} =
 4901:             $env{"form.scantron.responsetype.$line"};
 4902: 	$line++;
 4903:     }
 4904: }
 4905: 
 4906: #  Given the parsed scanline, get the response for 
 4907: #  'answer' number n:
 4908: 
 4909: sub get_response_bubbles {
 4910:     my ($parsed_line, $response)  = @_;
 4911: 
 4912:     my $bubble_line = $first_bubble_line{$response-1} +1;
 4913:     my $bubble_lines= $bubble_lines_per_response{$response-1};
 4914:     
 4915:     my $selected = "";
 4916: 
 4917:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
 4918: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
 4919: 	$bubble_line++;
 4920:     }
 4921:     return $selected;
 4922: }
 4923: 
 4924: =pod 
 4925: 
 4926: =item scantron_filenames
 4927: 
 4928:    Returns a list of the scantron files in the current course 
 4929: 
 4930: =cut
 4931: 
 4932: sub scantron_filenames {
 4933:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4934:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4935:     my $getpropath = 1;
 4936:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
 4937:                                        $getpropath);
 4938:     my @possiblenames;
 4939:     foreach my $filename (sort(@files)) {
 4940: 	($filename)=split(/&/,$filename);
 4941: 	if ($filename!~/^scantron_orig_/) { next ; }
 4942: 	$filename=~s/^scantron_orig_//;
 4943: 	push(@possiblenames,$filename);
 4944:     }
 4945:     return @possiblenames;
 4946: }
 4947: 
 4948: =pod 
 4949: 
 4950: =item scantron_uploads
 4951: 
 4952:    Returns  html drop-down list of scantron files in current course.
 4953: 
 4954:  Arguments:
 4955:    $file2grade - filename to set as selected in the dropdown
 4956: 
 4957: =cut
 4958: 
 4959: sub scantron_uploads {
 4960:     my ($file2grade) = @_;
 4961:     my $result=	'<select name="scantron_selectfile">';
 4962:     $result.="<option></option>";
 4963:     foreach my $filename (sort(&scantron_filenames())) {
 4964: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 4965:     }
 4966:     $result.="</select>";
 4967:     return $result;
 4968: }
 4969: 
 4970: =pod 
 4971: 
 4972: =item scantron_scantab
 4973: 
 4974:   Returns html drop down of the scantron formats in the scantronformat.tab
 4975:   file.
 4976: 
 4977: =cut
 4978: 
 4979: sub scantron_scantab {
 4980:     my $result='<select name="scantron_format">'."\n";
 4981:     $result.='<option></option>'."\n";
 4982:     my @lines = &get_scantronformat_file();
 4983:     if (@lines > 0) {
 4984:         foreach my $line (@lines) {
 4985:             next if (($line =~ /^\#/) || ($line eq ''));
 4986: 	    my ($name,$descrip)=split(/:/,$line);
 4987: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 4988:         }
 4989:     }
 4990:     $result.='</select>'."\n";
 4991:     return $result;
 4992: }
 4993: 
 4994: =pod
 4995: 
 4996: =item get_scantronformat_file
 4997: 
 4998:   Returns an array containing lines from the scantron format file for
 4999:   the domain of the course.
 5000: 
 5001:   If a url for a custom.tab file is listed in domain's configuration.db, 
 5002:   lines are from this file.
 5003: 
 5004:   Otherwise, if a default.tab has been published in RES space by the 
 5005:   domainconfig user, lines are from this file.
 5006: 
 5007:   Otherwise, fall back to getting lines from the legacy file on the
 5008:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 5009: 
 5010: =cut
 5011: 
 5012: sub get_scantronformat_file {
 5013:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5014:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 5015:     my $gottab = 0;
 5016:     my @lines;
 5017:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5018:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5019:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5020:             if ($formatfile ne '-1') {
 5021:                 @lines = split("\n",$formatfile,-1);
 5022:                 $gottab = 1;
 5023:             }
 5024:         }
 5025:     }
 5026:     if (!$gottab) {
 5027:         my $confname = $cdom.'-domainconfig';
 5028:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5029:         my $formatfile =  &Apache::lonnet::getfile($default);
 5030:         if ($formatfile ne '-1') {
 5031:             @lines = split("\n",$formatfile,-1);
 5032:             $gottab = 1;
 5033:         }
 5034:     }
 5035:     if (!$gottab) {
 5036:         my @domains = &Apache::lonnet::current_machine_domains();
 5037:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5038:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5039:             @lines = <$fh>;
 5040:             close($fh);
 5041:         } else {
 5042:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 5043:             @lines = <$fh>;
 5044:             close($fh);
 5045:         }
 5046:     }
 5047:     return @lines;
 5048: }
 5049: 
 5050: =pod 
 5051: 
 5052: =item scantron_CODElist
 5053: 
 5054:   Returns html drop down of the saved CODE lists from current course,
 5055:   generated from earlier printings.
 5056: 
 5057: =cut
 5058: 
 5059: sub scantron_CODElist {
 5060:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5061:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5062:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5063:     my $namechoice='<option></option>';
 5064:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5065: 	if ($name =~ /^error: 2 /) { next; }
 5066: 	if ($name =~ /^type\0/) { next; }
 5067: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5068:     }
 5069:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5070:     return $namechoice;
 5071: }
 5072: 
 5073: =pod 
 5074: 
 5075: =item scantron_CODEunique
 5076: 
 5077:   Returns the html for "Each CODE to be used once" radio.
 5078: 
 5079: =cut
 5080: 
 5081: sub scantron_CODEunique {
 5082:     my $result='<span class="LC_nobreak">
 5083:                  <label><input type="radio" name="scantron_CODEunique"
 5084:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5085:                 </span>
 5086:                 <span class="LC_nobreak">
 5087:                  <label><input type="radio" name="scantron_CODEunique"
 5088:                         value="no" />'.&mt('No').' </label>
 5089:                 </span>';
 5090:     return $result;
 5091: }
 5092: 
 5093: =pod 
 5094: 
 5095: =item scantron_selectphase
 5096: 
 5097:   Generates the initial screen to start the bubble sheet process.
 5098:   Allows for - starting a grading run.
 5099:              - downloading existing scan data (original, corrected
 5100:                                                 or skipped info)
 5101: 
 5102:              - uploading new scan data
 5103: 
 5104:  Arguments:
 5105:   $r          - The Apache request object
 5106:   $file2grade - name of the file that contain the scanned data to score
 5107: 
 5108: =cut
 5109: 
 5110: sub scantron_selectphase {
 5111:     my ($r,$file2grade,$symb) = @_;
 5112:     if (!$symb) {return '';}
 5113:     my $map_error;
 5114:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 5115:     if ($map_error) {
 5116:         $r->print('<br />'.&navmap_errormsg().'<br />');
 5117:         return;
 5118:     }
 5119:     my $default_form_data=&defaultFormData($symb);
 5120:     my $file_selector=&scantron_uploads($file2grade);
 5121:     my $format_selector=&scantron_scantab();
 5122:     my $CODE_selector=&scantron_CODElist();
 5123:     my $CODE_unique=&scantron_CODEunique();
 5124:     my $result;
 5125: 
 5126:     $ssi_error = 0;
 5127: 
 5128:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5129:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5130: 
 5131: 	# Chunk of form to prompt for a scantron file upload.
 5132: 
 5133:         $r->print('
 5134:     <br />
 5135:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5136:        '.&Apache::loncommon::start_data_table_header_row().'
 5137:             <th>
 5138:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 5139:             </th>
 5140:        '.&Apache::loncommon::end_data_table_header_row().'
 5141:        '.&Apache::loncommon::start_data_table_row().'
 5142:             <td>
 5143: ');
 5144:     my $default_form_data=&defaultFormData($symb);
 5145:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5146:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5147:     $r->print(&Apache::lonhtmlcommon::scripttag('
 5148:     function checkUpload(formname) {
 5149: 	if (formname.upfile.value == "") {
 5150: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 5151: 	    return false;
 5152: 	}
 5153: 	formname.submit();
 5154:     }'));
 5155:     $r->print('
 5156:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5157:                 '.$default_form_data.'
 5158:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5159:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5160:                 <input name="command" value="scantronupload_save" type="hidden" />
 5161:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5162:                 <br />
 5163:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 5164:               </form>
 5165: ');
 5166: 
 5167:         $r->print('
 5168:             </td>
 5169:        '.&Apache::loncommon::end_data_table_row().'
 5170:        '.&Apache::loncommon::end_data_table().'
 5171: ');
 5172:     }
 5173: 
 5174:     # Chunk of form to prompt for a file to grade and how:
 5175: 
 5176:     $result.= '
 5177:     <br />
 5178:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5179:     <input type="hidden" name="command" value="scantron_warning" />
 5180:     '.$default_form_data.'
 5181:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5182:        '.&Apache::loncommon::start_data_table_header_row().'
 5183:             <th colspan="2">
 5184:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5185:             </th>
 5186:        '.&Apache::loncommon::end_data_table_header_row().'
 5187:        '.&Apache::loncommon::start_data_table_row().'
 5188:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5189:        '.&Apache::loncommon::end_data_table_row().'
 5190:        '.&Apache::loncommon::start_data_table_row().'
 5191:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 5192:        '.&Apache::loncommon::end_data_table_row().'
 5193:        '.&Apache::loncommon::start_data_table_row().'
 5194:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 5195:        '.&Apache::loncommon::end_data_table_row().'
 5196:        '.&Apache::loncommon::start_data_table_row().'
 5197:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5198:        '.&Apache::loncommon::end_data_table_row().'
 5199:        '.&Apache::loncommon::start_data_table_row().'
 5200:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5201:        '.&Apache::loncommon::end_data_table_row().'
 5202:        '.&Apache::loncommon::start_data_table_row().'
 5203: 	    <td> '.&mt('Options:').' </td>
 5204:             <td>
 5205: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5206:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5207:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5208: 	    </td>
 5209:        '.&Apache::loncommon::end_data_table_row().'
 5210:        '.&Apache::loncommon::start_data_table_row().'
 5211:             <td colspan="2">
 5212:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 5213:             </td>
 5214:        '.&Apache::loncommon::end_data_table_row().'
 5215:     '.&Apache::loncommon::end_data_table().'
 5216:     </form>
 5217: ';
 5218:    
 5219:     $r->print($result);
 5220: 
 5221: 
 5222: 
 5223:     # Chunk of the form that prompts to view a scoring office file,
 5224:     # corrected file, skipped records in a file.
 5225: 
 5226:     $r->print('
 5227:    <br />
 5228:    <form action="/adm/grades" name="scantron_download">
 5229:      '.$default_form_data.'
 5230:      <input type="hidden" name="command" value="scantron_download" />
 5231:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5232:        '.&Apache::loncommon::start_data_table_header_row().'
 5233:               <th>
 5234:                 &nbsp;'.&mt('Download a scoring office file').'
 5235:               </th>
 5236:        '.&Apache::loncommon::end_data_table_header_row().'
 5237:        '.&Apache::loncommon::start_data_table_row().'
 5238:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5239:                 <br />
 5240:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5241:        '.&Apache::loncommon::end_data_table_row().'
 5242:      '.&Apache::loncommon::end_data_table().'
 5243:    </form>
 5244:    <br />
 5245: ');
 5246: 
 5247:     &Apache::lonpickcode::code_list($r,2);
 5248: 
 5249:     $r->print('<br /><form method="post" name="checkscantron">'.
 5250:              $default_form_data."\n".
 5251:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5252:              &Apache::loncommon::start_data_table_header_row()."\n".
 5253:              '<th colspan="2">
 5254:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 5255:              '</th>'."\n".
 5256:               &Apache::loncommon::end_data_table_header_row()."\n".
 5257:               &Apache::loncommon::start_data_table_row()."\n".
 5258:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5259:               '<td> '.$sequence_selector.' </td>'.
 5260:               &Apache::loncommon::end_data_table_row()."\n".
 5261:               &Apache::loncommon::start_data_table_row()."\n".
 5262:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5263:               '<td> '.$file_selector.' </td>'."\n".
 5264:               &Apache::loncommon::end_data_table_row()."\n".
 5265:               &Apache::loncommon::start_data_table_row()."\n".
 5266:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5267:               '<td> '.$format_selector.' </td>'."\n".
 5268:               &Apache::loncommon::end_data_table_row()."\n".
 5269:               &Apache::loncommon::start_data_table_row()."\n".
 5270:               '<td> '.&mt('Options').' </td>'."\n".
 5271:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 5272:               &Apache::loncommon::end_data_table_row()."\n".
 5273:               &Apache::loncommon::start_data_table_row()."\n".
 5274:               '<td colspan="2">'."\n".
 5275:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5276:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 5277:               '</td>'."\n".
 5278:               &Apache::loncommon::end_data_table_row()."\n".
 5279:               &Apache::loncommon::end_data_table()."\n".
 5280:               '</form><br />');
 5281:     return;
 5282: }
 5283: 
 5284: =pod
 5285: 
 5286: =item get_scantron_config
 5287: 
 5288:    Parse and return the scantron configuration line selected as a
 5289:    hash of configuration file fields.
 5290: 
 5291:  Arguments:
 5292:     which - the name of the configuration to parse from the file.
 5293: 
 5294: 
 5295:  Returns:
 5296:             If the named configuration is not in the file, an empty
 5297:             hash is returned.
 5298:     a hash with the fields
 5299:       name         - internal name for the this configuration setup
 5300:       description  - text to display to operator that describes this config
 5301:       CODElocation - if 0 or the string 'none'
 5302:                           - no CODE exists for this config
 5303:                      if -1 || the string 'letter'
 5304:                           - a CODE exists for this config and is
 5305:                             a string of letters
 5306:                      Unsupported value (but planned for future support)
 5307:                           if a positive integer
 5308:                                - The CODE exists as the first n items from
 5309:                                  the question section of the form
 5310:                           if the string 'number'
 5311:                                - The CODE exists for this config and is
 5312:                                  a string of numbers
 5313:       CODEstart   - (only matter if a CODE exists) column in the line where
 5314:                      the CODE starts
 5315:       CODElength  - length of the CODE
 5316:       IDstart     - column where the student/employee ID starts
 5317:       IDlength    - length of the student/employee ID info
 5318:       Qstart      - column where the information from the bubbled
 5319:                     'questions' start
 5320:       Qlength     - number of columns comprising a single bubble line from
 5321:                     the sheet. (usually either 1 or 10)
 5322:       Qon         - either a single character representing the character used
 5323:                     to signal a bubble was chosen in the positional setup, or
 5324:                     the string 'letter' if the letter of the chosen bubble is
 5325:                     in the final, or 'number' if a number representing the
 5326:                     chosen bubble is in the file (1->A 0->J)
 5327:       Qoff        - the character used to represent that a bubble was
 5328:                     left blank
 5329:       PaperID     - if the scanning process generates a unique number for each
 5330:                     sheet scanned the column that this ID number starts in
 5331:       PaperIDlength - number of columns that comprise the unique ID number
 5332:                       for the sheet of paper
 5333:       FirstName   - column that the first name starts in
 5334:       FirstNameLength - number of columns that the first name spans
 5335:  
 5336:       LastName    - column that the last name starts in
 5337:       LastNameLength - number of columns that the last name spans
 5338: 
 5339: =cut
 5340: 
 5341: sub get_scantron_config {
 5342:     my ($which) = @_;
 5343:     my @lines = &get_scantronformat_file();
 5344:     my %config;
 5345:     #FIXME probably should move to XML it has already gotten a bit much now
 5346:     foreach my $line (@lines) {
 5347: 	my ($name,$descrip)=split(/:/,$line);
 5348: 	if ($name ne $which ) { next; }
 5349: 	chomp($line);
 5350: 	my @config=split(/:/,$line);
 5351: 	$config{'name'}=$config[0];
 5352: 	$config{'description'}=$config[1];
 5353: 	$config{'CODElocation'}=$config[2];
 5354: 	$config{'CODEstart'}=$config[3];
 5355: 	$config{'CODElength'}=$config[4];
 5356: 	$config{'IDstart'}=$config[5];
 5357: 	$config{'IDlength'}=$config[6];
 5358: 	$config{'Qstart'}=$config[7];
 5359:  	$config{'Qlength'}=$config[8];
 5360: 	$config{'Qoff'}=$config[9];
 5361: 	$config{'Qon'}=$config[10];
 5362: 	$config{'PaperID'}=$config[11];
 5363: 	$config{'PaperIDlength'}=$config[12];
 5364: 	$config{'FirstName'}=$config[13];
 5365: 	$config{'FirstNamelength'}=$config[14];
 5366: 	$config{'LastName'}=$config[15];
 5367: 	$config{'LastNamelength'}=$config[16];
 5368: 	last;
 5369:     }
 5370:     return %config;
 5371: }
 5372: 
 5373: =pod 
 5374: 
 5375: =item username_to_idmap
 5376: 
 5377:     creates a hash keyed by student/employee ID with values of the corresponding
 5378:     student username:domain.
 5379: 
 5380:   Arguments:
 5381: 
 5382:     $classlist - reference to the class list hash. This is a hash
 5383:                  keyed by student name:domain  whose elements are references
 5384:                  to arrays containing various chunks of information
 5385:                  about the student. (See loncoursedata for more info).
 5386: 
 5387:   Returns
 5388:     %idmap - the constructed hash
 5389: 
 5390: =cut
 5391: 
 5392: sub username_to_idmap {
 5393:     my ($classlist)= @_;
 5394:     my %idmap;
 5395:     foreach my $student (keys(%$classlist)) {
 5396: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5397: 	    $student;
 5398:     }
 5399:     return %idmap;
 5400: }
 5401: 
 5402: =pod
 5403: 
 5404: =item scantron_fixup_scanline
 5405: 
 5406:    Process a requested correction to a scanline.
 5407: 
 5408:   Arguments:
 5409:     $scantron_config   - hash from &get_scantron_config()
 5410:     $scan_data         - hash of correction information 
 5411:                           (see &scantron_getfile())
 5412:     $line              - existing scanline
 5413:     $whichline         - line number of the passed in scanline
 5414:     $field             - type of change to process 
 5415:                          (either 
 5416:                           'ID'     -> correct the student/employee ID
 5417:                           'CODE'   -> correct the CODE
 5418:                           'answer' -> fixup the submitted answers)
 5419:     
 5420:    $args               - hash of additional info,
 5421:                           - 'ID' 
 5422:                                'newid' -> studentID to use in replacement
 5423:                                           of existing one
 5424:                           - 'CODE' 
 5425:                                'CODE_ignore_dup' - set to true if duplicates
 5426:                                                    should be ignored.
 5427: 	                       'CODE' - is new code or 'use_unfound'
 5428:                                         if the existing unfound code should
 5429:                                         be used as is
 5430:                           - 'answer'
 5431:                                'response' - new answer or 'none' if blank
 5432:                                'question' - the bubble line to change
 5433:                                'questionnum' - the question identifier,
 5434:                                                may include subquestion. 
 5435: 
 5436:   Returns:
 5437:     $line - the modified scanline
 5438: 
 5439:   Side effects: 
 5440:     $scan_data - may be updated
 5441: 
 5442: =cut
 5443: 
 5444: 
 5445: sub scantron_fixup_scanline {
 5446:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5447:     if ($field eq 'ID') {
 5448: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5449: 	    return ($line,1,'New value too large');
 5450: 	}
 5451: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5452: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5453: 				     $args->{'newid'});
 5454: 	}
 5455: 	substr($line,$$scantron_config{'IDstart'}-1,
 5456: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5457: 	if ($args->{'newid'}=~/^\s*$/) {
 5458: 	    &scan_data($scan_data,"$whichline.user",
 5459: 		       $args->{'username'}.':'.$args->{'domain'});
 5460: 	}
 5461:     } elsif ($field eq 'CODE') {
 5462: 	if ($args->{'CODE_ignore_dup'}) {
 5463: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5464: 	}
 5465: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5466: 	if ($args->{'CODE'} ne 'use_unfound') {
 5467: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5468: 		return ($line,1,'New CODE value too large');
 5469: 	    }
 5470: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5471: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5472: 	    }
 5473: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5474: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5475: 	}
 5476:     } elsif ($field eq 'answer') {
 5477: 	my $length=$scantron_config->{'Qlength'};
 5478: 	my $off=$scantron_config->{'Qoff'};
 5479: 	my $on=$scantron_config->{'Qon'};
 5480: 	my $answer=${off}x$length;
 5481: 	if ($args->{'response'} eq 'none') {
 5482: 	    &scan_data($scan_data,
 5483: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5484: 	} else {
 5485: 	    if ($on eq 'letter') {
 5486: 		my @alphabet=('A'..'Z');
 5487: 		$answer=$alphabet[$args->{'response'}];
 5488: 	    } elsif ($on eq 'number') {
 5489: 		$answer=$args->{'response'}+1;
 5490: 		if ($answer == 10) { $answer = '0'; }
 5491: 	    } else {
 5492: 		substr($answer,$args->{'response'},1)=$on;
 5493: 	    }
 5494: 	    &scan_data($scan_data,
 5495: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5496: 	}
 5497: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5498: 	substr($line,$where-1,$length)=$answer;
 5499:     }
 5500:     return $line;
 5501: }
 5502: 
 5503: =pod
 5504: 
 5505: =item scan_data
 5506: 
 5507:     Edit or look up  an item in the scan_data hash.
 5508: 
 5509:   Arguments:
 5510:     $scan_data  - The hash (see scantron_getfile)
 5511:     $key        - shorthand of the key to edit (actual key is
 5512:                   scantronfilename_key).
 5513:     $data        - New value of the hash entry.
 5514:     $delete      - If true, the entry is removed from the hash.
 5515: 
 5516:   Returns:
 5517:     The new value of the hash table field (undefined if deleted).
 5518: 
 5519: =cut
 5520: 
 5521: 
 5522: sub scan_data {
 5523:     my ($scan_data,$key,$value,$delete)=@_;
 5524:     my $filename=$env{'form.scantron_selectfile'};
 5525:     if (defined($value)) {
 5526: 	$scan_data->{$filename.'_'.$key} = $value;
 5527:     }
 5528:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5529:     return $scan_data->{$filename.'_'.$key};
 5530: }
 5531: 
 5532: # ----- These first few routines are general use routines.----
 5533: 
 5534: # Return the number of occurences of a pattern in a string.
 5535: 
 5536: sub occurence_count {
 5537:     my ($string, $pattern) = @_;
 5538: 
 5539:     my @matches = ($string =~ /$pattern/g);
 5540: 
 5541:     return scalar(@matches);
 5542: }
 5543: 
 5544: 
 5545: # Take a string known to have digits and convert all the
 5546: # digits into letters in the range J,A..I.
 5547: 
 5548: sub digits_to_letters {
 5549:     my ($input) = @_;
 5550: 
 5551:     my @alphabet = ('J', 'A'..'I');
 5552: 
 5553:     my @input    = split(//, $input);
 5554:     my $output ='';
 5555:     for (my $i = 0; $i < scalar(@input); $i++) {
 5556: 	if ($input[$i] =~ /\d/) {
 5557: 	    $output .= $alphabet[$input[$i]];
 5558: 	} else {
 5559: 	    $output .= $input[$i];
 5560: 	}
 5561:     }
 5562:     return $output;
 5563: }
 5564: 
 5565: =pod 
 5566: 
 5567: =item scantron_parse_scanline
 5568: 
 5569:   Decodes a scanline from the selected scantron file
 5570: 
 5571:  Arguments:
 5572:     line             - The text of the scantron file line to process
 5573:     whichline        - Line number
 5574:     scantron_config  - Hash describing the format of the scantron lines.
 5575:     scan_data        - Hash of extra information about the scanline
 5576:                        (see scantron_getfile for more information)
 5577:     just_header      - True if should not process question answers but only
 5578:                        the stuff to the left of the answers.
 5579:  Returns:
 5580:    Hash containing the result of parsing the scanline
 5581: 
 5582:    Keys are all proceeded by the string 'scantron.'
 5583: 
 5584:        CODE    - the CODE in use for this scanline
 5585:        useCODE - 1 if the CODE is invalid but it usage has been forced
 5586:                  by the operator
 5587:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 5588:                             CODEs were selected, but the usage has been
 5589:                             forced by the operator
 5590:        ID  - student/employee ID
 5591:        PaperID - if used, the ID number printed on the sheet when the 
 5592:                  paper was scanned
 5593:        FirstName - first name from the sheet
 5594:        LastName  - last name from the sheet
 5595: 
 5596:      if just_header was not true these key may also exist
 5597: 
 5598:        missingerror - a list of bubble ranges that are considered to be answers
 5599:                       to a single question that don't have any bubbles filled in.
 5600:                       Of the form questionnumber:firstbubblenumber:count.
 5601:        doubleerror  - a list of bubble ranges that are considered to be answers
 5602:                       to a single question that have more than one bubble filled in.
 5603:                       Of the form questionnumber::firstbubblenumber:count
 5604:    
 5605:                 In the above, count is the number of bubble responses in the
 5606:                 input line needed to represent the possible answers to the question.
 5607:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 5608:                 per line would have count = 2.
 5609: 
 5610:        maxquest     - the number of the last bubble line that was parsed
 5611: 
 5612:        (<number> starts at 1)
 5613:        <number>.answer - zero or more letters representing the selected
 5614:                          letters from the scanline for the bubble line 
 5615:                          <number>.
 5616:                          if blank there was either no bubble or there where
 5617:                          multiple bubbles, (consult the keys missingerror and
 5618:                          doubleerror if this is an error condition)
 5619: 
 5620: =cut
 5621: 
 5622: sub scantron_parse_scanline {
 5623:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
 5624: 
 5625:     my %record;
 5626:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 5627:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 5628:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
 5629:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 5630: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 5631: 	if ($$scantron_config{'CODElocation'} < 0 ||
 5632: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 5633: 	    $$scantron_config{'CODElocation'} eq 'number') {
 5634: 	    $record{'scantron.CODE'}=substr($data,
 5635: 					    $$scantron_config{'CODEstart'}-1,
 5636: 					    $$scantron_config{'CODElength'});
 5637: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 5638: 		$record{'scantron.useCODE'}=1;
 5639: 	    }
 5640: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 5641: 		$record{'scantron.CODE_ignore_dup'}=1;
 5642: 	    }
 5643: 	} else {
 5644: 	    #FIXME interpret first N questions
 5645: 	}
 5646:     }
 5647:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 5648: 				  $$scantron_config{'IDlength'});
 5649:     $record{'scantron.PaperID'}=
 5650: 	substr($data,$$scantron_config{'PaperID'}-1,
 5651: 	       $$scantron_config{'PaperIDlength'});
 5652:     $record{'scantron.FirstName'}=
 5653: 	substr($data,$$scantron_config{'FirstName'}-1,
 5654: 	       $$scantron_config{'FirstNamelength'});
 5655:     $record{'scantron.LastName'}=
 5656: 	substr($data,$$scantron_config{'LastName'}-1,
 5657: 	       $$scantron_config{'LastNamelength'});
 5658:     if ($just_header) { return \%record; }
 5659: 
 5660:     my @alphabet=('A'..'Z');
 5661:     my $questnum=0;
 5662:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 5663: 
 5664:     chomp($questions);		# Get rid of any trailing \n.
 5665:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 5666:     while (length($questions)) {
 5667: 	my $answers_needed = $bubble_lines_per_response{$questnum};
 5668:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 5669:                              || 1;
 5670:         $questnum++;
 5671:         my $quest_id = $questnum;
 5672:         my $currentquest = substr($questions,0,$answer_length);
 5673:         $questions       = substr($questions,$answer_length);
 5674:         if (length($currentquest) < $answer_length) { next; }
 5675: 
 5676:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
 5677:             my $subquestnum = 1;
 5678:             my $subquestions = $currentquest;
 5679:             my @subanswers_needed = 
 5680:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
 5681:             foreach my $subans (@subanswers_needed) {
 5682:                 my $subans_length =
 5683:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 5684:                 my $currsubquest = substr($subquestions,0,$subans_length);
 5685:                 $subquestions   = substr($subquestions,$subans_length);
 5686:                 $quest_id = "$questnum.$subquestnum";
 5687:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 5688:                     ($$scantron_config{'Qon'} eq 'number')) {
 5689:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 5690:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 5691:                         \@alphabet,\%record,$scantron_config,$scan_data);
 5692:                 } else {
 5693:                     $ansnum = &scantron_validator_positional($ansnum,
 5694:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
 5695:                 }
 5696:                 $subquestnum ++;
 5697:             }
 5698:         } else {
 5699:             if (($$scantron_config{'Qon'} eq 'letter') ||
 5700:                 ($$scantron_config{'Qon'} eq 'number')) {
 5701:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 5702:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5703:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5704:             } else {
 5705:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 5706:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5707:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5708:             }
 5709:         }
 5710:     }
 5711:     $record{'scantron.maxquest'}=$questnum;
 5712:     return \%record;
 5713: }
 5714: 
 5715: sub scantron_validator_lettnum {
 5716:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 5717:         $alphabet,$record,$scantron_config,$scan_data) = @_;
 5718: 
 5719:     # Qon 'letter' implies for each slot in currquest we have:
 5720:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 5721:     #    about anything else (esp. a value of Qoff) for missing
 5722:     #    bubbles.
 5723:     #
 5724:     # Qon 'number' implies each slot gives a digit that indexes the
 5725:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 5726:     #    and * or ? for double bubbles on a single line.
 5727:     #
 5728: 
 5729:     my $matchon;
 5730:     if ($$scantron_config{'Qon'} eq 'letter') {
 5731:         $matchon = '[A-Z]';
 5732:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 5733:         $matchon = '\d';
 5734:     }
 5735:     my $occurrences = 0;
 5736:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5737:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5738:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5739:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5740:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5741:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5742:         my @singlelines = split('',$currquest);
 5743:         foreach my $entry (@singlelines) {
 5744:             $occurrences = &occurence_count($entry,$matchon);
 5745:             if ($occurrences > 1) {
 5746:                 last;
 5747:             }
 5748:         } 
 5749:     } else {
 5750:         $occurrences = &occurence_count($currquest,$matchon); 
 5751:     }
 5752:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 5753:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5754:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5755:             my $bubble = substr($currquest,$ans,1);
 5756:             if ($bubble =~ /$matchon/ ) {
 5757:                 if ($$scantron_config{'Qon'} eq 'number') {
 5758:                     if ($bubble == 0) {
 5759:                         $bubble = 10; 
 5760:                     }
 5761:                     $record->{"scantron.$ansnum.answer"} = 
 5762:                         $alphabet->[$bubble-1];
 5763:                 } else {
 5764:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 5765:                 }
 5766:             } else {
 5767:                 $record->{"scantron.$ansnum.answer"}='';
 5768:             }
 5769:             $ansnum++;
 5770:         }
 5771:     } elsif (!defined($currquest)
 5772:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 5773:             || (&occurence_count($currquest,$matchon) == 0)) {
 5774:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5775:             $record->{"scantron.$ansnum.answer"}='';
 5776:             $ansnum++;
 5777:         }
 5778:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5779:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 5780:         }
 5781:     } else {
 5782:         if ($$scantron_config{'Qon'} eq 'number') {
 5783:             $currquest = &digits_to_letters($currquest);            
 5784:         }
 5785:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5786:             my $bubble = substr($currquest,$ans,1);
 5787:             $record->{"scantron.$ansnum.answer"} = $bubble;
 5788:             $ansnum++;
 5789:         }
 5790:     }
 5791:     return $ansnum;
 5792: }
 5793: 
 5794: sub scantron_validator_positional {
 5795:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 5796:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
 5797: 
 5798:     # Otherwise there's a positional notation;
 5799:     # each bubble line requires Qlength items, and there are filled in
 5800:     # bubbles for each case where there 'Qon' characters.
 5801:     #
 5802: 
 5803:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 5804: 
 5805:     # If the split only gives us one element.. the full length of the
 5806:     # answer string, no bubbles are filled in:
 5807: 
 5808:     if ($answers_needed eq '') {
 5809:         return;
 5810:     }
 5811: 
 5812:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 5813:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5814:             $record->{"scantron.$ansnum.answer"}='';
 5815:             $ansnum++;
 5816:         }
 5817:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5818:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 5819:         }
 5820:     } elsif (scalar(@array) == 2) {
 5821:         my $location = length($array[0]);
 5822:         my $line_num = int($location / $$scantron_config{'Qlength'});
 5823:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 5824:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5825:             if ($ans eq $line_num) {
 5826:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 5827:             } else {
 5828:                 $record->{"scantron.$ansnum.answer"} = ' ';
 5829:             }
 5830:             $ansnum++;
 5831:          }
 5832:     } else {
 5833:         #  If there's more than one instance of a bubble character
 5834:         #  That's a double bubble; with positional notation we can
 5835:         #  record all the bubbles filled in as well as the
 5836:         #  fact this response consists of multiple bubbles.
 5837:         #
 5838:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5839:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5840:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5841:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5842:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5843:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5844:             my $doubleerror = 0;
 5845:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 5846:                    (!$doubleerror)) {
 5847:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 5848:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 5849:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 5850:                if (length(@currarray) > 2) {
 5851:                    $doubleerror = 1;
 5852:                } 
 5853:             }
 5854:             if ($doubleerror) {
 5855:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5856:             }
 5857:         } else {
 5858:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5859:         }
 5860:         my $item = $ansnum;
 5861:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5862:             $record->{"scantron.$item.answer"} = '';
 5863:             $item ++;
 5864:         }
 5865: 
 5866:         my @ans=@array;
 5867:         my $i=0;
 5868:         my $increment = 0;
 5869:         while ($#ans) {
 5870:             $i+=length($ans[0]) + $increment;
 5871:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 5872:             my $bubble = $i%$$scantron_config{'Qlength'};
 5873:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 5874:             shift(@ans);
 5875:             $increment = 1;
 5876:         }
 5877:         $ansnum += $answers_needed;
 5878:     }
 5879:     return $ansnum;
 5880: }
 5881: 
 5882: =pod
 5883: 
 5884: =item scantron_add_delay
 5885: 
 5886:    Adds an error message that occurred during the grading phase to a
 5887:    queue of messages to be shown after grading pass is complete
 5888: 
 5889:  Arguments:
 5890:    $delayqueue  - arrary ref of hash ref of error messages
 5891:    $scanline    - the scanline that caused the error
 5892:    $errormesage - the error message
 5893:    $errorcode   - a numeric code for the error
 5894: 
 5895:  Side Effects:
 5896:    updates the $delayqueue to have a new hash ref of the error
 5897: 
 5898: =cut
 5899: 
 5900: sub scantron_add_delay {
 5901:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 5902:     push(@$delayqueue,
 5903: 	 {'line' => $scanline, 'emsg' => $errormessage,
 5904: 	  'ecode' => $errorcode }
 5905: 	 );
 5906: }
 5907: 
 5908: =pod
 5909: 
 5910: =item scantron_find_student
 5911: 
 5912:    Finds the username for the current scanline
 5913: 
 5914:   Arguments:
 5915:    $scantron_record - hash result from scantron_parse_scanline
 5916:    $scan_data       - hash of correction information 
 5917:                       (see &scantron_getfile() form more information)
 5918:    $idmap           - hash from &username_to_idmap()
 5919:    $line            - number of current scanline
 5920:  
 5921:   Returns:
 5922:    Either 'username:domain' or undef if unknown
 5923: 
 5924: =cut
 5925: 
 5926: sub scantron_find_student {
 5927:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 5928:     my $scanID=$$scantron_record{'scantron.ID'};
 5929:     if ($scanID =~ /^\s*$/) {
 5930:  	return &scan_data($scan_data,"$line.user");
 5931:     }
 5932:     foreach my $id (keys(%$idmap)) {
 5933:  	if (lc($id) eq lc($scanID)) {
 5934:  	    return $$idmap{$id};
 5935:  	}
 5936:     }
 5937:     return undef;
 5938: }
 5939: 
 5940: =pod
 5941: 
 5942: =item scantron_filter
 5943: 
 5944:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 5945:    hidden resources was selected
 5946: 
 5947: =cut
 5948: 
 5949: sub scantron_filter {
 5950:     my ($curres)=@_;
 5951: 
 5952:     if (ref($curres) && $curres->is_problem()) {
 5953: 	# if the user has asked to not have either hidden
 5954: 	# or 'randomout' controlled resources to be graded
 5955: 	# don't include them
 5956: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 5957: 	    && $curres->randomout) {
 5958: 	    return 0;
 5959: 	}
 5960: 	return 1;
 5961:     }
 5962:     return 0;
 5963: }
 5964: 
 5965: =pod
 5966: 
 5967: =item scantron_process_corrections
 5968: 
 5969:    Gets correction information out of submitted form data and corrects
 5970:    the scanline
 5971: 
 5972: =cut
 5973: 
 5974: sub scantron_process_corrections {
 5975:     my ($r) = @_;
 5976:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 5977:     my ($scanlines,$scan_data)=&scantron_getfile();
 5978:     my $classlist=&Apache::loncoursedata::get_classlist();
 5979:     my $which=$env{'form.scantron_line'};
 5980:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 5981:     my ($skip,$err,$errmsg);
 5982:     if ($env{'form.scantron_skip_record'}) {
 5983: 	$skip=1;
 5984:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 5985: 	my $newstudent=$env{'form.scantron_username'}.':'.
 5986: 	    $env{'form.scantron_domain'};
 5987: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 5988: 	($line,$err,$errmsg)=
 5989: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 5990: 				     'ID',{'newid'=>$newid,
 5991: 				    'username'=>$env{'form.scantron_username'},
 5992: 				    'domain'=>$env{'form.scantron_domain'}});
 5993:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 5994: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 5995: 	my $newCODE;
 5996: 	my %args;
 5997: 	if      ($resolution eq 'use_unfound') {
 5998: 	    $newCODE='use_unfound';
 5999: 	} elsif ($resolution eq 'use_found') {
 6000: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6001: 	} elsif ($resolution eq 'use_typed') {
 6002: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6003: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6004: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6005: 	}
 6006: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6007: 	    $args{'CODE_ignore_dup'}=1;
 6008: 	}
 6009: 	$args{'CODE'}=$newCODE;
 6010: 	($line,$err,$errmsg)=
 6011: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6012: 				     'CODE',\%args);
 6013:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6014: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6015: 	    ($line,$err,$errmsg)=
 6016: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6017: 					 $which,'answer',
 6018: 					 { 'question'=>$question,
 6019: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6020:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6021: 	    if ($err) { last; }
 6022: 	}
 6023:     }
 6024:     if ($err) {
 6025: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
 6026:     } else {
 6027: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 6028: 	&scantron_putfile($scanlines,$scan_data);
 6029:     }
 6030: }
 6031: 
 6032: =pod
 6033: 
 6034: =item reset_skipping_status
 6035: 
 6036:    Forgets the current set of remember skipped scanlines (and thus
 6037:    reverts back to considering all lines in the
 6038:    scantron_skipped_<filename> file)
 6039: 
 6040: =cut
 6041: 
 6042: sub reset_skipping_status {
 6043:     my ($scanlines,$scan_data)=&scantron_getfile();
 6044:     &scan_data($scan_data,'remember_skipping',undef,1);
 6045:     &scantron_putfile(undef,$scan_data);
 6046: }
 6047: 
 6048: =pod
 6049: 
 6050: =item start_skipping
 6051: 
 6052:    Marks a scanline to be skipped. 
 6053: 
 6054: =cut
 6055: 
 6056: sub start_skipping {
 6057:     my ($scan_data,$i)=@_;
 6058:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6059:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6060: 	$remembered{$i}=2;
 6061:     } else {
 6062: 	$remembered{$i}=1;
 6063:     }
 6064:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6065: }
 6066: 
 6067: =pod
 6068: 
 6069: =item should_be_skipped
 6070: 
 6071:    Checks whether a scanline should be skipped.
 6072: 
 6073: =cut
 6074: 
 6075: sub should_be_skipped {
 6076:     my ($scanlines,$scan_data,$i)=@_;
 6077:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6078: 	# not redoing old skips
 6079: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6080: 	return 0;
 6081:     }
 6082:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6083: 
 6084:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6085: 	return 0;
 6086:     }
 6087:     return 1;
 6088: }
 6089: 
 6090: =pod
 6091: 
 6092: =item remember_current_skipped
 6093: 
 6094:    Discovers what scanlines are in the scantron_skipped_<filename>
 6095:    file and remembers them into scan_data for later use.
 6096: 
 6097: =cut
 6098: 
 6099: sub remember_current_skipped {
 6100:     my ($scanlines,$scan_data)=&scantron_getfile();
 6101:     my %to_remember;
 6102:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6103: 	if ($scanlines->{'skipped'}[$i]) {
 6104: 	    $to_remember{$i}=1;
 6105: 	}
 6106:     }
 6107: 
 6108:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6109:     &scantron_putfile(undef,$scan_data);
 6110: }
 6111: 
 6112: =pod
 6113: 
 6114: =item check_for_error
 6115: 
 6116:     Checks if there was an error when attempting to remove a specific
 6117:     scantron_.. bubble sheet data file. Prints out an error if
 6118:     something went wrong.
 6119: 
 6120: =cut
 6121: 
 6122: sub check_for_error {
 6123:     my ($r,$result)=@_;
 6124:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6125: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6126:     }
 6127: }
 6128: 
 6129: =pod
 6130: 
 6131: =item scantron_warning_screen
 6132: 
 6133:    Interstitial screen to make sure the operator has selected the
 6134:    correct options before we start the validation phase.
 6135: 
 6136: =cut
 6137: 
 6138: sub scantron_warning_screen {
 6139:     my ($button_text)=@_;
 6140:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6141:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6142:     my $CODElist;
 6143:     if ($scantron_config{'CODElocation'} &&
 6144: 	$scantron_config{'CODEstart'} &&
 6145: 	$scantron_config{'CODElength'}) {
 6146: 	$CODElist=$env{'form.scantron_CODElist'};
 6147: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
 6148: 	$CODElist=
 6149: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6150: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6151:     }
 6152:     return ('
 6153: <p>
 6154: <span class="LC_warning">
 6155: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
 6156: </p>
 6157: <table>
 6158: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6159: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6160: '.$CODElist.'
 6161: </table>
 6162: <br />
 6163: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
 6164: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
 6165: 
 6166: <br />
 6167: ');
 6168: }
 6169: 
 6170: =pod
 6171: 
 6172: =item scantron_do_warning
 6173: 
 6174:    Check if the operator has picked something for all required
 6175:    fields. Error out if something is missing.
 6176: 
 6177: =cut
 6178: 
 6179: sub scantron_do_warning {
 6180:     my ($r,$symb)=@_;
 6181:     if (!$symb) {return '';}
 6182:     my $default_form_data=&defaultFormData($symb);
 6183:     $r->print(&scantron_form_start().$default_form_data);
 6184:     if ( $env{'form.selectpage'} eq '' ||
 6185: 	 $env{'form.scantron_selectfile'} eq '' ||
 6186: 	 $env{'form.scantron_format'} eq '' ) {
 6187: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
 6188: 	if ( $env{'form.selectpage'} eq '') {
 6189: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6190: 	} 
 6191: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6192: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a file that contains the student\'s response data.').'</span></p>');
 6193: 	} 
 6194: 	if ( $env{'form.scantron_format'} eq '') {
 6195: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a the format of the student\'s response data.').'</span></p>');
 6196: 	} 
 6197:     } else {
 6198: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
 6199: 	$r->print('
 6200: '.$warning.'
 6201: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6202: <input type="hidden" name="command" value="scantron_validate" />
 6203: ');
 6204:     }
 6205:     $r->print("</form><br />");
 6206:     return '';
 6207: }
 6208: 
 6209: =pod
 6210: 
 6211: =item scantron_form_start
 6212: 
 6213:     html hidden input for remembering all selected grading options
 6214: 
 6215: =cut
 6216: 
 6217: sub scantron_form_start {
 6218:     my ($max_bubble)=@_;
 6219:     my $result= <<SCANTRONFORM;
 6220: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6221:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6222:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6223:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6224:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6225:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6226:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6227:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6228:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6229:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6230: SCANTRONFORM
 6231: 
 6232:   my $line = 0;
 6233:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6234:        my $chunk =
 6235: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6236:        $chunk .=
 6237: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6238:        $chunk .= 
 6239:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6240:        $chunk .=
 6241:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6242:        $result .= $chunk;
 6243:        $line++;
 6244:    }
 6245:     return $result;
 6246: }
 6247: 
 6248: =pod
 6249: 
 6250: =item scantron_validate_file
 6251: 
 6252:     Dispatch routine for doing validation of a bubble sheet data file.
 6253: 
 6254:     Also processes any necessary information resets that need to
 6255:     occur before validation begins (ignore previous corrections,
 6256:     restarting the skipped records processing)
 6257: 
 6258: =cut
 6259: 
 6260: sub scantron_validate_file {
 6261:     my ($r,$symb) = @_;
 6262:     if (!$symb) {return '';}
 6263:     my $default_form_data=&defaultFormData($symb);
 6264:     
 6265:     # do the detection of only doing skipped records first befroe we delete
 6266:     # them when doing the corrections reset
 6267:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6268: 	&reset_skipping_status();
 6269:     }
 6270:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6271: 	&remember_current_skipped();
 6272: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6273:     }
 6274: 
 6275:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6276: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6277: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6278: 	&check_for_error($r,&scantron_remove_scan_data());
 6279: 	$env{'form.scantron_options_ignore'}='done';
 6280:     }
 6281: 
 6282:     if ($env{'form.scantron_corrections'}) {
 6283: 	&scantron_process_corrections($r);
 6284:     }
 6285:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6286:     #get the student pick code ready
 6287:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6288:     my $nav_error;
 6289:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
 6290:     if ($nav_error) {
 6291:         $r->print(&navmap_errormsg());
 6292:         return '';
 6293:     }
 6294:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6295:     $r->print($result);
 6296:     
 6297:     my @validate_phases=( 'sequence',
 6298: 			  'ID',
 6299: 			  'CODE',
 6300: 			  'doublebubble',
 6301: 			  'missingbubbles');
 6302:     if (!$env{'form.validatepass'}) {
 6303: 	$env{'form.validatepass'} = 0;
 6304:     }
 6305:     my $currentphase=$env{'form.validatepass'};
 6306: 
 6307: 
 6308:     my $stop=0;
 6309:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6310: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6311: 	$r->rflush();
 6312: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6313: 	{
 6314: 	    no strict 'refs';
 6315: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6316: 	}
 6317:     }
 6318:     if (!$stop) {
 6319: 	my $warning=&scantron_warning_screen('Start Grading');
 6320: 	$r->print(&mt('Validation process complete.').'<br />'.
 6321:                   $warning.
 6322:                   &mt('Perform verification for each student after storage of submissions?').
 6323:                   '&nbsp;<span class="LC_nobreak"><label>'.
 6324:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 6325:                   ('&nbsp;'x3).'<label>'.
 6326:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 6327:                   '</label></span><br />'.
 6328:                   &mt('Grading will take longer if you use verification.').'<br />'.
 6329:                   &mt("Alternatively, the 'Review bubblesheet data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
 6330:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 6331:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 6332:     } else {
 6333: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6334: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6335:     }
 6336:     if ($stop) {
 6337: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6338: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 6339: 	    $r->print(' '.&mt('this error').' <br />');
 6340: 
 6341: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
 6342: 	} else {
 6343:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6344: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 6345:             } else {
 6346:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 6347:             }
 6348: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6349: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6350: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6351: 	}
 6352:     }
 6353:     $r->print(" </form><br />");
 6354:     return '';
 6355: }
 6356: 
 6357: 
 6358: =pod
 6359: 
 6360: =item scantron_remove_file
 6361: 
 6362:    Removes the requested bubble sheet data file, makes sure that
 6363:    scantron_original_<filename> is never removed
 6364: 
 6365: 
 6366: =cut
 6367: 
 6368: sub scantron_remove_file {
 6369:     my ($which)=@_;
 6370:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6371:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6372:     my $file='scantron_';
 6373:     if ($which eq 'corrected' || $which eq 'skipped') {
 6374: 	$file.=$which.'_';
 6375:     } else {
 6376: 	return 'refused';
 6377:     }
 6378:     $file.=$env{'form.scantron_selectfile'};
 6379:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6380: }
 6381: 
 6382: 
 6383: =pod
 6384: 
 6385: =item scantron_remove_scan_data
 6386: 
 6387:    Removes all scan_data correction for the requested bubble sheet
 6388:    data file.  (In the case that both the are doing skipped records we need
 6389:    to remember the old skipped lines for the time being so that element
 6390:    persists for a while.)
 6391: 
 6392: =cut
 6393: 
 6394: sub scantron_remove_scan_data {
 6395:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6396:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6397:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6398:     my @todelete;
 6399:     my $filename=$env{'form.scantron_selectfile'};
 6400:     foreach my $key (@keys) {
 6401: 	if ($key=~/^\Q$filename\E_/) {
 6402: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6403: 		$key=~/remember_skipping/) {
 6404: 		next;
 6405: 	    }
 6406: 	    push(@todelete,$key);
 6407: 	}
 6408:     }
 6409:     my $result;
 6410:     if (@todelete) {
 6411: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6412: 				       \@todelete,$cdom,$cname);
 6413:     } else {
 6414: 	$result = 'ok';
 6415:     }
 6416:     return $result;
 6417: }
 6418: 
 6419: 
 6420: =pod
 6421: 
 6422: =item scantron_getfile
 6423: 
 6424:     Fetches the requested bubble sheet data file (all 3 versions), and
 6425:     the scan_data hash
 6426:   
 6427:   Arguments:
 6428:     None
 6429: 
 6430:   Returns:
 6431:     2 hash references
 6432: 
 6433:      - first one has 
 6434:          orig      -
 6435:          corrected -
 6436:          skipped   -  each of which points to an array ref of the specified
 6437:                       file broken up into individual lines
 6438:          count     - number of scanlines
 6439:  
 6440:      - second is the scan_data hash possible keys are
 6441:        ($number refers to scanline numbered $number and thus the key affects
 6442:         only that scanline
 6443:         $bubline refers to the specific bubble line element and the aspects
 6444:         refers to that specific bubble line element)
 6445: 
 6446:        $number.user - username:domain to use
 6447:        $number.CODE_ignore_dup 
 6448:                     - ignore the duplicate CODE error 
 6449:        $number.useCODE
 6450:                     - use the CODE in the scanline as is
 6451:        $number.no_bubble.$bubline
 6452:                     - it is valid that there is no bubbled in bubble
 6453:                       at $number $bubline
 6454:        remember_skipping
 6455:                     - a frozen hash containing keys of $number and values
 6456:                       of either 
 6457:                         1 - we are on a 'do skipped records pass' and plan
 6458:                             on processing this line
 6459:                         2 - we are on a 'do skipped records pass' and this
 6460:                             scanline has been marked to skip yet again
 6461: 
 6462: =cut
 6463: 
 6464: sub scantron_getfile {
 6465:     #FIXME really would prefer a scantron directory
 6466:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6467:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6468:     my $lines;
 6469:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6470: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 6471:     my %scanlines;
 6472:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 6473:     my $temp=$scanlines{'orig'};
 6474:     $scanlines{'count'}=$#$temp;
 6475: 
 6476:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6477: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 6478:     if ($lines eq '-1') {
 6479: 	$scanlines{'corrected'}=[];
 6480:     } else {
 6481: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 6482:     }
 6483:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6484: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 6485:     if ($lines eq '-1') {
 6486: 	$scanlines{'skipped'}=[];
 6487:     } else {
 6488: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 6489:     }
 6490:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 6491:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 6492:     my %scan_data = @tmp;
 6493:     return (\%scanlines,\%scan_data);
 6494: }
 6495: 
 6496: =pod
 6497: 
 6498: =item lonnet_putfile
 6499: 
 6500:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 6501: 
 6502:  Arguments:
 6503:    $contents - data to store
 6504:    $filename - filename to store $contents into
 6505: 
 6506:  Returns:
 6507:    result value from &Apache::lonnet::finishuserfileupload
 6508: 
 6509: =cut
 6510: 
 6511: sub lonnet_putfile {
 6512:     my ($contents,$filename)=@_;
 6513:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6514:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6515:     $env{'form.sillywaytopassafilearound'}=$contents;
 6516:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 6517: 
 6518: }
 6519: 
 6520: =pod
 6521: 
 6522: =item scantron_putfile
 6523: 
 6524:     Stores the current version of the bubble sheet data files, and the
 6525:     scan_data hash. (Does not modify the original version only the
 6526:     corrected and skipped versions.
 6527: 
 6528:  Arguments:
 6529:     $scanlines - hash ref that looks like the first return value from
 6530:                  &scantron_getfile()
 6531:     $scan_data - hash ref that looks like the second return value from
 6532:                  &scantron_getfile()
 6533: 
 6534: =cut
 6535: 
 6536: sub scantron_putfile {
 6537:     my ($scanlines,$scan_data) = @_;
 6538:     #FIXME really would prefer a scantron directory
 6539:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6540:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6541:     if ($scanlines) {
 6542: 	my $prefix='scantron_';
 6543: # no need to update orig, shouldn't change
 6544: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 6545: #		    $env{'form.scantron_selectfile'});
 6546: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 6547: 			$prefix.'corrected_'.
 6548: 			$env{'form.scantron_selectfile'});
 6549: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 6550: 			$prefix.'skipped_'.
 6551: 			$env{'form.scantron_selectfile'});
 6552:     }
 6553:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 6554: }
 6555: 
 6556: =pod
 6557: 
 6558: =item scantron_get_line
 6559: 
 6560:    Returns the correct version of the scanline
 6561: 
 6562:  Arguments:
 6563:     $scanlines - hash ref that looks like the first return value from
 6564:                  &scantron_getfile()
 6565:     $scan_data - hash ref that looks like the second return value from
 6566:                  &scantron_getfile()
 6567:     $i         - number of the requested line (starts at 0)
 6568: 
 6569:  Returns:
 6570:    A scanline, (either the original or the corrected one if it
 6571:    exists), or undef if the requested scanline should be
 6572:    skipped. (Either because it's an skipped scanline, or it's an
 6573:    unskipped scanline and we are not doing a 'do skipped scanlines'
 6574:    pass.
 6575: 
 6576: =cut
 6577: 
 6578: sub scantron_get_line {
 6579:     my ($scanlines,$scan_data,$i)=@_;
 6580:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 6581:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 6582:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 6583:     return $scanlines->{'orig'}[$i]; 
 6584: }
 6585: 
 6586: =pod
 6587: 
 6588: =item scantron_todo_count
 6589: 
 6590:     Counts the number of scanlines that need processing.
 6591: 
 6592:  Arguments:
 6593:     $scanlines - hash ref that looks like the first return value from
 6594:                  &scantron_getfile()
 6595:     $scan_data - hash ref that looks like the second return value from
 6596:                  &scantron_getfile()
 6597: 
 6598:  Returns:
 6599:     $count - number of scanlines to process
 6600: 
 6601: =cut
 6602: 
 6603: sub get_todo_count {
 6604:     my ($scanlines,$scan_data)=@_;
 6605:     my $count=0;
 6606:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6607: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6608: 	if ($line=~/^[\s\cz]*$/) { next; }
 6609: 	$count++;
 6610:     }
 6611:     return $count;
 6612: }
 6613: 
 6614: =pod
 6615: 
 6616: =item scantron_put_line
 6617: 
 6618:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
 6619:     data file.
 6620: 
 6621:  Arguments:
 6622:     $scanlines - hash ref that looks like the first return value from
 6623:                  &scantron_getfile()
 6624:     $scan_data - hash ref that looks like the second return value from
 6625:                  &scantron_getfile()
 6626:     $i         - line number to update
 6627:     $newline   - contents of the updated scanline
 6628:     $skip      - if true make the line for skipping and update the
 6629:                  'skipped' file
 6630: 
 6631: =cut
 6632: 
 6633: sub scantron_put_line {
 6634:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 6635:     if ($skip) {
 6636: 	$scanlines->{'skipped'}[$i]=$newline;
 6637: 	&start_skipping($scan_data,$i);
 6638: 	return;
 6639:     }
 6640:     $scanlines->{'corrected'}[$i]=$newline;
 6641: }
 6642: 
 6643: =pod
 6644: 
 6645: =item scantron_clear_skip
 6646: 
 6647:    Remove a line from the 'skipped' file
 6648: 
 6649:  Arguments:
 6650:     $scanlines - hash ref that looks like the first return value from
 6651:                  &scantron_getfile()
 6652:     $scan_data - hash ref that looks like the second return value from
 6653:                  &scantron_getfile()
 6654:     $i         - line number to update
 6655: 
 6656: =cut
 6657: 
 6658: sub scantron_clear_skip {
 6659:     my ($scanlines,$scan_data,$i)=@_;
 6660:     if (exists($scanlines->{'skipped'}[$i])) {
 6661: 	undef($scanlines->{'skipped'}[$i]);
 6662: 	return 1;
 6663:     }
 6664:     return 0;
 6665: }
 6666: 
 6667: =pod
 6668: 
 6669: =item scantron_filter_not_exam
 6670: 
 6671:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 6672:    filter out resources that are not marked as 'exam' mode
 6673: 
 6674: =cut
 6675: 
 6676: sub scantron_filter_not_exam {
 6677:     my ($curres)=@_;
 6678:     
 6679:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 6680: 	# if the user has asked to not have either hidden
 6681: 	# or 'randomout' controlled resources to be graded
 6682: 	# don't include them
 6683: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6684: 	    && $curres->randomout) {
 6685: 	    return 0;
 6686: 	}
 6687: 	return 1;
 6688:     }
 6689:     return 0;
 6690: }
 6691: 
 6692: =pod
 6693: 
 6694: =item scantron_validate_sequence
 6695: 
 6696:     Validates the selected sequence, checking for resource that are
 6697:     not set to exam mode.
 6698: 
 6699: =cut
 6700: 
 6701: sub scantron_validate_sequence {
 6702:     my ($r,$currentphase) = @_;
 6703: 
 6704:     my $navmap=Apache::lonnavmaps::navmap->new();
 6705:     unless (ref($navmap)) {
 6706:         $r->print(&navmap_errormsg());
 6707:         return (1,$currentphase);
 6708:     }
 6709:     my (undef,undef,$sequence)=
 6710: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6711: 
 6712:     my $map=$navmap->getResourceByUrl($sequence);
 6713: 
 6714:     $r->print('<input type="hidden" name="validate_sequence_exam"
 6715:                                     value="ignore" />');
 6716:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 6717: 	my @resources=
 6718: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 6719: 	if (@resources) {
 6720: 	    $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>");
 6721: 	    return (1,$currentphase);
 6722: 	}
 6723:     }
 6724: 
 6725:     return (0,$currentphase+1);
 6726: }
 6727: 
 6728: 
 6729: 
 6730: sub scantron_validate_ID {
 6731:     my ($r,$currentphase) = @_;
 6732:     
 6733:     #get student info
 6734:     my $classlist=&Apache::loncoursedata::get_classlist();
 6735:     my %idmap=&username_to_idmap($classlist);
 6736: 
 6737:     #get scantron line setup
 6738:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6739:     my ($scanlines,$scan_data)=&scantron_getfile();
 6740: 
 6741:     my $nav_error;
 6742:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble_lines.. array.
 6743:     if ($nav_error) {
 6744:         $r->print(&navmap_errormsg());
 6745:         return(1,$currentphase);
 6746:     }
 6747: 
 6748:     my %found=('ids'=>{},'usernames'=>{});
 6749:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6750: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6751: 	if ($line=~/^[\s\cz]*$/) { next; }
 6752: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6753: 						 $scan_data);
 6754: 	my $id=$$scan_record{'scantron.ID'};
 6755: 	my $found;
 6756: 	foreach my $checkid (keys(%idmap)) {
 6757: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 6758: 	}
 6759: 	if ($found) {
 6760: 	    my $username=$idmap{$found};
 6761: 	    if ($found{'ids'}{$found}) {
 6762: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6763: 					 $line,'duplicateID',$found);
 6764: 		return(1,$currentphase);
 6765: 	    } elsif ($found{'usernames'}{$username}) {
 6766: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6767: 					 $line,'duplicateID',$username);
 6768: 		return(1,$currentphase);
 6769: 	    }
 6770: 	    #FIXME store away line we previously saw the ID on to use above
 6771: 	    $found{'ids'}{$found}++;
 6772: 	    $found{'usernames'}{$username}++;
 6773: 	} else {
 6774: 	    if ($id =~ /^\s*$/) {
 6775: 		my $username=&scan_data($scan_data,"$i.user");
 6776: 		if (defined($username) && $found{'usernames'}{$username}) {
 6777: 		    &scantron_get_correction($r,$i,$scan_record,
 6778: 					     \%scantron_config,
 6779: 					     $line,'duplicateID',$username);
 6780: 		    return(1,$currentphase);
 6781: 		} elsif (!defined($username)) {
 6782: 		    &scantron_get_correction($r,$i,$scan_record,
 6783: 					     \%scantron_config,
 6784: 					     $line,'incorrectID');
 6785: 		    return(1,$currentphase);
 6786: 		}
 6787: 		$found{'usernames'}{$username}++;
 6788: 	    } else {
 6789: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6790: 					 $line,'incorrectID');
 6791: 		return(1,$currentphase);
 6792: 	    }
 6793: 	}
 6794:     }
 6795: 
 6796:     return (0,$currentphase+1);
 6797: }
 6798: 
 6799: 
 6800: sub scantron_get_correction {
 6801:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
 6802: #FIXME in the case of a duplicated ID the previous line, probably need
 6803: #to show both the current line and the previous one and allow skipping
 6804: #the previous one or the current one
 6805: 
 6806:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 6807: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6808: 			    " for PaperID <tt>[_1]</tt>",
 6809: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
 6810:     } else {
 6811: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6812: 			    " in scanline [_1] <pre>[_2]</pre>",
 6813: 			    $i,$line)."</p> \n");
 6814:     }
 6815:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
 6816: 			  "The name on the paper is [_2],[_3]",
 6817: 			  $$scan_record{'scantron.ID'},
 6818: 			  $$scan_record{'scantron.LastName'},
 6819: 			  $$scan_record{'scantron.FirstName'})."</p>";
 6820: 
 6821:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 6822:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 6823:                            # Array populated for doublebubble or
 6824:     my @lines_to_correct;  # missingbubble errors to build javascript
 6825:                            # to validate radio button checking   
 6826: 
 6827:     if ($error =~ /ID$/) {
 6828: 	if ($error eq 'incorrectID') {
 6829: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
 6830: 		      "</p>\n");
 6831: 	} elsif ($error eq 'duplicateID') {
 6832: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 6833: 	}
 6834: 	$r->print($message);
 6835: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6836: 	$r->print("\n<ul><li> ");
 6837: 	#FIXME it would be nice if this sent back the user ID and
 6838: 	#could do partial userID matches
 6839: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 6840: 				       'scantron_username','scantron_domain'));
 6841: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 6842: 	$r->print("\n@".
 6843: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 6844: 
 6845: 	$r->print('</li>');
 6846:     } elsif ($error =~ /CODE$/) {
 6847: 	if ($error eq 'incorrectCODE') {
 6848: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 6849: 	} elsif ($error eq 'duplicateCODE') {
 6850: 	    $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");
 6851: 	}
 6852: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
 6853: 			    $$scan_record{'scantron.CODE'})."<br />\n");
 6854: 	$r->print($message);
 6855: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6856: 	$r->print("\n<br /> ");
 6857: 	my $i=0;
 6858: 	if ($error eq 'incorrectCODE' 
 6859: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 6860: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 6861: 	    if ($closest > 0) {
 6862: 		foreach my $testcode (@{$closest}) {
 6863: 		    my $checked='';
 6864: 		    if (!$i) { $checked=' checked="checked"'; }
 6865: 		    $r->print("
 6866:    <label>
 6867:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 6868:        ".&mt("Use the similar CODE [_1] instead.",
 6869: 	    "<b><tt>".$testcode."</tt></b>")."
 6870:     </label>
 6871:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 6872: 		    $r->print("\n<br />");
 6873: 		    $i++;
 6874: 		}
 6875: 	    }
 6876: 	}
 6877: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 6878: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 6879: 	    $r->print("
 6880:     <label>
 6881:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 6882:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
 6883: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 6884:     </label>");
 6885: 	    $r->print("\n<br />");
 6886: 	}
 6887: 
 6888: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
 6889: function change_radio(field) {
 6890:     var slct=document.scantronupload.scantron_CODE_resolution;
 6891:     var i;
 6892:     for (i=0;i<slct.length;i++) {
 6893:         if (slct[i].value==field) { slct[i].checked=true; }
 6894:     }
 6895: }
 6896: ENDSCRIPT
 6897: 	my $href="/adm/pickcode?".
 6898: 	   "form=".&escape("scantronupload").
 6899: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 6900: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 6901: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 6902: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 6903: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 6904: 	    $r->print("
 6905:     <label>
 6906:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 6907:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 6908: 	     "<a target='_blank' href='$href'>","</a>")."
 6909:     </label> 
 6910:     ".&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\')" />'));
 6911: 	    $r->print("\n<br />");
 6912: 	}
 6913: 	$r->print("
 6914:     <label>
 6915:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 6916:        ".&mt("Use [_1] as the CODE.",
 6917: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 6918: 	$r->print("\n<br /><br />");
 6919:     } elsif ($error eq 'doublebubble') {
 6920: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 6921: 
 6922: 	# The form field scantron_questions is acutally a list of line numbers.
 6923: 	# represented by this form so:
 6924: 
 6925: 	my $line_list = &questions_to_line_list($arg);
 6926: 
 6927: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6928: 		  $line_list.'" />');
 6929: 	$r->print($message);
 6930: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 6931: 	foreach my $question (@{$arg}) {
 6932: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6933:                                                    $scan_record, $error);
 6934:             push(@lines_to_correct,@linenums);
 6935: 	}
 6936:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6937:     } elsif ($error eq 'missingbubble') {
 6938: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
 6939: 	$r->print($message);
 6940: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 6941: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 6942: 
 6943: 	# The form field scantron_questions is actually a list of line numbers not
 6944: 	# a list of question numbers. Therefore:
 6945: 	#
 6946: 	
 6947: 	my $line_list = &questions_to_line_list($arg);
 6948: 
 6949: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6950: 		  $line_list.'" />');
 6951: 	foreach my $question (@{$arg}) {
 6952: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6953:                                                    $scan_record, $error);
 6954:             push(@lines_to_correct,@linenums);
 6955: 	}
 6956:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6957:     } else {
 6958: 	$r->print("\n<ul>");
 6959:     }
 6960:     $r->print("\n</li></ul>");
 6961: }
 6962: 
 6963: sub verify_bubbles_checked {
 6964:     my (@ansnums) = @_;
 6965:     my $ansnumstr = join('","',@ansnums);
 6966:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 6967:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
 6968: function verify_bubble_radio(form) {
 6969:     var ansnumArray = new Array ("$ansnumstr");
 6970:     var need_bubble_count = 0;
 6971:     for (var i=0; i<ansnumArray.length; i++) {
 6972:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 6973:             var bubble_picked = 0; 
 6974:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 6975:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 6976:                     bubble_picked = 1;
 6977:                 }
 6978:             }
 6979:             if (bubble_picked == 0) {
 6980:                 need_bubble_count ++;
 6981:             }
 6982:         }
 6983:     }
 6984:     if (need_bubble_count) {
 6985:         alert("$warning");
 6986:         return;
 6987:     }
 6988:     form.submit(); 
 6989: }
 6990: ENDSCRIPT
 6991:     return $output;
 6992: }
 6993: 
 6994: =pod
 6995: 
 6996: =item  questions_to_line_list
 6997: 
 6998: Converts a list of questions into a string of comma separated
 6999: line numbers in the answer sheet used by the questions.  This is
 7000: used to fill in the scantron_questions form field.
 7001: 
 7002:   Arguments:
 7003:      questions    - Reference to an array of questions.
 7004: 
 7005: =cut
 7006: 
 7007: 
 7008: sub questions_to_line_list {
 7009:     my ($questions) = @_;
 7010:     my @lines;
 7011: 
 7012:     foreach my $item (@{$questions}) {
 7013:         my $question = $item;
 7014:         my ($first,$count,$last);
 7015:         if ($item =~ /^(\d+)\.(\d+)$/) {
 7016:             $question = $1;
 7017:             my $subquestion = $2;
 7018:             $first = $first_bubble_line{$question-1} + 1;
 7019:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7020:             my $subcount = 1;
 7021:             while ($subcount<$subquestion) {
 7022:                 $first += $subans[$subcount-1];
 7023:                 $subcount ++;
 7024:             }
 7025:             $count = $subans[$subquestion-1];
 7026:         } else {
 7027: 	    $first   = $first_bubble_line{$question-1} + 1;
 7028: 	    $count   = $bubble_lines_per_response{$question-1};
 7029:         }
 7030:         $last = $first+$count-1;
 7031:         push(@lines, ($first..$last));
 7032:     }
 7033:     return join(',', @lines);
 7034: }
 7035: 
 7036: =pod 
 7037: 
 7038: =item prompt_for_corrections
 7039: 
 7040: Prompts for a potentially multiline correction to the
 7041: user's bubbling (factors out common code from scantron_get_correction
 7042: for multi and missing bubble cases).
 7043: 
 7044:  Arguments:
 7045:    $r           - Apache request object.
 7046:    $question    - The question number to prompt for.
 7047:    $scan_config - The scantron file configuration hash.
 7048:    $scan_record - Reference to the hash that has the the parsed scanlines.
 7049:    $error       - Type of error
 7050: 
 7051:  Implicit inputs:
 7052:    %bubble_lines_per_response   - Starting line numbers for each question.
 7053:                                   Numbered from 0 (but question numbers are from
 7054:                                   1.
 7055:    %first_bubble_line           - Starting bubble line for each question.
 7056:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 7057:                                   type problems render as separate sub-questions, 
 7058:                                   in exam mode. This hash contains a 
 7059:                                   comma-separated list of the lines per 
 7060:                                   sub-question.
 7061:    %responsetype_per_response   - essayresponse, formularesponse,
 7062:                                   stringresponse, imageresponse, reactionresponse,
 7063:                                   and organicresponse type problem parts can have
 7064:                                   multiple lines per response if the weight
 7065:                                   assigned exceeds 10.  In this case, only
 7066:                                   one bubble per line is permitted, but more 
 7067:                                   than one line might contain bubbles, e.g.
 7068:                                   bubbling of: line 1 - J, line 2 - J, 
 7069:                                   line 3 - B would assign 22 points.  
 7070: 
 7071: =cut
 7072: 
 7073: sub prompt_for_corrections {
 7074:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
 7075:     my ($current_line,$lines);
 7076:     my @linenums;
 7077:     my $questionnum = $question;
 7078:     if ($question =~ /^(\d+)\.(\d+)$/) {
 7079:         $question = $1;
 7080:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7081:         my $subquestion = $2;
 7082:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7083:         my $subcount = 1;
 7084:         while ($subcount<$subquestion) {
 7085:             $current_line += $subans[$subcount-1];
 7086:             $subcount ++;
 7087:         }
 7088:         $lines = $subans[$subquestion-1];
 7089:     } else {
 7090:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7091:         $lines        = $bubble_lines_per_response{$question-1};
 7092:     }
 7093:     if ($lines > 1) {
 7094:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7095:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
 7096:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
 7097:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
 7098:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
 7099:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
 7100:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
 7101:             $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 />');
 7102:         } else {
 7103:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7104:         }
 7105:     }
 7106:     for (my $i =0; $i < $lines; $i++) {
 7107:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7108: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
 7109: 	        		  $questionnum,$error,split('', $selected));
 7110:         push(@linenums,$current_line);
 7111: 	$current_line++;
 7112:     }
 7113:     if ($lines > 1) {
 7114: 	$r->print("<hr /><br />");
 7115:     }
 7116:     return @linenums;
 7117: }
 7118: 
 7119: =pod
 7120: 
 7121: =item scantron_bubble_selector
 7122:   
 7123:    Generates the html radiobuttons to correct a single bubble line
 7124:    possibly showing the existing the selected bubbles if known
 7125: 
 7126:  Arguments:
 7127:     $r           - Apache request object
 7128:     $scan_config - hash from &get_scantron_config()
 7129:     $line        - Number of the line being displayed.
 7130:     $questionnum - Question number (may include subquestion)
 7131:     $error       - Type of error.
 7132:     @selected    - Array of bubbles picked on this line.
 7133: 
 7134: =cut
 7135: 
 7136: sub scantron_bubble_selector {
 7137:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7138:     my $max=$$scan_config{'Qlength'};
 7139: 
 7140:     my $scmode=$$scan_config{'Qon'};
 7141:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
 7142: 
 7143:     my @alphabet=('A'..'Z');
 7144:     $r->print(&Apache::loncommon::start_data_table().
 7145:               &Apache::loncommon::start_data_table_row());
 7146:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7147:     for (my $i=0;$i<$max+1;$i++) {
 7148: 	$r->print("\n".'<td align="center">');
 7149: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7150: 	else { $r->print('&nbsp;'); }
 7151: 	$r->print('</td>');
 7152:     }
 7153:     $r->print(&Apache::loncommon::end_data_table_row().
 7154:               &Apache::loncommon::start_data_table_row());
 7155:     for (my $i=0;$i<$max;$i++) {
 7156: 	$r->print("\n".
 7157: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7158: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7159:     }
 7160:     my $nobub_checked = ' ';
 7161:     if ($error eq 'missingbubble') {
 7162:         $nobub_checked = ' checked = "checked" ';
 7163:     }
 7164:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7165: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7166:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7167:               $line.'" value="'.$questionnum.'" /></td>');
 7168:     $r->print(&Apache::loncommon::end_data_table_row().
 7169:               &Apache::loncommon::end_data_table());
 7170: }
 7171: 
 7172: =pod
 7173: 
 7174: =item num_matches
 7175: 
 7176:    Counts the number of characters that are the same between the two arguments.
 7177: 
 7178:  Arguments:
 7179:    $orig - CODE from the scanline
 7180:    $code - CODE to match against
 7181: 
 7182:  Returns:
 7183:    $count - integer count of the number of same characters between the
 7184:             two arguments
 7185: 
 7186: =cut
 7187: 
 7188: sub num_matches {
 7189:     my ($orig,$code) = @_;
 7190:     my @code=split(//,$code);
 7191:     my @orig=split(//,$orig);
 7192:     my $same=0;
 7193:     for (my $i=0;$i<scalar(@code);$i++) {
 7194: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7195:     }
 7196:     return $same;
 7197: }
 7198: 
 7199: =pod
 7200: 
 7201: =item scantron_get_closely_matching_CODEs
 7202: 
 7203:    Cycles through all CODEs and finds the set that has the greatest
 7204:    number of same characters as the provided CODE
 7205: 
 7206:  Arguments:
 7207:    $allcodes - hash ref returned by &get_codes()
 7208:    $CODE     - CODE from the current scanline
 7209: 
 7210:  Returns:
 7211:    2 element list
 7212:     - first elements is number of how closely matching the best fit is 
 7213:       (5 means best set has 5 matching characters)
 7214:     - second element is an arrary ref containing the set of valid CODEs
 7215:       that best fit the passed in CODE
 7216: 
 7217: =cut
 7218: 
 7219: sub scantron_get_closely_matching_CODEs {
 7220:     my ($allcodes,$CODE)=@_;
 7221:     my @CODEs;
 7222:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7223: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7224:     }
 7225: 
 7226:     return ($#CODEs,$CODEs[-1]);
 7227: }
 7228: 
 7229: =pod
 7230: 
 7231: =item get_codes
 7232: 
 7233:    Builds a hash which has keys of all of the valid CODEs from the selected
 7234:    set of remembered CODEs.
 7235: 
 7236:  Arguments:
 7237:   $old_name - name of the set of remembered CODEs
 7238:   $cdom     - domain of the course
 7239:   $cnum     - internal course name
 7240: 
 7241:  Returns:
 7242:   %allcodes - keys are the valid CODEs, values are all 1
 7243: 
 7244: =cut
 7245: 
 7246: sub get_codes {
 7247:     my ($old_name, $cdom, $cnum) = @_;
 7248:     if (!$old_name) {
 7249: 	$old_name=$env{'form.scantron_CODElist'};
 7250:     }
 7251:     if (!$cdom) {
 7252: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7253:     }
 7254:     if (!$cnum) {
 7255: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7256:     }
 7257:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7258: 				    $cdom,$cnum);
 7259:     my %allcodes;
 7260:     if ($result{"type\0$old_name"} eq 'number') {
 7261: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7262:     } else {
 7263: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7264:     }
 7265:     return %allcodes;
 7266: }
 7267: 
 7268: =pod
 7269: 
 7270: =item scantron_validate_CODE
 7271: 
 7272:    Validates all scanlines in the selected file to not have any
 7273:    invalid or underspecified CODEs and that none of the codes are
 7274:    duplicated if this was requested.
 7275: 
 7276: =cut
 7277: 
 7278: sub scantron_validate_CODE {
 7279:     my ($r,$currentphase) = @_;
 7280:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7281:     if ($scantron_config{'CODElocation'} &&
 7282: 	$scantron_config{'CODEstart'} &&
 7283: 	$scantron_config{'CODElength'}) {
 7284: 	if (!defined($env{'form.scantron_CODElist'})) {
 7285: 	    &FIXME_blow_up()
 7286: 	}
 7287:     } else {
 7288: 	return (0,$currentphase+1);
 7289:     }
 7290:     
 7291:     my %usedCODEs;
 7292: 
 7293:     my %allcodes=&get_codes();
 7294: 
 7295:     my $nav_error;
 7296:     &scantron_get_maxbubble(\$nav_error); # parse needs the lines per response array.
 7297:     if ($nav_error) {
 7298:         $r->print(&navmap_errormsg());
 7299:         return(1,$currentphase);
 7300:     }
 7301: 
 7302:     my ($scanlines,$scan_data)=&scantron_getfile();
 7303:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7304: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7305: 	if ($line=~/^[\s\cz]*$/) { next; }
 7306: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7307: 						 $scan_data);
 7308: 	my $CODE=$$scan_record{'scantron.CODE'};
 7309: 	my $error=0;
 7310: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7311: 	    &scantron_get_correction($r,$i,$scan_record,
 7312: 				     \%scantron_config,
 7313: 				     $line,'incorrectCODE',\%allcodes);
 7314: 	    return(1,$currentphase);
 7315: 	}
 7316: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7317: 	    && !$$scan_record{'scantron.useCODE'}) {
 7318: 	    &scantron_get_correction($r,$i,$scan_record,
 7319: 				     \%scantron_config,
 7320: 				     $line,'incorrectCODE',\%allcodes);
 7321: 	    return(1,$currentphase);
 7322: 	}
 7323: 	if (exists($usedCODEs{$CODE}) 
 7324: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 7325: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 7326: 	    &scantron_get_correction($r,$i,$scan_record,
 7327: 				     \%scantron_config,
 7328: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 7329: 	    return(1,$currentphase);
 7330: 	}
 7331: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 7332:     }
 7333:     return (0,$currentphase+1);
 7334: }
 7335: 
 7336: =pod
 7337: 
 7338: =item scantron_validate_doublebubble
 7339: 
 7340:    Validates all scanlines in the selected file to not have any
 7341:    bubble lines with multiple bubbles marked.
 7342: 
 7343: =cut
 7344: 
 7345: sub scantron_validate_doublebubble {
 7346:     my ($r,$currentphase) = @_;
 7347:     #get student info
 7348:     my $classlist=&Apache::loncoursedata::get_classlist();
 7349:     my %idmap=&username_to_idmap($classlist);
 7350: 
 7351:     #get scantron line setup
 7352:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7353:     my ($scanlines,$scan_data)=&scantron_getfile();
 7354:     my $nav_error;
 7355:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble line array.
 7356:     if ($nav_error) {
 7357:         $r->print(&navmap_errormsg());
 7358:         return(1,$currentphase);
 7359:     }
 7360: 
 7361:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7362: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7363: 	if ($line=~/^[\s\cz]*$/) { next; }
 7364: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7365: 						 $scan_data);
 7366: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 7367: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 7368: 				 'doublebubble',
 7369: 				 $$scan_record{'scantron.doubleerror'});
 7370:     	return (1,$currentphase);
 7371:     }
 7372:     return (0,$currentphase+1);
 7373: }
 7374: 
 7375: 
 7376: sub scantron_get_maxbubble {
 7377:     my ($nav_error) = @_;
 7378:     if (defined($env{'form.scantron_maxbubble'}) &&
 7379: 	$env{'form.scantron_maxbubble'}) {
 7380: 	&restore_bubble_lines();
 7381: 	return $env{'form.scantron_maxbubble'};
 7382:     }
 7383: 
 7384:     my (undef, undef, $sequence) =
 7385: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7386: 
 7387:     my $navmap=Apache::lonnavmaps::navmap->new();
 7388:     unless (ref($navmap)) {
 7389:         if (ref($nav_error)) {
 7390:             $$nav_error = 1;
 7391:         }
 7392:         return;
 7393:     }
 7394:     my $map=$navmap->getResourceByUrl($sequence);
 7395:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7396: 
 7397:     &Apache::lonxml::clear_problem_counter();
 7398: 
 7399:     my $uname       = $env{'user.name'};
 7400:     my $udom        = $env{'user.domain'};
 7401:     my $cid         = $env{'request.course.id'};
 7402:     my $total_lines = 0;
 7403:     %bubble_lines_per_response = ();
 7404:     %first_bubble_line         = ();
 7405:     %subdivided_bubble_lines   = ();
 7406:     %responsetype_per_response = ();
 7407: 
 7408:     my $response_number = 0;
 7409:     my $bubble_line     = 0;
 7410:     foreach my $resource (@resources) {
 7411:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
 7412:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 7413: 	    foreach my $part_id (@{$parts}) {
 7414:                 my $lines;
 7415: 
 7416: 	        # TODO - make this a persistent hash not an array.
 7417: 
 7418:                 # optionresponse, matchresponse and rankresponse type items 
 7419:                 # render as separate sub-questions in exam mode.
 7420:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 7421:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 7422:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 7423:                     my ($numbub,$numshown);
 7424:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 7425:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 7426:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 7427:                         }
 7428:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 7429:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 7430:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 7431:                         }
 7432:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 7433:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 7434:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 7435:                         }
 7436:                     }
 7437:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 7438:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 7439:                     }
 7440:                     my $bubbles_per_line = 10;
 7441:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
 7442:                     if (($numbub % $bubbles_per_line) != 0) {
 7443:                         $inner_bubble_lines++;
 7444:                     }
 7445:                     for (my $i=0; $i<$numshown; $i++) {
 7446:                         $subdivided_bubble_lines{$response_number} .= 
 7447:                             $inner_bubble_lines.',';
 7448:                     }
 7449:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 7450:                     $lines = $numshown * $inner_bubble_lines;
 7451:                 } else {
 7452:                     $lines = $analysis->{"$part_id.bubble_lines"};
 7453:                 } 
 7454: 
 7455:                 $first_bubble_line{$response_number} = $bubble_line;
 7456: 	        $bubble_lines_per_response{$response_number} = $lines;
 7457:                 $responsetype_per_response{$response_number} = 
 7458:                     $analysis->{$part_id.'.type'};
 7459: 	        $response_number++;
 7460: 
 7461: 	        $bubble_line +=  $lines;
 7462: 	        $total_lines +=  $lines;
 7463: 	    }
 7464:         }
 7465:     }
 7466:     &Apache::lonnet::delenv('scantron.');
 7467: 
 7468:     &save_bubble_lines();
 7469:     $env{'form.scantron_maxbubble'} =
 7470: 	$total_lines;
 7471:     return $env{'form.scantron_maxbubble'};
 7472: }
 7473: 
 7474: sub scantron_validate_missingbubbles {
 7475:     my ($r,$currentphase) = @_;
 7476:     #get student info
 7477:     my $classlist=&Apache::loncoursedata::get_classlist();
 7478:     my %idmap=&username_to_idmap($classlist);
 7479: 
 7480:     #get scantron line setup
 7481:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7482:     my ($scanlines,$scan_data)=&scantron_getfile();
 7483:     my $nav_error;
 7484:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
 7485:     if ($nav_error) {
 7486:         return(1,$currentphase);
 7487:     }
 7488:     if (!$max_bubble) { $max_bubble=2**31; }
 7489:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7490: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7491: 	if ($line=~/^[\s\cz]*$/) { next; }
 7492: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7493: 						 $scan_data);
 7494: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 7495: 	my @to_correct;
 7496: 	
 7497: 	# Probably here's where the error is...
 7498: 
 7499: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 7500:             my $lastbubble;
 7501:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 7502:                my $question = $1;
 7503:                my $subquestion = $2;
 7504:                if (!defined($first_bubble_line{$question -1})) { next; }
 7505:                my $first = $first_bubble_line{$question-1};
 7506:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7507:                my $subcount = 1;
 7508:                while ($subcount<$subquestion) {
 7509:                    $first += $subans[$subcount-1];
 7510:                    $subcount ++;
 7511:                }
 7512:                my $count = $subans[$subquestion-1];
 7513:                $lastbubble = $first + $count;
 7514:             } else {
 7515:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
 7516:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
 7517:             }
 7518:             if ($lastbubble > $max_bubble) { next; }
 7519: 	    push(@to_correct,$missing);
 7520: 	}
 7521: 	if (@to_correct) {
 7522: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7523: 				     $line,'missingbubble',\@to_correct);
 7524: 	    return (1,$currentphase);
 7525: 	}
 7526: 
 7527:     }
 7528:     return (0,$currentphase+1);
 7529: }
 7530: 
 7531: 
 7532: sub scantron_process_students {
 7533:     my ($r,$symb) = @_;
 7534: 
 7535:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7536:     if (!$symb) {
 7537: 	return '';
 7538:     }
 7539:     my $default_form_data=&defaultFormData($symb);
 7540: 
 7541:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7542:     my ($scanlines,$scan_data)=&scantron_getfile();
 7543:     my $classlist=&Apache::loncoursedata::get_classlist();
 7544:     my %idmap=&username_to_idmap($classlist);
 7545:     my $navmap=Apache::lonnavmaps::navmap->new();
 7546:     unless (ref($navmap)) {
 7547:         $r->print(&navmap_errormsg());
 7548:         return '';
 7549:     }  
 7550:     my $map=$navmap->getResourceByUrl($sequence);
 7551:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7552:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 7553:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 7554:                             \%grader_randomlists_by_symb);
 7555:     my $resource_error;
 7556:     foreach my $resource (@resources) {
 7557:         my $ressymb;
 7558:         if (ref($resource)) {
 7559:             $ressymb = $resource->symb();
 7560:         } else {
 7561:             $resource_error = 1;
 7562:             last;
 7563:         }
 7564:         my ($analysis,$parts) =
 7565:             &scantron_partids_tograde($resource,$env{'request.course.id'},
 7566:                                       $env{'user.name'},$env{'user.domain'},1);
 7567:         $grader_partids_by_symb{$ressymb} = $parts;
 7568:         if (ref($analysis) eq 'HASH') {
 7569:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7570:                 $grader_randomlists_by_symb{$ressymb} = 
 7571:                     $analysis->{'parts_withrandomlist'};
 7572:             }
 7573:         }
 7574:     }
 7575:     if ($resource_error) {
 7576:         $r->print(&navmap_errormsg());
 7577:         return '';
 7578:     }
 7579: 
 7580:     my ($uname,$udom);
 7581:     my $result= <<SCANTRONFORM;
 7582: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7583:   <input type="hidden" name="command" value="scantron_configphase" />
 7584:   $default_form_data
 7585: SCANTRONFORM
 7586:     $r->print($result);
 7587: 
 7588:     my @delayqueue;
 7589:     my (%completedstudents,%scandata);
 7590:     
 7591:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 7592:     my $count=&get_todo_count($scanlines,$scan_data);
 7593:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
 7594:  				    'Bubblesheet Progress',$count,
 7595: 				    'inline',undef,'scantronupload');
 7596:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 7597: 					  'Processing first student');
 7598:     $r->print('<br />');
 7599:     my $start=&Time::HiRes::time();
 7600:     my $i=-1;
 7601:     my $started;
 7602: 
 7603:     my $nav_error;
 7604:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
 7605:     if ($nav_error) {
 7606:         $r->print(&navmap_errormsg());
 7607:         return '';
 7608:     }
 7609: 
 7610:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 7611:     # the user and return.
 7612: 
 7613:     if ($ssi_error) {
 7614: 	$r->print("</form>");
 7615: 	&ssi_print_error($r);
 7616:         &Apache::lonnet::remove_lock($lock);
 7617: 	return '';		# Dunno why the other returns return '' rather than just returning.
 7618:     }
 7619: 
 7620:     my %lettdig = &letter_to_digits();
 7621:     my $numletts = scalar(keys(%lettdig));
 7622: 
 7623:     while ($i<$scanlines->{'count'}) {
 7624:  	($uname,$udom)=('','');
 7625:  	$i++;
 7626:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7627:  	if ($line=~/^[\s\cz]*$/) { next; }
 7628: 	if ($started) {
 7629: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 7630: 						     'last student');
 7631: 	}
 7632: 	$started=1;
 7633:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7634:  						 $scan_data);
 7635:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 7636:  					      \%idmap,$i)) {
 7637:   	    &scantron_add_delay(\@delayqueue,$line,
 7638:  				'Unable to find a student that matches',1);
 7639:  	    next;
 7640:   	}
 7641:  	if (exists $completedstudents{$uname}) {
 7642:  	    &scantron_add_delay(\@delayqueue,$line,
 7643:  				'Student '.$uname.' has multiple sheets',2);
 7644:  	    next;
 7645:  	}
 7646:   	($uname,$udom)=split(/:/,$uname);
 7647: 
 7648:         my (%partids_by_symb,$res_error);
 7649:         foreach my $resource (@resources) {
 7650:             my $ressymb;
 7651:             if (ref($resource)) {
 7652:                 $ressymb = $resource->symb();
 7653:             } else {
 7654:                 $res_error = 1;
 7655:                 last;
 7656:             }
 7657:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 7658:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 7659:                 my ($analysis,$parts) =
 7660:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
 7661:                 $partids_by_symb{$ressymb} = $parts;
 7662:             } else {
 7663:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 7664:             }
 7665:         }
 7666: 
 7667:         if ($res_error) {
 7668:             &scantron_add_delay(\@delayqueue,$line,
 7669:                                 'An error occurred while grading student '.$uname,2);
 7670:             next;
 7671:         }
 7672: 
 7673: 	&Apache::lonxml::clear_problem_counter();
 7674:   	&Apache::lonnet::appenv($scan_record);
 7675: 
 7676: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 7677: 	    &scantron_putfile($scanlines,$scan_data);
 7678: 	}
 7679: 	
 7680:         my $scancode;
 7681:         if ((exists($scan_record->{'scantron.CODE'})) &&
 7682:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 7683:             $scancode = $scan_record->{'scantron.CODE'};
 7684:         } else {
 7685:             $scancode = '';
 7686:         }
 7687: 
 7688:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7689:                                    \@resources,\%partids_by_symb) eq 'ssi_error') {
 7690:             $ssi_error = 0; # So end of handler error message does not trigger.
 7691:             $r->print("</form>");
 7692:             &ssi_print_error($r);
 7693:             &Apache::lonnet::remove_lock($lock);
 7694:             return '';      # Why return ''?  Beats me.
 7695:         }
 7696: 
 7697: 	$completedstudents{$uname}={'line'=>$line};
 7698:         if ($env{'form.verifyrecord'}) {
 7699:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 7700:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 7701:             chomp($studentdata);
 7702:             $studentdata =~ s/\r$//;
 7703:             my $studentrecord = '';
 7704:             my $counter = -1;
 7705:             foreach my $resource (@resources) {
 7706:                 my $ressymb = $resource->symb();
 7707:                 ($counter,my $recording) =
 7708:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7709:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 7710:                                              \%scantron_config,\%lettdig,$numletts);
 7711:                 $studentrecord .= $recording;
 7712:             }
 7713:             if ($studentrecord ne $studentdata) {
 7714:                 &Apache::lonxml::clear_problem_counter();
 7715:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7716:                                            \@resources,\%partids_by_symb) eq 'ssi_error') {
 7717:                     $ssi_error = 0; # So end of handler error message does not trigger.
 7718:                     $r->print("</form>");
 7719:                     &ssi_print_error($r);
 7720:                     &Apache::lonnet::remove_lock($lock);
 7721:                     delete($completedstudents{$uname});
 7722:                     return '';
 7723:                 }
 7724:                 $counter = -1;
 7725:                 $studentrecord = '';
 7726:                 foreach my $resource (@resources) {
 7727:                     my $ressymb = $resource->symb();
 7728:                     ($counter,my $recording) =
 7729:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7730:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 7731:                                                  \%scantron_config,\%lettdig,$numletts);
 7732:                     $studentrecord .= $recording;
 7733:                 }
 7734:                 if ($studentrecord ne $studentdata) {
 7735:                     $r->print('<p><span class="LC_error">');
 7736:                     if ($scancode eq '') {
 7737:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
 7738:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 7739:                     } else {
 7740:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
 7741:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 7742:                     }
 7743:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 7744:                               &Apache::loncommon::start_data_table_header_row()."\n".
 7745:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 7746:                               &Apache::loncommon::end_data_table_header_row()."\n".
 7747:                               &Apache::loncommon::start_data_table_row().
 7748:                               '<td>'.&mt('Bubble Sheet').'</td>'.
 7749:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
 7750:                               &Apache::loncommon::end_data_table_row().
 7751:                               &Apache::loncommon::start_data_table_row().
 7752:                               '<td>Stored submissions</td>'.
 7753:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
 7754:                               &Apache::loncommon::end_data_table_row().
 7755:                               &Apache::loncommon::end_data_table().'</p>');
 7756:                 } else {
 7757:                     $r->print('<br /><span class="LC_warning">'.
 7758:                              &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 />'.
 7759:                              &mt("As a consequence, this user's submission history records two tries.").
 7760:                                  '</span><br />');
 7761:                 }
 7762:             }
 7763:         }
 7764:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 7765:     } continue {
 7766: 	&Apache::lonxml::clear_problem_counter();
 7767: 	&Apache::lonnet::delenv('scantron.');
 7768:     }
 7769:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 7770:     &Apache::lonnet::remove_lock($lock);
 7771: #    my $lasttime = &Time::HiRes::time()-$start;
 7772: #    $r->print("<p>took $lasttime</p>");
 7773: 
 7774:     $r->print("</form>");
 7775:     return '';
 7776: }
 7777: 
 7778: sub graders_resources_pass {
 7779:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
 7780:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 7781:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 7782:         foreach my $resource (@{$resources}) {
 7783:             my $ressymb = $resource->symb();
 7784:             my ($analysis,$parts) =
 7785:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 7786:                                           $env{'user.name'},$env{'user.domain'},1);
 7787:             $grader_partids_by_symb->{$ressymb} = $parts;
 7788:             if (ref($analysis) eq 'HASH') {
 7789:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7790:                     $grader_randomlists_by_symb->{$ressymb} =
 7791:                         $analysis->{'parts_withrandomlist'};
 7792:                 }
 7793:             }
 7794:         }
 7795:     }
 7796:     return;
 7797: }
 7798: 
 7799: sub grade_student_bubbles {
 7800:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
 7801:     if (ref($resources) eq 'ARRAY') {
 7802:         my $count = 0;
 7803:         foreach my $resource (@{$resources}) {
 7804:             my $ressymb = $resource->symb();
 7805:             my %form = ('submitted'      => 'scantron',
 7806:                         'grade_target'   => 'grade',
 7807:                         'grade_username' => $uname,
 7808:                         'grade_domain'   => $udom,
 7809:                         'grade_courseid' => $env{'request.course.id'},
 7810:                         'grade_symb'     => $ressymb,
 7811:                         'CODE'           => $scancode
 7812:                        );
 7813:             if (ref($parts) eq 'HASH') {
 7814:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 7815:                     foreach my $part (@{$parts->{$ressymb}}) {
 7816:                         $form{'scantron_questnum_start.'.$part} =
 7817:                             1+$env{'form.scantron.first_bubble_line.'.$count};
 7818:                         $count++;
 7819:                     }
 7820:                 }
 7821:             }
 7822:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 7823:             return 'ssi_error' if ($ssi_error);
 7824:             last if (&Apache::loncommon::connection_aborted($r));
 7825:         }
 7826:     }
 7827:     return;
 7828: }
 7829: 
 7830: sub scantron_upload_scantron_data {
 7831:     my ($r,$symb)=@_;
 7832:     my $dom = $env{'request.role.domain'};
 7833:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 7834:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 7835:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 7836: 							  'domainid',
 7837: 							  'coursename',$dom);
 7838:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 7839:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
 7840:     my $default_form_data=&defaultFormData($symb);
 7841:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 7842:     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.");
 7843:     $r->print(&Apache::lonhtmlcommon::scripttag('
 7844:     function checkUpload(formname) {
 7845: 	if (formname.upfile.value == "") {
 7846: 	    alert("'.$nofile_alert.'");
 7847: 	    return false;
 7848: 	}
 7849:         if (formname.courseid.value == "") {
 7850:             alert("'.$nocourseid_alert.'");
 7851:             return false;
 7852:         }
 7853: 	formname.submit();
 7854:     }
 7855: 
 7856:     function ToSyllabus() {
 7857:         var cdom = '."'$dom'".';
 7858:         var cnum = document.rules.courseid.value;
 7859:         if (cdom == "" || cdom == null) {
 7860:             return;
 7861:         }
 7862:         if (cnum == "" || cnum == null) {
 7863:            return;
 7864:         }
 7865:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 7866:                             "height=350,width=350,scrollbars=yes,menubar=no");
 7867:         return;
 7868:     }
 7869: 
 7870: '));
 7871:     $r->print('
 7872: <h3>'.&mt('Send scanned bubblesheet data to a course').'</h3>
 7873: 
 7874: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 7875: '.$default_form_data.
 7876:   &Apache::lonhtmlcommon::start_pick_box().
 7877:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 7878:   '<input name="courseid" type="text" size="30" />'.$select_link.
 7879:   &Apache::lonhtmlcommon::row_closure().
 7880:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 7881:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 7882:   &Apache::lonhtmlcommon::row_closure().
 7883:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 7884:   '<input name="domainid" type="hidden" />'.$domdesc.
 7885:   &Apache::lonhtmlcommon::row_closure().
 7886:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 7887:   '<input type="file" name="upfile" size="50" />'.
 7888:   &Apache::lonhtmlcommon::row_closure(1).
 7889:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 7890: 
 7891: <input name="command" value="scantronupload_save" type="hidden" />
 7892: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 7893: </form>
 7894: ');
 7895:     return '';
 7896: }
 7897: 
 7898: 
 7899: sub scantron_upload_scantron_data_save {
 7900:     my($r,$symb)=@_;
 7901:     my $doanotherupload=
 7902: 	'<br /><form action="/adm/grades" method="post">'."\n".
 7903: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 7904: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 7905: 	'</form>'."\n";
 7906:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 7907: 	!&Apache::lonnet::allowed('usc',
 7908: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 7909: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 7910: 	unless ($symb) {
 7911: 	    $r->print($doanotherupload);
 7912: 	}
 7913: 	return '';
 7914:     }
 7915:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 7916:     my $uploadedfile;
 7917:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
 7918:     if (length($env{'form.upfile'}) < 2) {
 7919:         $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>'));
 7920:     } else {
 7921:         my $result = 
 7922:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
 7923:                                             $env{'form.courseid'},$env{'form.domainid'});
 7924: 	if ($result =~ m{^/uploaded/}) {
 7925: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
 7926:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
 7927: 			  '<span class="LC_filename">'.$result.'</span>'));
 7928:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 7929:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 7930:                                                        $env{'form.courseid'},$uploadedfile));
 7931: 	} else {
 7932: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
 7933:                           '<span class="LC_error">','</span>',$result,
 7934: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 7935: 	}
 7936:     }
 7937:     if ($symb) {
 7938: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
 7939:     } else {
 7940: 	$r->print($doanotherupload);
 7941:     }
 7942:     return '';
 7943: }
 7944: 
 7945: sub validate_uploaded_scantron_file {
 7946:     my ($cdom,$cname,$fname) = @_;
 7947:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 7948:     my @lines;
 7949:     if ($scanlines ne '-1') {
 7950:         @lines=split("\n",$scanlines,-1);
 7951:     }
 7952:     my $output;
 7953:     if (@lines) {
 7954:         my (%counts,$max_match_format);
 7955:         my ($max_match_count,$max_match_pct) = (0,0);
 7956:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 7957:         my %idmap = &username_to_idmap($classlist);
 7958:         foreach my $key (keys(%idmap)) {
 7959:             my $lckey = lc($key);
 7960:             $idmap{$lckey} = $idmap{$key};
 7961:         }
 7962:         my %unique_formats;
 7963:         my @formatlines = &get_scantronformat_file();
 7964:         foreach my $line (@formatlines) {
 7965:             chomp($line);
 7966:             my @config = split(/:/,$line);
 7967:             my $idstart = $config[5];
 7968:             my $idlength = $config[6];
 7969:             if (($idstart ne '') && ($idlength > 0)) {
 7970:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 7971:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 7972:                 } else {
 7973:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 7974:                 }
 7975:             }
 7976:         }
 7977:         foreach my $key (keys(%unique_formats)) {
 7978:             my ($idstart,$idlength) = split(':',$key);
 7979:             %{$counts{$key}} = (
 7980:                                'found'   => 0,
 7981:                                'total'   => 0,
 7982:                               );
 7983:             foreach my $line (@lines) {
 7984:                 next if ($line =~ /^#/);
 7985:                 next if ($line =~ /^[\s\cz]*$/);
 7986:                 my $id = substr($line,$idstart-1,$idlength);
 7987:                 $id = lc($id);
 7988:                 if (exists($idmap{$id})) {
 7989:                     $counts{$key}{'found'} ++;
 7990:                 }
 7991:                 $counts{$key}{'total'} ++;
 7992:             }
 7993:             if ($counts{$key}{'total'}) {
 7994:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 7995:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 7996:                     $max_match_pct = $percent_match;
 7997:                     $max_match_format = $key;
 7998:                     $max_match_count = $counts{$key}{'total'};
 7999:                 }
 8000:             }
 8001:         }
 8002:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 8003:             my $format_descs;
 8004:             my $numwithformat = @{$unique_formats{$max_match_format}};
 8005:             for (my $i=0; $i<$numwithformat; $i++) {
 8006:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 8007:                 if ($i<$numwithformat-2) {
 8008:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 8009:                 } elsif ($i==$numwithformat-2) {
 8010:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 8011:                 } elsif ($i==$numwithformat-1) {
 8012:                     $format_descs .= '"<i>'.$desc.'</i>"';
 8013:                 }
 8014:             }
 8015:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 8016:             $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).
 8017:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
 8018:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
 8019:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
 8020:                                   '<i>'.$cdom.'</i>').'</li>'.
 8021:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 8022:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
 8023:                        '</ul>';
 8024:         }
 8025:     } else {
 8026:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
 8027:     }
 8028:     return $output;
 8029: }
 8030: 
 8031: sub valid_file {
 8032:     my ($requested_file)=@_;
 8033:     foreach my $filename (sort(&scantron_filenames())) {
 8034: 	if ($requested_file eq $filename) { return 1; }
 8035:     }
 8036:     return 0;
 8037: }
 8038: 
 8039: sub scantron_download_scantron_data {
 8040:     my ($r,$symb)=@_;
 8041:     my $default_form_data=&defaultFormData($symb);
 8042:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8043:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8044:     my $file=$env{'form.scantron_selectfile'};
 8045:     if (! &valid_file($file)) {
 8046: 	$r->print('
 8047: 	<p>
 8048: 	    '.&mt('The requested file name was invalid.').'
 8049:         </p>
 8050: ');
 8051: 	return;
 8052:     }
 8053:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 8054:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 8055:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 8056:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 8057:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 8058:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 8059:     $r->print('
 8060:     <p>
 8061: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
 8062: 	      '<a href="'.$orig.'">','</a>').'
 8063:     </p>
 8064:     <p>
 8065: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 8066: 	      '<a href="'.$corrected.'">','</a>').'
 8067:     </p>
 8068:     <p>
 8069: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 8070: 	      '<a href="'.$skipped.'">','</a>').'
 8071:     </p>
 8072: ');
 8073:     return '';
 8074: }
 8075: 
 8076: sub checkscantron_results {
 8077:     my ($r,$symb) = @_;
 8078:     if (!$symb) {return '';}
 8079:     my $cid = $env{'request.course.id'};
 8080:     my %lettdig = &letter_to_digits();
 8081:     my $numletts = scalar(keys(%lettdig));
 8082:     my $cnum = $env{'course.'.$cid.'.num'};
 8083:     my $cdom = $env{'course.'.$cid.'.domain'};
 8084:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8085:     my %record;
 8086:     my %scantron_config =
 8087:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 8088:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 8089:     my $classlist=&Apache::loncoursedata::get_classlist();
 8090:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 8091:     my $navmap=Apache::lonnavmaps::navmap->new();
 8092:     unless (ref($navmap)) {
 8093:         $r->print(&navmap_errormsg());
 8094:         return '';
 8095:     }
 8096:     my $map=$navmap->getResourceByUrl($sequence);
 8097:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8098:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 8099:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
 8100: 
 8101:     my ($uname,$udom);
 8102:     my (%scandata,%lastname,%bylast);
 8103:     $r->print('
 8104: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 8105: 
 8106:     my @delayqueue;
 8107:     my %completedstudents;
 8108: 
 8109:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
 8110:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
 8111:                                     'Progress of Bubblesheet Data/Submission Records Comparison',$count,
 8112:                                     'inline',undef,'checkscantron');
 8113:     my ($username,$domain,$started);
 8114:     my $nav_error;
 8115:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
 8116:     if ($nav_error) {
 8117:         $r->print(&navmap_errormsg());
 8118:         return '';
 8119:     }
 8120: 
 8121:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 8122:                                           'Processing first student');
 8123:     my $start=&Time::HiRes::time();
 8124:     my $i=-1;
 8125: 
 8126:     while ($i<$scanlines->{'count'}) {
 8127:         ($username,$domain,$uname)=('','','');
 8128:         $i++;
 8129:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 8130:         if ($line=~/^[\s\cz]*$/) { next; }
 8131:         if ($started) {
 8132:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 8133:                                                      'last student');
 8134:         }
 8135:         $started=1;
 8136:         my $scan_record=
 8137:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 8138:                                                      $scan_data);
 8139:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
 8140:                                                               \%idmap,$i)) {
 8141:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8142:                                 'Unable to find a student that matches',1);
 8143:             next;
 8144:         }
 8145:         if (exists $completedstudents{$uname}) {
 8146:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8147:                                 'Student '.$uname.' has multiple sheets',2);
 8148:             next;
 8149:         }
 8150:         my $pid = $scan_record->{'scantron.ID'};
 8151:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 8152:         push(@{$bylast{$lastname{$pid}}},$pid);
 8153:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8154:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8155:         chomp($scandata{$pid});
 8156:         $scandata{$pid} =~ s/\r$//;
 8157:         ($username,$domain)=split(/:/,$uname);
 8158:         my $counter = -1;
 8159:         foreach my $resource (@resources) {
 8160:             my $parts;
 8161:             my $ressymb = $resource->symb();
 8162:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8163:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8164:                 (my $analysis,$parts) =
 8165:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
 8166:             } else {
 8167:                 $parts = $grader_partids_by_symb{$ressymb};
 8168:             }
 8169:             ($counter,my $recording) =
 8170:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 8171:                                          $scandata{$pid},$parts,
 8172:                                          \%scantron_config,\%lettdig,$numletts);
 8173:             $record{$pid} .= $recording;
 8174:         }
 8175:     }
 8176:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8177:     $r->print('<br />');
 8178:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 8179:     $passed = 0;
 8180:     $failed = 0;
 8181:     $numstudents = 0;
 8182:     foreach my $last (sort(keys(%bylast))) {
 8183:         if (ref($bylast{$last}) eq 'ARRAY') {
 8184:             foreach my $pid (sort(@{$bylast{$last}})) {
 8185:                 my $showscandata = $scandata{$pid};
 8186:                 my $showrecord = $record{$pid};
 8187:                 $showscandata =~ s/\s/&nbsp;/g;
 8188:                 $showrecord =~ s/\s/&nbsp;/g;
 8189:                 if ($scandata{$pid} eq $record{$pid}) {
 8190:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 8191:                     $okstudents .= '<tr class="'.$css_class.'">'.
 8192: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 8193: '</tr>'."\n".
 8194: '<tr class="'.$css_class.'">'."\n".
 8195: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
 8196:                     $passed ++;
 8197:                 } else {
 8198:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 8199:                     $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".
 8200: '</tr>'."\n".
 8201: '<tr class="'.$css_class.'">'."\n".
 8202: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 8203: '</tr>'."\n";
 8204:                     $failed ++;
 8205:                 }
 8206:                 $numstudents ++;
 8207:             }
 8208:         }
 8209:     }
 8210:     $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>');
 8211:     $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>');
 8212:     if ($passed) {
 8213:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 8214:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8215:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8216:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8217:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8218:                  $okstudents."\n".
 8219:                  &Apache::loncommon::end_data_table().'<br />');
 8220:     }
 8221:     if ($failed) {
 8222:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 8223:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8224:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8225:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8226:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8227:                  $badstudents."\n".
 8228:                  &Apache::loncommon::end_data_table()).'<br />'.
 8229:                  &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.');  
 8230:     }
 8231:     $r->print('</form><br />');
 8232:     return;
 8233: }
 8234: 
 8235: sub verify_scantron_grading {
 8236:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 8237:         $scantron_config,$lettdig,$numletts) = @_;
 8238:     my ($record,%expected,%startpos);
 8239:     return ($counter,$record) if (!ref($resource));
 8240:     return ($counter,$record) if (!$resource->is_problem());
 8241:     my $symb = $resource->symb();
 8242:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 8243:     foreach my $part_id (@{$partids}) {
 8244:         $counter ++;
 8245:         $expected{$part_id} = 0;
 8246:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
 8247:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
 8248:             foreach my $item (@sub_lines) {
 8249:                 $expected{$part_id} += $item;
 8250:             }
 8251:         } else {
 8252:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
 8253:         }
 8254:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 8255:     }
 8256:     if ($symb) {
 8257:         my %recorded;
 8258:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 8259:         if ($returnhash{'version'}) {
 8260:             my %lasthash=();
 8261:             my $version;
 8262:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 8263:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 8264:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 8265:                 }
 8266:             }
 8267:             foreach my $key (keys(%lasthash)) {
 8268:                 if ($key =~ /\.scantron$/) {
 8269:                     my $value = &unescape($lasthash{$key});
 8270:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 8271:                     if ($value eq '') {
 8272:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 8273:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 8274:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8275:                             }
 8276:                         }
 8277:                     } else {
 8278:                         my @tocheck;
 8279:                         my @items = split(//,$value);
 8280:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 8281:                             ($scantron_config->{'Qon'} eq 'number')) {
 8282:                             if (@items < $expected{$part_id}) {
 8283:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 8284:                                 my @singles = split(//,$fragment);
 8285:                                 foreach my $pos (@singles) {
 8286:                                     if ($pos eq ' ') {
 8287:                                         push(@tocheck,$pos);
 8288:                                     } else {
 8289:                                         my $next = shift(@items);
 8290:                                         push(@tocheck,$next);
 8291:                                     }
 8292:                                 }
 8293:                             } else {
 8294:                                 @tocheck = @items;
 8295:                             }
 8296:                             foreach my $letter (@tocheck) {
 8297:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 8298:                                     if ($letter !~ /^[A-J]$/) {
 8299:                                         $letter = $scantron_config->{'Qoff'};
 8300:                                     }
 8301:                                     $recorded{$part_id} .= $letter;
 8302:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 8303:                                     my $digit;
 8304:                                     if ($letter !~ /^[A-J]$/) {
 8305:                                         $digit = $scantron_config->{'Qoff'};
 8306:                                     } else {
 8307:                                         $digit = $lettdig->{$letter};
 8308:                                     }
 8309:                                     $recorded{$part_id} .= $digit;
 8310:                                 }
 8311:                             }
 8312:                         } else {
 8313:                             @tocheck = @items;
 8314:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 8315:                                 my $curr_sub = shift(@tocheck);
 8316:                                 my $digit;
 8317:                                 if ($curr_sub =~ /^[A-J]$/) {
 8318:                                     $digit = $lettdig->{$curr_sub}-1;
 8319:                                 }
 8320:                                 if ($curr_sub eq 'J') {
 8321:                                     $digit += scalar($numletts);
 8322:                                 }
 8323:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8324:                                     if ($j == $digit) {
 8325:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 8326:                                     } else {
 8327:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8328:                                     }
 8329:                                 }
 8330:                             }
 8331:                         }
 8332:                     }
 8333:                 }
 8334:             }
 8335:         }
 8336:         foreach my $part_id (@{$partids}) {
 8337:             if ($recorded{$part_id} eq '') {
 8338:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 8339:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8340:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8341:                     }
 8342:                 }
 8343:             }
 8344:             $record .= $recorded{$part_id};
 8345:         }
 8346:     }
 8347:     return ($counter,$record);
 8348: }
 8349: 
 8350: sub letter_to_digits { 
 8351:     my %lettdig = (
 8352:                     A => 1,
 8353:                     B => 2,
 8354:                     C => 3,
 8355:                     D => 4,
 8356:                     E => 5,
 8357:                     F => 6,
 8358:                     G => 7,
 8359:                     H => 8,
 8360:                     I => 9,
 8361:                     J => 0,
 8362:                   );
 8363:     return %lettdig;
 8364: }
 8365: 
 8366: 
 8367: #-------- end of section for handling grading scantron forms -------
 8368: #
 8369: #-------------------------------------------------------------------
 8370: 
 8371: #-------------------------- Menu interface -------------------------
 8372: #
 8373: #--- Href with symb and command ---
 8374: 
 8375: sub href_symb_cmd {
 8376:     my ($symb,$cmd)=@_;
 8377:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&command='.$cmd;
 8378: }
 8379: 
 8380: sub grading_menu {
 8381:     my ($request,$symb) = @_;
 8382:     if (!$symb) {return '';}
 8383: 
 8384:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 8385:                   'command'=>'individual');
 8386:     
 8387:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8388: 
 8389:     $fields{'command'}='ungraded';
 8390:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8391: 
 8392:     $fields{'command'}='table';
 8393:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8394: 
 8395:     $fields{'command'}='all_for_one';
 8396:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8397: 
 8398:     $fields{'command'}='downloadfilesselect';
 8399:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8400: 
 8401:     $fields{'command'} = 'csvform';
 8402:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8403:     
 8404:     $fields{'command'} = 'processclicker';
 8405:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8406:     
 8407:     $fields{'command'} = 'scantron_selectphase';
 8408:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8409: 
 8410:     $fields{'command'} = 'initialverifyreceipt';
 8411:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8412:     
 8413:     my @menu = ({	categorytitle=>'Hand Grading',
 8414:             items =>[
 8415:                         {	linktext => 'Select individual students to grade',
 8416:                     		url => $url1a,
 8417:                     		permission => 'F',
 8418:                     		icon => 'edit-find-replace.png',
 8419:                     		linktitle => 'Grade current resource for a selection of students.'
 8420:                         }, 
 8421:                         {       linktext => 'Grade ungraded submissions.',
 8422:                                 url => $url1b,
 8423:                                 permission => 'F',
 8424:                                 icon => 'edit-find-replace.png',
 8425:                                 linktitle => 'Grade all submissions that have not been graded yet.'
 8426:                         },
 8427: 
 8428:                         {       linktext => 'Grading table',
 8429:                                 url => $url1c,
 8430:                                 permission => 'F',
 8431:                                 icon => 'edit-find-replace.png',
 8432:                                 linktitle => 'Grade current resource for all students.'
 8433:                         },
 8434:                         {       linktext => 'Grade page/folder for one student',
 8435:                                 url => $url1d,
 8436:                                 permission => 'F',
 8437:                                 icon => 'edit-find-replace.png',
 8438:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
 8439:                         },
 8440:                         {       linktext => 'Download submissions',
 8441:                                 url => $url1e,
 8442:                                 permission => 'F',
 8443:                                 icon => 'edit-find-replace.png',
 8444:                                 linktitle => 'Download all students submissions.'
 8445:                         }]},
 8446:                          { categorytitle=>'Automated Grading',
 8447:                items =>[
 8448: 
 8449:                 	    {	linktext => 'Upload Scores',
 8450:                     		url => $url2,
 8451:                     		permission => 'F',
 8452:                     		icon => 'uploadscores.png',
 8453:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 8454:                 	    },
 8455:                 	    {	linktext => 'Process Clicker',
 8456:                     		url => $url3,
 8457:                     		permission => 'F',
 8458:                     		icon => 'addClickerInfoFile.png',
 8459:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 8460:                 	    },
 8461:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
 8462:                     		url => $url4,
 8463:                     		permission => 'F',
 8464:                     		icon => 'stat.png',
 8465:                     		linktitle => 'Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.'
 8466:                 	    },
 8467:                             {   linktext => 'Verify Receipt Number',
 8468:                                 url => $url5,
 8469:                                 permission => 'F',
 8470:                                 icon => 'edit-find-replace.png',
 8471:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
 8472:                             }
 8473: 
 8474:                     ]
 8475:             });
 8476: 
 8477:     # Create the menu
 8478:     my $Str;
 8479:     $Str .= '<form method="post" action="" name="gradingMenu">';
 8480:     $Str .= '<input type="hidden" name="command" value="" />'.
 8481:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8482: 
 8483:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
 8484:     return $Str;    
 8485: }
 8486: 
 8487: 
 8488: sub ungraded {
 8489:     my ($request)=@_;
 8490:     &submit_options($request);
 8491: }
 8492: 
 8493: sub submit_options_sequence {
 8494:     my ($request,$symb) = @_;
 8495:     if (!$symb) {return '';}
 8496:     &commonJSfunctions($request);
 8497:     my $result;
 8498: 
 8499:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8500:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 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: 
 8524:     $result.='
 8525: <h2>
 8526:   '.&mt('Grading table').'
 8527: </h2>'.
 8528:             &selectfield(0).
 8529:             '<input type="hidden" name="command" value="viewgrades" />
 8530:             <div>
 8531:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 8532:             </div>
 8533:         </div>
 8534:   </form>';
 8535:     return $result;
 8536: }
 8537: 
 8538: sub submit_options_download {
 8539:     my ($request,$symb) = @_;
 8540:     if (!$symb) {return '';}
 8541: 
 8542:     &commonJSfunctions($request);
 8543: 
 8544:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8545:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8546:     $result.='
 8547: <h2>
 8548:   '.&mt('Select Students for Which to Download Submissions').'
 8549: </h2>'.&selectfield(1).'
 8550:                 <input type="hidden" name="command" value="downloadfileslink" /> 
 8551:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 8552:             </div>
 8553:           </div>
 8554: 
 8555: 
 8556:   </form>';
 8557:     return $result;
 8558: }
 8559: 
 8560: #--- Displays the submissions first page -------
 8561: sub submit_options {
 8562:     my ($request,$symb) = @_;
 8563:     if (!$symb) {return '';}
 8564: 
 8565:     &commonJSfunctions($request);
 8566:     my $result;
 8567: 
 8568:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8569: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8570:     $result.='
 8571: <h2>
 8572:   '.&mt('Select individual students to grade').'
 8573: </h2>'.&selectfield(1).'
 8574:                 <input type="hidden" name="command" value="submission" /> 
 8575: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
 8576:             </div>
 8577:           </div>
 8578: 
 8579: 
 8580:   </form>';
 8581:     return $result;
 8582: }
 8583: 
 8584: sub selectfield {
 8585:    my ($full)=@_;
 8586:    my $result='<div class="LC_columnSection">
 8587:   
 8588:     <fieldset>
 8589:       <legend>
 8590:        '.&mt('Sections').'
 8591:       </legend>
 8592:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
 8593:     </fieldset>
 8594:   
 8595:     <fieldset>
 8596:       <legend>
 8597:         '.&mt('Groups').'
 8598:       </legend>
 8599:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 8600:     </fieldset>
 8601:   
 8602:     <fieldset>
 8603:       <legend>
 8604:         '.&mt('Access Status').'
 8605:       </legend>
 8606:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
 8607:     </fieldset>';
 8608:     if ($full) {
 8609:        $result.='
 8610:     <fieldset>
 8611:       <legend>
 8612:         '.&mt('Submission Status').'
 8613:       </legend>'.
 8614:        &Apache::loncommon::select_form('all','submitonly',
 8615:           (&Apache::lonlocal::texthash(
 8616:              'yes'       => 'with submissions',
 8617:              'queued'    => 'in grading queue',
 8618:              'graded'    => 'with ungraded submissions',
 8619:              'incorrect' => 'with incorrect submissions',
 8620:              'all'       => 'with any status'),
 8621:              'select_form_order' => ['yes','queued','graded','incorrect','all'])).
 8622:    '</fieldset>';
 8623:     }
 8624:     $result.='</div><br />';
 8625:     return $result;
 8626: }
 8627: 
 8628: sub reset_perm {
 8629:     undef(%perm);
 8630: }
 8631: 
 8632: sub init_perm {
 8633:     &reset_perm();
 8634:     foreach my $test_perm ('vgr','mgr','opa') {
 8635: 
 8636: 	my $scope = $env{'request.course.id'};
 8637: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 8638: 
 8639: 	    $scope .= '/'.$env{'request.course.sec'};
 8640: 	    if ( $perm{$test_perm}=
 8641: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 8642: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 8643: 	    } else {
 8644: 		delete($perm{$test_perm});
 8645: 	    }
 8646: 	}
 8647:     }
 8648: }
 8649: 
 8650: sub gather_clicker_ids {
 8651:     my %clicker_ids;
 8652: 
 8653:     my $classlist = &Apache::loncoursedata::get_classlist();
 8654: 
 8655:     # Set up a couple variables.
 8656:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 8657:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 8658:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 8659: 
 8660:     foreach my $student (keys(%$classlist)) {
 8661:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 8662:         my $username = $classlist->{$student}->[$username_idx];
 8663:         my $domain   = $classlist->{$student}->[$domain_idx];
 8664:         my $clickers =
 8665: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 8666:         foreach my $id (split(/\,/,$clickers)) {
 8667:             $id=~s/^[\#0]+//;
 8668:             $id=~s/[\-\:]//g;
 8669:             if (exists($clicker_ids{$id})) {
 8670: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 8671:             } else {
 8672: 		$clicker_ids{$id}=$username.':'.$domain;
 8673:             }
 8674:         }
 8675:     }
 8676:     return %clicker_ids;
 8677: }
 8678: 
 8679: sub gather_adv_clicker_ids {
 8680:     my %clicker_ids;
 8681:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 8682:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8683:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 8684:     foreach my $element (sort(keys(%coursepersonnel))) {
 8685:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 8686:             my ($puname,$pudom)=split(/\:/,$person);
 8687:             my $clickers =
 8688: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 8689:             foreach my $id (split(/\,/,$clickers)) {
 8690: 		$id=~s/^[\#0]+//;
 8691:                 $id=~s/[\-\:]//g;
 8692: 		if (exists($clicker_ids{$id})) {
 8693: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 8694: 		} else {
 8695: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 8696: 		}
 8697:             }
 8698:         }
 8699:     }
 8700:     return %clicker_ids;
 8701: }
 8702: 
 8703: sub clicker_grading_parameters {
 8704:     return ('gradingmechanism' => 'scalar',
 8705:             'upfiletype' => 'scalar',
 8706:             'specificid' => 'scalar',
 8707:             'pcorrect' => 'scalar',
 8708:             'pincorrect' => 'scalar');
 8709: }
 8710: 
 8711: sub process_clicker {
 8712:     my ($r,$symb)=@_;
 8713:     if (!$symb) {return '';}
 8714:     my $result=&checkforfile_js();
 8715:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 8716:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 8717:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
 8718:         '</b></td></tr>'."\n";
 8719:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
 8720: # Attempt to restore parameters from last session, set defaults if not present
 8721:     my %Saveable_Parameters=&clicker_grading_parameters();
 8722:     &Apache::loncommon::restore_course_settings('grades_clicker',
 8723:                                                  \%Saveable_Parameters);
 8724:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 8725:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 8726:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 8727:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 8728: 
 8729:     my %checked;
 8730:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 8731:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 8732:           $checked{$gradingmechanism}=' checked="checked"';
 8733:        }
 8734:     }
 8735: 
 8736:     my $upload=&mt("Upload File");
 8737:     my $type=&mt("Type");
 8738:     my $attendance=&mt("Award points just for participation");
 8739:     my $personnel=&mt("Correctness determined from response by course personnel");
 8740:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 8741:     my $given=&mt("Correctness determined from given list of answers").' '.
 8742:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 8743:     my $pcorrect=&mt("Percentage points for correct solution");
 8744:     my $pincorrect=&mt("Percentage points for incorrect solution");
 8745:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 8746: 						   ('iclicker' => 'i>clicker',
 8747:                                                     'interwrite' => 'interwrite PRS'));
 8748:     $symb = &Apache::lonenc::check_encrypt($symb);
 8749:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
 8750: function sanitycheck() {
 8751: // Accept only integer percentages
 8752:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 8753:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 8754: // Find out grading choice
 8755:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8756:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 8757:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 8758:       }
 8759:    }
 8760: // By default, new choice equals user selection
 8761:    newgradingchoice=gradingchoice;
 8762: // Not good to give more points for false answers than correct ones
 8763:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 8764:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 8765:    }
 8766: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 8767:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 8768:       document.forms.gradesupload.pcorrect.value=100;
 8769:       document.forms.gradesupload.pincorrect.value=100;
 8770:    }
 8771: // If the values are different, cannot be attendance only
 8772:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 8773:        (gradingchoice=='attendance')) {
 8774:        newgradingchoice='personnel';
 8775:    }
 8776: // Change grading choice to new one
 8777:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8778:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 8779:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 8780:       } else {
 8781:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 8782:       }
 8783:    }
 8784: // Remember the old state
 8785:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 8786: }
 8787: ENDUPFORM
 8788:     $result.= <<ENDUPFORM;
 8789: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 8790: <input type="hidden" name="symb" value="$symb" />
 8791: <input type="hidden" name="command" value="processclickerfile" />
 8792: <input type="file" name="upfile" size="50" />
 8793: <br /><label>$type: $selectform</label>
 8794: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
 8795: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
 8796: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
 8797: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 8798: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
 8799: <br />&nbsp;&nbsp;&nbsp;
 8800: <input type="text" name="givenanswer" size="50" />
 8801: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 8802: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
 8803: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
 8804: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 8805: </form>'
 8806: ENDUPFORM
 8807:     $result.='</td></tr></table>'."\n".
 8808:              '</td></tr></table><br /><br />'."\n";
 8809:     return $result;
 8810: }
 8811: 
 8812: sub process_clicker_file {
 8813:     my ($r,$symb)=@_;
 8814:     if (!$symb) {return '';}
 8815: 
 8816:     my %Saveable_Parameters=&clicker_grading_parameters();
 8817:     &Apache::loncommon::store_course_settings('grades_clicker',
 8818:                                               \%Saveable_Parameters);
 8819:     my $result='';
 8820:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 8821: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 8822: 	return $result;
 8823:     }
 8824:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 8825:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 8826:         return $result;
 8827:     }
 8828:     my $foundgiven=0;
 8829:     if ($env{'form.gradingmechanism'} eq 'given') {
 8830:         $env{'form.givenanswer'}=~s/^\s*//gs;
 8831:         $env{'form.givenanswer'}=~s/\s*$//gs;
 8832:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
 8833:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 8834:         my @answers=split(/\,/,$env{'form.givenanswer'});
 8835:         $foundgiven=$#answers+1;
 8836:     }
 8837:     my %clicker_ids=&gather_clicker_ids();
 8838:     my %correct_ids;
 8839:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 8840: 	%correct_ids=&gather_adv_clicker_ids();
 8841:     }
 8842:     if ($env{'form.gradingmechanism'} eq 'specific') {
 8843: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 8844: 	   $correct_id=~tr/a-z/A-Z/;
 8845: 	   $correct_id=~s/\s//gs;
 8846: 	   $correct_id=~s/^[\#0]+//;
 8847:            $correct_id=~s/[\-\:]//g;
 8848:            if ($correct_id) {
 8849: 	      $correct_ids{$correct_id}='specified';
 8850:            }
 8851:         }
 8852:     }
 8853:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 8854: 	$result.=&mt('Score based on attendance only');
 8855:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
 8856:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
 8857:     } else {
 8858: 	my $number=0;
 8859: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 8860: 	foreach my $id (sort(keys(%correct_ids))) {
 8861: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 8862: 	    if ($correct_ids{$id} eq 'specified') {
 8863: 		$result.=&mt('specified');
 8864: 	    } else {
 8865: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 8866: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 8867: 	    }
 8868: 	    $number++;
 8869: 	}
 8870:         $result.="</p>\n";
 8871: 	if ($number==0) {
 8872: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
 8873: 	    return $result;
 8874: 	}
 8875:     }
 8876:     if (length($env{'form.upfile'}) < 2) {
 8877:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
 8878: 		     '<span class="LC_error">',
 8879: 		     '</span>',
 8880: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
 8881:         return $result;
 8882:     }
 8883: 
 8884: # Were able to get all the info needed, now analyze the file
 8885: 
 8886:     $result.=&Apache::loncommon::studentbrowser_javascript();
 8887:     $symb = &Apache::lonenc::check_encrypt($symb);
 8888:     my $heading=&mt('Scanning clicker file');
 8889:     $result.=(<<ENDHEADER);
 8890: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 8891: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 8892: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 8893: <form method="post" action="/adm/grades" name="clickeranalysis">
 8894: <input type="hidden" name="symb" value="$symb" />
 8895: <input type="hidden" name="command" value="assignclickergrades" />
 8896: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 8897: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 8898: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 8899: ENDHEADER
 8900:     if ($env{'form.gradingmechanism'} eq 'given') {
 8901:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
 8902:     } 
 8903:     my %responses;
 8904:     my @questiontitles;
 8905:     my $errormsg='';
 8906:     my $number=0;
 8907:     if ($env{'form.upfiletype'} eq 'iclicker') {
 8908: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 8909:     }
 8910:     if ($env{'form.upfiletype'} eq 'interwrite') {
 8911:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 8912:     }
 8913:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 8914:              '<input type="hidden" name="number" value="'.$number.'" />'.
 8915:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 8916:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 8917:              '<br />';
 8918:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
 8919:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
 8920:        return $result;
 8921:     } 
 8922: # Remember Question Titles
 8923: # FIXME: Possibly need delimiter other than ":"
 8924:     for (my $i=0;$i<$number;$i++) {
 8925:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 8926:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 8927:     }
 8928:     my $correct_count=0;
 8929:     my $student_count=0;
 8930:     my $unknown_count=0;
 8931: # Match answers with usernames
 8932: # FIXME: Possibly need delimiter other than ":"
 8933:     foreach my $id (keys(%responses)) {
 8934:        if ($correct_ids{$id}) {
 8935:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 8936:           $correct_count++;
 8937:        } elsif ($clicker_ids{$id}) {
 8938:           if ($clicker_ids{$id}=~/\,/) {
 8939: # More than one user with the same clicker!
 8940:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 8941:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 8942:                            "<select name='multi".$id."'>";
 8943:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 8944:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 8945:              }
 8946:              $result.='</select>';
 8947:              $unknown_count++;
 8948:           } else {
 8949: # Good: found one and only one user with the right clicker
 8950:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 8951:              $student_count++;
 8952:           }
 8953:        } else {
 8954:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 8955:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 8956:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 8957:                    "\n".&mt("Domain").": ".
 8958:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 8959:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
 8960:           $unknown_count++;
 8961:        }
 8962:     }
 8963:     $result.='<hr />'.
 8964:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 8965:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
 8966:        if ($correct_count==0) {
 8967:           $errormsg.="Found no correct answers answers for grading!";
 8968:        } elsif ($correct_count>1) {
 8969:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 8970:        }
 8971:     }
 8972:     if ($number<1) {
 8973:        $errormsg.="Found no questions.";
 8974:     }
 8975:     if ($errormsg) {
 8976:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 8977:     } else {
 8978:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 8979:     }
 8980:     $result.='</form></td></tr></table>'."\n".
 8981:              '</td></tr></table><br /><br />'."\n";
 8982:     return $result;
 8983: }
 8984: 
 8985: sub iclicker_eval {
 8986:     my ($questiontitles,$responses)=@_;
 8987:     my $number=0;
 8988:     my $errormsg='';
 8989:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 8990:         my %components=&Apache::loncommon::record_sep($line);
 8991:         my @entries=map {$components{$_}} (sort(keys(%components)));
 8992: 	if ($entries[0] eq 'Question') {
 8993: 	    for (my $i=3;$i<$#entries;$i+=6) {
 8994: 		$$questiontitles[$number]=$entries[$i];
 8995: 		$number++;
 8996: 	    }
 8997: 	}
 8998: 	if ($entries[0]=~/^\#/) {
 8999: 	    my $id=$entries[0];
 9000: 	    my @idresponses;
 9001: 	    $id=~s/^[\#0]+//;
 9002: 	    for (my $i=0;$i<$number;$i++) {
 9003: 		my $idx=3+$i*6;
 9004: 		push(@idresponses,$entries[$idx]);
 9005: 	    }
 9006: 	    $$responses{$id}=join(',',@idresponses);
 9007: 	}
 9008:     }
 9009:     return ($errormsg,$number);
 9010: }
 9011: 
 9012: sub interwrite_eval {
 9013:     my ($questiontitles,$responses)=@_;
 9014:     my $number=0;
 9015:     my $errormsg='';
 9016:     my $skipline=1;
 9017:     my $questionnumber=0;
 9018:     my %idresponses=();
 9019:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9020:         my %components=&Apache::loncommon::record_sep($line);
 9021:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9022:         if ($entries[1] eq 'Time') { $skipline=0; next; }
 9023:         if ($entries[1] eq 'Response') { $skipline=1; }
 9024:         next if $skipline;
 9025:         if ($entries[0]!=$questionnumber) {
 9026:            $questionnumber=$entries[0];
 9027:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
 9028:            $number++;
 9029:         }
 9030:         my $id=$entries[4];
 9031:         $id=~s/^[\#0]+//;
 9032:         $id=~s/^v\d*\://i;
 9033:         $id=~s/[\-\:]//g;
 9034:         $idresponses{$id}[$number]=$entries[6];
 9035:     }
 9036:     foreach my $id (keys(%idresponses)) {
 9037:        $$responses{$id}=join(',',@{$idresponses{$id}});
 9038:        $$responses{$id}=~s/^\s*\,//;
 9039:     }
 9040:     return ($errormsg,$number);
 9041: }
 9042: 
 9043: sub assign_clicker_grades {
 9044:     my ($r,$symb)=@_;
 9045:     if (!$symb) {return '';}
 9046: # See which part we are saving to
 9047:     my $res_error;
 9048:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 9049:     if ($res_error) {
 9050:         return &navmap_errormsg();
 9051:     }
 9052: # FIXME: This should probably look for the first handgradeable part
 9053:     my $part=$$partlist[0];
 9054: # Start screen output
 9055:     my $result='';
 9056: 
 9057:     my $heading=&mt('Assigning grades based on clicker file');
 9058:     $result.=(<<ENDHEADER);
 9059: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 9060: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 9061: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 9062: ENDHEADER
 9063: # Get correct result
 9064: # FIXME: Possibly need delimiter other than ":"
 9065:     my @correct=();
 9066:     my $gradingmechanism=$env{'form.gradingmechanism'};
 9067:     my $number=$env{'form.number'};
 9068:     if ($gradingmechanism ne 'attendance') {
 9069:        foreach my $key (keys(%env)) {
 9070:           if ($key=~/^form\.correct\:/) {
 9071:              my @input=split(/\,/,$env{$key});
 9072:              for (my $i=0;$i<=$#input;$i++) {
 9073:                  if (($correct[$i]) && ($input[$i]) &&
 9074:                      ($correct[$i] ne $input[$i])) {
 9075:                     $result.='<br /><span class="LC_warning">'.
 9076:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
 9077:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
 9078:                  } elsif ($input[$i]) {
 9079:                     $correct[$i]=$input[$i];
 9080:                  }
 9081:              }
 9082:           }
 9083:        }
 9084:        for (my $i=0;$i<$number;$i++) {
 9085:           if (!$correct[$i]) {
 9086:              $result.='<br /><span class="LC_error">'.
 9087:                       &mt('No correct result given for question "[_1]"!',
 9088:                           $env{'form.question:'.$i}).'</span>';
 9089:           }
 9090:        }
 9091:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
 9092:     }
 9093: # Start grading
 9094:     my $pcorrect=$env{'form.pcorrect'};
 9095:     my $pincorrect=$env{'form.pincorrect'};
 9096:     my $storecount=0;
 9097:     foreach my $key (keys(%env)) {
 9098:        my $user='';
 9099:        if ($key=~/^form\.student\:(.*)$/) {
 9100:           $user=$1;
 9101:        }
 9102:        if ($key=~/^form\.unknown\:(.*)$/) {
 9103:           my $id=$1;
 9104:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
 9105:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
 9106:           } elsif ($env{'form.multi'.$id}) {
 9107:              $user=$env{'form.multi'.$id};
 9108:           }
 9109:        }
 9110:        if ($user) { 
 9111:           my @answer=split(/\,/,$env{$key});
 9112:           my $sum=0;
 9113:           my $realnumber=$number;
 9114:           for (my $i=0;$i<$number;$i++) {
 9115:              if  ($correct[$i] eq '-') {
 9116:                 $realnumber--;
 9117:              } elsif ($answer[$i]) {
 9118:                 if ($gradingmechanism eq 'attendance') {
 9119:                    $sum+=$pcorrect;
 9120:                 } elsif ($correct[$i] eq '*') {
 9121:                    $sum+=$pcorrect;
 9122:                 } else {
 9123:                    if ($answer[$i] eq $correct[$i]) {
 9124:                       $sum+=$pcorrect;
 9125:                    } else {
 9126:                       $sum+=$pincorrect;
 9127:                    }
 9128:                 }
 9129:              }
 9130:           }
 9131:           my $ave=$sum/(100*$realnumber);
 9132: # Store
 9133:           my ($username,$domain)=split(/\:/,$user);
 9134:           my %grades=();
 9135:           $grades{"resource.$part.solved"}='correct_by_override';
 9136:           $grades{"resource.$part.awarded"}=$ave;
 9137:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 9138:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
 9139:                                                  $env{'request.course.id'},
 9140:                                                  $domain,$username);
 9141:           if ($returncode ne 'ok') {
 9142:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
 9143:           } else {
 9144:              $storecount++;
 9145:           }
 9146:        }
 9147:     }
 9148: # We are done
 9149:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
 9150:              '</td></tr></table>'."\n".
 9151:              '</td></tr></table><br /><br />'."\n";
 9152:     return $result;
 9153: }
 9154: 
 9155: sub navmap_errormsg {
 9156:     return '<div class="LC_error">'.
 9157:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
 9158:            &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>').
 9159:            '</div>';
 9160: }
 9161: 
 9162: sub startpage {
 9163:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag) = @_;
 9164:     unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
 9165:     $r->print(&Apache::loncommon::start_page('Grading',undef,
 9166:                                           {'bread_crumbs' => $crumbs}));
 9167:     unless ($nodisplayflag) {
 9168:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag));
 9169:     }
 9170: }
 9171: 
 9172: sub handler {
 9173:     my $request=$_[0];
 9174:     &reset_caches();
 9175:     if ($env{'browser.mathml'}) {
 9176: 	&Apache::loncommon::content_type($request,'text/xml');
 9177:     } else {
 9178: 	&Apache::loncommon::content_type($request,'text/html');
 9179:     }
 9180:     $request->send_http_header;
 9181:     return '' if $request->header_only;
 9182:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
 9183: 
 9184: # see what command we need to execute
 9185: 
 9186:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
 9187:     my $command=$commands[0];
 9188: 
 9189:     if ($#commands > 0) {
 9190: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
 9191:     }
 9192: 
 9193: # see what the symb is
 9194: 
 9195:     my $symb=$env{'form.symb'};
 9196:     unless ($symb) {
 9197:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
 9198:        $symb=&Apache::lonnet::symbread($url);
 9199:     }
 9200:     &Apache::lonenc::check_decrypt(\$symb);                             
 9201: 
 9202:     $ssi_error = 0;
 9203:     if ($symb eq '' && $command eq '') {
 9204: #
 9205: # Not called from a resource
 9206: #    
 9207: 
 9208:     } else {
 9209: 	&init_perm();
 9210: 	if ($command eq 'submission' && $perm{'vgr'}) {
 9211:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}]);
 9212: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
 9213: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
 9214:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
 9215:                                        {href=>'',text=>'Select student'}],1,1);
 9216: 	    &pickStudentPage($request,$symb);
 9217: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
 9218:             &startpage($request,$symb,
 9219:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
 9220:                                        {href=>'',text=>'Select student'},
 9221:                                        {href=>'',text=>'Grade student'}],1,1);
 9222: 	    &displayPage($request,$symb);
 9223: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
 9224:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
 9225:                                        {href=>'',text=>'Select student'},
 9226:                                        {href=>'',text=>'Grade student'},
 9227:                                        {href=>'',text=>'Store grades'}],1,1);
 9228: 	    &updateGradeByPage($request,$symb);
 9229: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
 9230:             &startpage($request,$symb,[{href=>'',text=>'...'},
 9231:                                        {href=>'',text=>'Modify grades'}]);
 9232: 	    &processGroup($request,$symb);
 9233: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
 9234:             &startpage($request,$symb);
 9235: 	    $request->print(&grading_menu($request,$symb));
 9236: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
 9237:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
 9238: 	    $request->print(&submit_options($request,$symb));
 9239:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
 9240:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
 9241:             $request->print(&listStudents($request,$symb,'graded'));
 9242:         } elsif ($command eq 'table' && $perm{'vgr'}) {
 9243:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
 9244:             $request->print(&submit_options_table($request,$symb));
 9245:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
 9246:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
 9247:             $request->print(&submit_options_sequence($request,$symb));
 9248: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
 9249:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
 9250: 	    $request->print(&viewgrades($request,$symb));
 9251: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
 9252:             &startpage($request,$symb,[{href=>'',text=>'...'},
 9253:                                        {href=>'',text=>'Store grades'}]);
 9254: 	    $request->print(&processHandGrade($request,$symb));
 9255: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
 9256:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
 9257:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
 9258:                                                                              text=>"Modify grades"},
 9259:                                        {href=>'', text=>"Store grades"}]);
 9260: 	    $request->print(&editgrades($request,$symb));
 9261:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
 9262:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
 9263:             $request->print(&initialverifyreceipt($request,$symb));
 9264: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
 9265:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
 9266:                                        {href=>'',text=>'Verification Result'}]);
 9267: 	    $request->print(&verifyreceipt($request,$symb));
 9268:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
 9269:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
 9270:             $request->print(&process_clicker($request,$symb));
 9271:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
 9272:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
 9273:                                        {href=>'', text=>'Process clicker file'}]);
 9274:             $request->print(&process_clicker_file($request,$symb));
 9275:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
 9276:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
 9277:                                        {href=>'', text=>'Process clicker file'},
 9278:                                        {href=>'', text=>'Store grades'}]);
 9279:             $request->print(&assign_clicker_grades($request,$symb));
 9280: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
 9281:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9282: 	    $request->print(&upcsvScores_form($request,$symb));
 9283: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
 9284:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9285: 	    $request->print(&csvupload($request,$symb));
 9286: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
 9287:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9288: 	    $request->print(&csvuploadmap($request,$symb));
 9289: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
 9290: 	    if ($env{'form.associate'} ne 'Reverse Association') {
 9291:                 &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9292: 		$request->print(&csvuploadoptions($request,$symb));
 9293: 	    } else {
 9294: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
 9295: 		    $env{'form.upfile_associate'} = 'reverse';
 9296: 		} else {
 9297: 		    $env{'form.upfile_associate'} = 'forward';
 9298: 		}
 9299:                 &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9300: 		$request->print(&csvuploadmap($request,$symb));
 9301: 	    }
 9302: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
 9303:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9304: 	    $request->print(&csvuploadassign($request,$symb));
 9305: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
 9306:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9307: 	    $request->print(&scantron_selectphase($request,undef,$symb));
 9308:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
 9309:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9310:  	    $request->print(&scantron_do_warning($request,$symb));
 9311: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
 9312:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9313: 	    $request->print(&scantron_validate_file($request,$symb));
 9314: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
 9315:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9316: 	    $request->print(&scantron_process_students($request,$symb));
 9317:  	} elsif ($command eq 'scantronupload' && 
 9318:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9319: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9320:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9321:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
 9322:  	} elsif ($command eq 'scantronupload_save' &&
 9323:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9324: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9325:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9326:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
 9327:  	} elsif ($command eq 'scantron_download' &&
 9328: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 9329:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9330:  	    $request->print(&scantron_download_scantron_data($request,$symb));
 9331:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
 9332:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9333:             $request->print(&checkscantron_results($request,$symb));
 9334:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
 9335:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
 9336:             $request->print(&submit_options_download($request,$symb));
 9337:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
 9338:             &startpage($request,$symb,
 9339:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
 9340:     {href=>'', text=>'Download submissions'}]);
 9341:             &submit_download_link($request,$symb);
 9342: 	} elsif ($command) {
 9343:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
 9344: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
 9345: 	}
 9346:     }
 9347:     if ($ssi_error) {
 9348: 	&ssi_print_error($request);
 9349:     }
 9350:     $request->print(&Apache::loncommon::end_page());
 9351:     &reset_caches();
 9352:     return '';
 9353: }
 9354: 
 9355: 1;
 9356: 
 9357: __END__;
 9358: 
 9359: 
 9360: =head1 NAME
 9361: 
 9362: Apache::grades
 9363: 
 9364: =head1 SYNOPSIS
 9365: 
 9366: Handles the viewing of grades.
 9367: 
 9368: This is part of the LearningOnline Network with CAPA project
 9369: described at http://www.lon-capa.org.
 9370: 
 9371: =head1 OVERVIEW
 9372: 
 9373: Do an ssi with retries:
 9374: While I'd love to factor out this with the vesrion in lonprintout,
 9375: 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
 9376: I'm not quite ready to invent (e.g. an ssi_with_retry object).
 9377: 
 9378: At least the logic that drives this has been pulled out into loncommon.
 9379: 
 9380: 
 9381: 
 9382: ssi_with_retries - Does the server side include of a resource.
 9383:                      if the ssi call returns an error we'll retry it up to
 9384:                      the number of times requested by the caller.
 9385:                      If we still have a proble, no text is appended to the
 9386:                      output and we set some global variables.
 9387:                      to indicate to the caller an SSI error occurred.  
 9388:                      All of this is supposed to deal with the issues described
 9389:                      in LonCAPA BZ 5631 see:
 9390:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
 9391:                      by informing the user that this happened.
 9392: 
 9393: Parameters:
 9394:   resource   - The resource to include.  This is passed directly, without
 9395:                interpretation to lonnet::ssi.
 9396:   form       - The form hash parameters that guide the interpretation of the resource
 9397:                
 9398:   retries    - Number of retries allowed before giving up completely.
 9399: Returns:
 9400:   On success, returns the rendered resource identified by the resource parameter.
 9401: Side Effects:
 9402:   The following global variables can be set:
 9403:    ssi_error                - If an unrecoverable error occurred this becomes true.
 9404:                               It is up to the caller to initialize this to false
 9405:                               if desired.
 9406:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
 9407:                               of the resource that could not be rendered by the ssi
 9408:                               call.
 9409:    ssi_error_message   - The error string fetched from the ssi response
 9410:                               in the event of an error.
 9411: 
 9412: 
 9413: =head1 HANDLER SUBROUTINE
 9414: 
 9415: ssi_with_retries()
 9416: 
 9417: =head1 SUBROUTINES
 9418: 
 9419: =over
 9420: 
 9421: =item scantron_get_correction() : 
 9422: 
 9423:    Builds the interface screen to interact with the operator to fix a
 9424:    specific error condition in a specific scanline
 9425: 
 9426:  Arguments:
 9427:     $r           - Apache request object
 9428:     $i           - number of the current scanline
 9429:     $scan_record - hash ref as returned from &scantron_parse_scanline()
 9430:     $scan_config - hash ref as returned from &get_scantron_config()
 9431:     $line        - full contents of the current scanline
 9432:     $error       - error condition, valid values are
 9433:                    'incorrectCODE', 'duplicateCODE',
 9434:                    'doublebubble', 'missingbubble',
 9435:                    'duplicateID', 'incorrectID'
 9436:     $arg         - extra information needed
 9437:        For errors:
 9438:          - duplicateID   - paper number that this studentID was seen before on
 9439:          - duplicateCODE - array ref of the paper numbers this CODE was
 9440:                            seen on before
 9441:          - incorrectCODE - current incorrect CODE 
 9442:          - doublebubble  - array ref of the bubble lines that have double
 9443:                            bubble errors
 9444:          - missingbubble - array ref of the bubble lines that have missing
 9445:                            bubble errors
 9446: 
 9447: =item  scantron_get_maxbubble() : 
 9448: 
 9449:    Arguments:
 9450:        $nav_error  - Reference to scalar which is a flag to indicate a
 9451:                       failure to retrieve a navmap object.
 9452:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
 9453:        calling routine should trap the error condition and display the warning
 9454:        found in &navmap_errormsg().
 9455: 
 9456:    Returns the maximum number of bubble lines that are expected to
 9457:    occur. Does this by walking the selected sequence rendering the
 9458:    resource and then checking &Apache::lonxml::get_problem_counter()
 9459:    for what the current value of the problem counter is.
 9460: 
 9461:    Caches the results to $env{'form.scantron_maxbubble'},
 9462:    $env{'form.scantron.bubble_lines.n'}, 
 9463:    $env{'form.scantron.first_bubble_line.n'} and
 9464:    $env{"form.scantron.sub_bubblelines.n"}
 9465:    which are the total number of bubble, lines, the number of bubble
 9466:    lines for response n and number of the first bubble line for response n,
 9467:    and a comma separated list of numbers of bubble lines for sub-questions
 9468:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
 9469: 
 9470: 
 9471: =item  scantron_validate_missingbubbles() : 
 9472: 
 9473:    Validates all scanlines in the selected file to not have any
 9474:     answers that don't have bubbles that have not been verified
 9475:     to be bubble free.
 9476: 
 9477: =item  scantron_process_students() : 
 9478: 
 9479:    Routine that does the actual grading of the bubble sheet information.
 9480: 
 9481:    The parsed scanline hash is added to %env 
 9482: 
 9483:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
 9484:    foreach resource , with the form data of
 9485: 
 9486: 	'submitted'     =>'scantron' 
 9487: 	'grade_target'  =>'grade',
 9488: 	'grade_username'=> username of student
 9489: 	'grade_domain'  => domain of student
 9490: 	'grade_courseid'=> of course
 9491: 	'grade_symb'    => symb of resource to grade
 9492: 
 9493:     This triggers a grading pass. The problem grading code takes care
 9494:     of converting the bubbled letter information (now in %env) into a
 9495:     valid submission.
 9496: 
 9497: =item  scantron_upload_scantron_data() :
 9498: 
 9499:     Creates the screen for adding a new bubble sheet data file to a course.
 9500: 
 9501: =item  scantron_upload_scantron_data_save() : 
 9502: 
 9503:    Adds a provided bubble information data file to the course if user
 9504:    has the correct privileges to do so. 
 9505: 
 9506: =item  valid_file() :
 9507: 
 9508:    Validates that the requested bubble data file exists in the course.
 9509: 
 9510: =item  scantron_download_scantron_data() : 
 9511: 
 9512:    Shows a list of the three internal files (original, corrected,
 9513:    skipped) for a specific bubble sheet data file that exists in the
 9514:    course.
 9515: 
 9516: =item  scantron_validate_ID() : 
 9517: 
 9518:    Validates all scanlines in the selected file to not have any
 9519:    invalid or underspecified student/employee IDs
 9520: 
 9521: =item navmap_errormsg() :
 9522: 
 9523:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
 9524:    Should be called whenever the request to instantiate a navmap object fails.  
 9525: 
 9526: =back
 9527: 
 9528: =cut

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