File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.636: download - view: text, annotated - select for diffs
Mon Aug 30 09:47:32 2010 UTC (13 years, 8 months ago) by wenzelju
Branches: MAIN
CVS tags: HEAD
Icons for grading-interface.

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.636 2010/08/30 09:47:32 wenzelju 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 Apache::lonstathelpers;
   47: use String::Similarity;
   48: use LONCAPA;
   49: 
   50: use POSIX qw(floor);
   51: 
   52: 
   53: 
   54: my %perm=();
   55: 
   56: #  These variables are used to recover from ssi errors
   57: 
   58: my $ssi_retries = 5;
   59: my $ssi_error;
   60: my $ssi_error_resource;
   61: my $ssi_error_message;
   62: 
   63: 
   64: sub ssi_with_retries {
   65:     my ($resource, $retries, %form) = @_;
   66:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
   67:     if ($response->is_error) {
   68: 	$ssi_error          = 1;
   69: 	$ssi_error_resource = $resource;
   70: 	$ssi_error_message  = $response->code . " " . $response->message;
   71:     }
   72: 
   73:     return $content;
   74: 
   75: }
   76: #
   77: #  Prodcuces an ssi retry failure error message to the user:
   78: #
   79: 
   80: sub ssi_print_error {
   81:     my ($r) = @_;
   82:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
   83:     $r->print('
   84: <br />
   85: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
   86: <p>
   87: '.&mt('Unable to retrieve a resource from a server:').'<br />
   88: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
   89: '.&mt('Error:').' '.$ssi_error_message.'
   90: </p>
   91: <p>'.
   92: &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 />'.
   93: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
   94: '</p>');
   95:     return;
   96: }
   97: 
   98: #
   99: # --- Retrieve the parts from the metadata file.---
  100: # Returns an array of everything that the resources stores away
  101: #
  102: 
  103: sub getpartlist {
  104:     my ($symb,$errorref) = @_;
  105: 
  106:     my $navmap   = Apache::lonnavmaps::navmap->new();
  107:     unless (ref($navmap)) {
  108:         if (ref($errorref)) { 
  109:             $$errorref = 'navmap';
  110:             return;
  111:         }
  112:     }
  113:     my $res      = $navmap->getBySymb($symb);
  114:     my $partlist = $res->parts();
  115:     my $url      = $res->src();
  116:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
  117: 
  118:     my @stores;
  119:     foreach my $part (@{ $partlist }) {
  120: 	foreach my $key (@metakeys) {
  121: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
  122: 	}
  123:     }
  124:     return @stores;
  125: }
  126: 
  127: #--- Format fullname, username:domain if different for display
  128: #--- Use anywhere where the student names are listed
  129: sub nameUserString {
  130:     my ($type,$fullname,$uname,$udom) = @_;
  131:     if ($type eq 'header') {
  132: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
  133:     } else {
  134: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
  135: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
  136:     }
  137: }
  138: 
  139: #--- Get the partlist and the response type for a given problem. ---
  140: #--- Indicate if a response type is coded handgraded or not. ---
  141: #--- Sets response_error pointer to "1" if navmaps object broken ---
  142: sub response_type {
  143:     my ($symb,$response_error) = @_;
  144: 
  145:     my $navmap = Apache::lonnavmaps::navmap->new();
  146:     unless (ref($navmap)) {
  147:         if (ref($response_error)) {
  148:             $$response_error = 1;
  149:         }
  150:         return;
  151:     }
  152:     my $res = $navmap->getBySymb($symb);
  153:     unless (ref($res)) {
  154:         $$response_error = 1;
  155:         return;
  156:     }
  157:     my $partlist = $res->parts();
  158:     my %vPart = 
  159: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
  160:     my (%response_types,%handgrade);
  161:     foreach my $part (@{ $partlist }) {
  162: 	next if (%vPart && !exists($vPart{$part}));
  163: 
  164: 	my @types = $res->responseType($part);
  165: 	my @ids = $res->responseIds($part);
  166: 	for (my $i=0; $i < scalar(@ids); $i++) {
  167: 	    $response_types{$part}{$ids[$i]} = $types[$i];
  168: 	    $handgrade{$part.'_'.$ids[$i]} = 
  169: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
  170: 				     '.handgrade',$symb);
  171: 	}
  172:     }
  173:     return ($partlist,\%handgrade,\%response_types);
  174: }
  175: 
  176: sub flatten_responseType {
  177:     my ($responseType) = @_;
  178:     my @part_response_id =
  179: 	map { 
  180: 	    my $part = $_;
  181: 	    map {
  182: 		[$part,$_]
  183: 		} sort(keys(%{ $responseType->{$part} }));
  184: 	} sort(keys(%$responseType));
  185:     return @part_response_id;
  186: }
  187: 
  188: sub get_display_part {
  189:     my ($partID,$symb)=@_;
  190:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
  191:     if (defined($display) and $display ne '') {
  192:         $display.= ' (<span class="LC_internal_info">'
  193:                   .&mt('Part ID: [_1]',$partID).'</span>)';
  194:     } else {
  195: 	$display=$partID;
  196:     }
  197:     return $display;
  198: }
  199: 
  200: sub reset_caches {
  201:     &reset_analyze_cache();
  202:     &reset_perm();
  203: }
  204: 
  205: {
  206:     my %analyze_cache;
  207:     my %analyze_cache_formkeys;
  208: 
  209:     sub reset_analyze_cache {
  210: 	undef(%analyze_cache);
  211:         undef(%analyze_cache_formkeys);
  212:     }
  213: 
  214:     sub get_analyze {
  215: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash)=@_;
  216: 	my $key = "$symb\0$uname\0$udom";
  217: 	if (exists($analyze_cache{$key})) {
  218:             my $getupdate = 0;
  219:             if (ref($add_to_hash) eq 'HASH') {
  220:                 foreach my $item (keys(%{$add_to_hash})) {
  221:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
  222:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
  223:                             $getupdate = 1;
  224:                             last;
  225:                         }
  226:                     } else {
  227:                         $getupdate = 1;
  228:                     }
  229:                 }
  230:             }
  231:             if (!$getupdate) {
  232:                 return $analyze_cache{$key};
  233:             }
  234:         }
  235: 
  236: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  237: 	$url=&Apache::lonnet::clutter($url);
  238:         my %form = ('grade_target'      => 'analyze',
  239:                     'grade_domain'      => $udom,
  240:                     'grade_symb'        => $symb,
  241:                     'grade_courseid'    =>  $env{'request.course.id'},
  242:                     'grade_username'    => $uname,
  243:                     'grade_noincrement' => $no_increment);
  244:         if (ref($add_to_hash)) {
  245:             %form = (%form,%{$add_to_hash});
  246:         } 
  247: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
  248: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  249: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  250:         if (ref($add_to_hash) eq 'HASH') {
  251:             $analyze_cache_formkeys{$key} = $add_to_hash;
  252:         } else {
  253:             $analyze_cache_formkeys{$key} = {};
  254:         }
  255: 	return $analyze_cache{$key} = \%analyze;
  256:     }
  257: 
  258:     sub get_order {
  259: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment)=@_;
  260: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment);
  261: 	return $analyze->{"$partid.$respid.shown"};
  262:     }
  263: 
  264:     sub get_radiobutton_correct_foil {
  265: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
  266: 	my $analyze = &get_analyze($symb,$uname,$udom);
  267:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom);
  268:         if (ref($foils) eq 'ARRAY') {
  269: 	    foreach my $foil (@{$foils}) {
  270: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  271: 		    return $foil;
  272: 	        }
  273: 	    }
  274: 	}
  275:     }
  276: 
  277:     sub scantron_partids_tograde {
  278:         my ($resource,$cid,$uname,$udom,$check_for_randomlist) = @_;
  279:         my (%analysis,@parts);
  280:         if (ref($resource)) {
  281:             my $symb = $resource->symb();
  282:             my $add_to_form;
  283:             if ($check_for_randomlist) {
  284:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
  285:             }
  286:             my $analyze = &get_analyze($symb,$uname,$udom,undef,$add_to_form);
  287:             if (ref($analyze) eq 'HASH') {
  288:                 %analysis = %{$analyze};
  289:             }
  290:             if (ref($analysis{'parts'}) eq 'ARRAY') {
  291:                 foreach my $part (@{$analysis{'parts'}}) {
  292:                     my ($id,$respid) = split(/\./,$part);
  293:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
  294:                         push(@parts,$part);
  295:                     }
  296:                 }
  297:             }
  298:         }
  299:         return (\%analysis,\@parts);
  300:     }
  301: 
  302: }
  303: 
  304: #--- Clean response type for display
  305: #--- Currently filters option/rank/radiobutton/match/essay/Task
  306: #        response types only.
  307: sub cleanRecord {
  308:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  309: 	$uname,$udom) = @_;
  310:     my $grayFont = '<span class="LC_internal_info">';
  311:     if ($response =~ /^(option|rank)$/) {
  312: 	my %answer=&Apache::lonnet::str2hash($answer);
  313: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  314: 	my ($toprow,$bottomrow);
  315: 	foreach my $foil (@$order) {
  316: 	    if ($grading{$foil} == 1) {
  317: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  318: 	    } else {
  319: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  320: 	    }
  321: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  322: 	}
  323: 	return '<blockquote><table border="1">'.
  324: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  325: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  326: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
  327:     } elsif ($response eq 'match') {
  328: 	my %answer=&Apache::lonnet::str2hash($answer);
  329: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  330: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  331: 	my ($toprow,$middlerow,$bottomrow);
  332: 	foreach my $foil (@$order) {
  333: 	    my $item=shift(@items);
  334: 	    if ($grading{$foil} == 1) {
  335: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  336: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  337: 	    } else {
  338: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  339: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  340: 	    }
  341: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  342: 	}
  343: 	return '<blockquote><table border="1">'.
  344: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  345: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  346: 	    $middlerow.'</tr>'.
  347: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  348: 	    $bottomrow.'</tr>'.'</table></blockquote>';
  349:     } elsif ($response eq 'radiobutton') {
  350: 	my %answer=&Apache::lonnet::str2hash($answer);
  351: 	my ($toprow,$bottomrow);
  352: 	my $correct = 
  353: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
  354: 	foreach my $foil (@$order) {
  355: 	    if (exists($answer{$foil})) {
  356: 		if ($foil eq $correct) {
  357: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  358: 		} else {
  359: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  360: 		}
  361: 	    } else {
  362: 		$toprow.='<td>'.&mt('false').'</td>';
  363: 	    }
  364: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  365: 	}
  366: 	return '<blockquote><table border="1">'.
  367: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  368: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  369: 	    $bottomrow.'</tr>'.'</table></blockquote>';
  370:     } elsif ($response eq 'essay') {
  371: 	if (! exists ($env{'form.'.$symb})) {
  372: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  373: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  374: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  375: 
  376: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  377: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  378: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  379: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  380: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  381: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  382: 	}
  383: 	$answer =~ s-\n-<br />-g;
  384: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  385:     } elsif ( $response eq 'organic') {
  386: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
  387: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  388: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  389: 	return $result;
  390:     } elsif ( $response eq 'Task') {
  391: 	if ( $answer eq 'SUBMITTED') {
  392: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  393: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  394: 	    return $result;
  395: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  396: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  397: 			       keys(%{$record}));
  398: 	    return join('<br />',($version,@matches));
  399: 			       
  400: 			       
  401: 	} else {
  402: 	    my $result =
  403: 		'<p>'
  404: 		.&mt('Overall result: [_1]',
  405: 		     $record->{$version."resource.$respid.$partid.status"})
  406: 		.'</p>';
  407: 	    
  408: 	    $result .= '<ul>';
  409: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  410: 			     keys(%{$record}));
  411: 	    foreach my $grade (sort(@grade)) {
  412: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  413: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  414: 				     $dim, $record->{$grade}).
  415: 			  '</li>';
  416: 	    }
  417: 	    $result.='</ul>';
  418: 	    return $result;
  419: 	}
  420:     } elsif ( $response =~ m/(?:numerical|formula)/) {
  421: 	$answer = 
  422: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  423: 							      $answer);
  424:     }
  425:     return $answer;
  426: }
  427: 
  428: #-- A couple of common js functions
  429: sub commonJSfunctions {
  430:     my $request = shift;
  431:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
  432:     function radioSelection(radioButton) {
  433: 	var selection=null;
  434: 	if (radioButton.length > 1) {
  435: 	    for (var i=0; i<radioButton.length; i++) {
  436: 		if (radioButton[i].checked) {
  437: 		    return radioButton[i].value;
  438: 		}
  439: 	    }
  440: 	} else {
  441: 	    if (radioButton.checked) return radioButton.value;
  442: 	}
  443: 	return selection;
  444:     }
  445: 
  446:     function pullDownSelection(selectOne) {
  447: 	var selection="";
  448: 	if (selectOne.length > 1) {
  449: 	    for (var i=0; i<selectOne.length; i++) {
  450: 		if (selectOne[i].selected) {
  451: 		    return selectOne[i].value;
  452: 		}
  453: 	    }
  454: 	} else {
  455:             // only one value it must be the selected one
  456: 	    return selectOne.value;
  457: 	}
  458:     }
  459: COMMONJSFUNCTIONS
  460: }
  461: 
  462: #--- Dumps the class list with usernames,list of sections,
  463: #--- section, ids and fullnames for each user.
  464: sub getclasslist {
  465:     my ($getsec,$filterlist,$getgroup) = @_;
  466:     my @getsec;
  467:     my @getgroup;
  468:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  469:     if (!ref($getsec)) {
  470: 	if ($getsec ne '' && $getsec ne 'all') {
  471: 	    @getsec=($getsec);
  472: 	}
  473:     } else {
  474: 	@getsec=@{$getsec};
  475:     }
  476:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  477:     if (!ref($getgroup)) {
  478: 	if ($getgroup ne '' && $getgroup ne 'all') {
  479: 	    @getgroup=($getgroup);
  480: 	}
  481:     } else {
  482: 	@getgroup=@{$getgroup};
  483:     }
  484:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  485: 
  486:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  487:     # Bail out if we were unable to get the classlist
  488:     return if (! defined($classlist));
  489:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  490:     #
  491:     my %sections;
  492:     my %fullnames;
  493:     foreach my $student (keys(%$classlist)) {
  494:         my $end      = 
  495:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  496:         my $start    = 
  497:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  498:         my $id       = 
  499:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  500:         my $section  = 
  501:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  502:         my $fullname = 
  503:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  504:         my $status   = 
  505:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  506:         my $group   = 
  507:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  508: 	# filter students according to status selected
  509: 	if ($filterlist && (!($stu_status =~ /Any/))) {
  510: 	    if (!($stu_status =~ $status)) {
  511: 		delete($classlist->{$student});
  512: 		next;
  513: 	    }
  514: 	}
  515: 	# filter students according to groups selected
  516: 	my @stu_groups = split(/,/,$group);
  517: 	if (@getgroup) {
  518: 	    my $exclude = 1;
  519: 	    foreach my $grp (@getgroup) {
  520: 	        foreach my $stu_group (@stu_groups) {
  521: 	            if ($stu_group eq $grp) {
  522: 	                $exclude = 0;
  523:     	            } 
  524: 	        }
  525:     	        if (($grp eq 'none') && !$group) {
  526:         	        $exclude = 0;
  527:         	}
  528: 	    }
  529: 	    if ($exclude) {
  530: 	        delete($classlist->{$student});
  531: 	    }
  532: 	}
  533: 	$section = ($section ne '' ? $section : 'none');
  534: 	if (&canview($section)) {
  535: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  536: 		$sections{$section}++;
  537: 		if ($classlist->{$student}) {
  538: 		    $fullnames{$student}=$fullname;
  539: 		}
  540: 	    } else {
  541: 		delete($classlist->{$student});
  542: 	    }
  543: 	} else {
  544: 	    delete($classlist->{$student});
  545: 	}
  546:     }
  547:     my %seen = ();
  548:     my @sections = sort(keys(%sections));
  549:     return ($classlist,\@sections,\%fullnames);
  550: }
  551: 
  552: sub canmodify {
  553:     my ($sec)=@_;
  554:     if ($perm{'mgr'}) {
  555: 	if (!defined($perm{'mgr_section'})) {
  556: 	    # can modify whole class
  557: 	    return 1;
  558: 	} else {
  559: 	    if ($sec eq $perm{'mgr_section'}) {
  560: 		#can modify the requested section
  561: 		return 1;
  562: 	    } else {
  563: 		# can't modify the request section
  564: 		return 0;
  565: 	    }
  566: 	}
  567:     }
  568:     #can't modify
  569:     return 0;
  570: }
  571: 
  572: sub canview {
  573:     my ($sec)=@_;
  574:     if ($perm{'vgr'}) {
  575: 	if (!defined($perm{'vgr_section'})) {
  576: 	    # can modify whole class
  577: 	    return 1;
  578: 	} else {
  579: 	    if ($sec eq $perm{'vgr_section'}) {
  580: 		#can modify the requested section
  581: 		return 1;
  582: 	    } else {
  583: 		# can't modify the request section
  584: 		return 0;
  585: 	    }
  586: 	}
  587:     }
  588:     #can't modify
  589:     return 0;
  590: }
  591: 
  592: #--- Retrieve the grade status of a student for all the parts
  593: sub student_gradeStatus {
  594:     my ($symb,$udom,$uname,$partlist) = @_;
  595:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  596:     my %partstatus = ();
  597:     foreach (@$partlist) {
  598: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  599: 	$status              = 'nothing' if ($status eq '');
  600: 	$partstatus{$_}      = $status;
  601: 	my $subkey           = "resource.$_.submitted_by";
  602: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  603:     }
  604:     return %partstatus;
  605: }
  606: 
  607: # hidden form and javascript that calls the form
  608: # Use by verifyscript and viewgrades
  609: # Shows a student's view of problem and submission
  610: sub jscriptNform {
  611:     my ($symb) = @_;
  612:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  613:     my $jscript= &Apache::lonhtmlcommon::scripttag(
  614: 	'    function viewOneStudent(user,domain) {'."\n".
  615: 	'	document.onestudent.student.value = user;'."\n".
  616: 	'	document.onestudent.userdom.value = domain;'."\n".
  617: 	'	document.onestudent.submit();'."\n".
  618: 	'    }'."\n".
  619: 	"\n");
  620:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  621: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  622: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  623: 	'<input type="hidden" name="command" value="submission" />'."\n".
  624: 	'<input type="hidden" name="student" value="" />'."\n".
  625: 	'<input type="hidden" name="userdom" value="" />'."\n".
  626: 	'</form>'."\n";
  627:     return $jscript;
  628: }
  629: 
  630: 
  631: 
  632: # Given the score (as a number [0-1] and the weight) what is the final
  633: # point value? This function will round to the nearest tenth, third,
  634: # or quarter if one of those is within the tolerance of .00001.
  635: sub compute_points {
  636:     my ($score, $weight) = @_;
  637:     
  638:     my $tolerance = .00001;
  639:     my $points = $score * $weight;
  640: 
  641:     # Check for nearness to 1/x.
  642:     my $check_for_nearness = sub {
  643:         my ($factor) = @_;
  644:         my $num = ($points * $factor) + $tolerance;
  645:         my $floored_num = floor($num);
  646:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  647:             return $floored_num / $factor;
  648:         }
  649:         return $points;
  650:     };
  651: 
  652:     $points = $check_for_nearness->(10);
  653:     $points = $check_for_nearness->(3);
  654:     $points = $check_for_nearness->(4);
  655:     
  656:     return $points;
  657: }
  658: 
  659: #------------------ End of general use routines --------------------
  660: 
  661: #
  662: # Find most similar essay
  663: #
  664: 
  665: sub most_similar {
  666:     my ($uname,$udom,$uessay,$old_essays)=@_;
  667: 
  668: # ignore spaces and punctuation
  669: 
  670:     $uessay=~s/\W+/ /gs;
  671: 
  672: # ignore empty submissions (occuring when only files are sent)
  673: 
  674:     unless ($uessay=~/\w+/s) { return ''; }
  675: 
  676: # these will be returned. Do not care if not at least 50 percent similar
  677:     my $limit=0.6;
  678:     my $sname='';
  679:     my $sdom='';
  680:     my $scrsid='';
  681:     my $sessay='';
  682: # go through all essays ...
  683:     foreach my $tkey (keys(%$old_essays)) {
  684: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  685: # ... except the same student
  686:         next if (($tname eq $uname) && ($tdom eq $udom));
  687: 	my $tessay=$old_essays->{$tkey};
  688: 	$tessay=~s/\W+/ /gs;
  689: # String similarity gives up if not even limit
  690: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  691: # Found one
  692: 	if ($tsimilar>$limit) {
  693: 	    $limit=$tsimilar;
  694: 	    $sname=$tname;
  695: 	    $sdom=$tdom;
  696: 	    $scrsid=$tcrsid;
  697: 	    $sessay=$old_essays->{$tkey};
  698: 	}
  699:     }
  700:     if ($limit>0.6) {
  701:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  702:     } else {
  703:        return ('','','','',0);
  704:     }
  705: }
  706: 
  707: #-------------------------------------------------------------------
  708: 
  709: #------------------------------------ Receipt Verification Routines
  710: #
  711: 
  712: sub initialverifyreceipt {
  713:    my ($request,$symb) = @_;
  714:    &commonJSfunctions($request);
  715:    return '<form name="gradingMenu"><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
  716:         &Apache::lonnet::recprefix($env{'request.course.id'}).
  717:         '-<input type="text" name="receipt" size="4" />'.
  718:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  719:         '<input type="hidden" name="command" value="verify" />'.
  720:         "</form>\n";
  721: }
  722: 
  723: #--- Check whether a receipt number is valid.---
  724: sub verifyreceipt {
  725:     my ($request,$symb)  = @_;
  726: 
  727:     my $courseid = $env{'request.course.id'};
  728:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  729: 	$env{'form.receipt'};
  730:     $receipt     =~ s/[^\-\d]//g;
  731: 
  732:     my $title.=
  733: 	'<h3><span class="LC_info">'.
  734: 	&mt('Verifying Receipt Number [_1]',$receipt).
  735: 	'</span></h3>'."\n";
  736: 
  737:     my ($string,$contents,$matches) = ('','',0);
  738:     my (undef,undef,$fullname) = &getclasslist('all','0');
  739:     
  740:     my $receiptparts=0;
  741:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  742: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  743:     my $parts=['0'];
  744:     if ($receiptparts) {
  745:         my $res_error; 
  746:         ($parts)=&response_type($symb,\$res_error);
  747:         if ($res_error) {
  748:             return &navmap_errormsg();
  749:         } 
  750:     }
  751:     
  752:     my $header = 
  753: 	&Apache::loncommon::start_data_table().
  754: 	&Apache::loncommon::start_data_table_header_row().
  755: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  756: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  757: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  758:     if ($receiptparts) {
  759: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  760:     }
  761:     $header.=
  762: 	&Apache::loncommon::end_data_table_header_row();
  763: 
  764:     foreach (sort 
  765: 	     {
  766: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  767: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  768: 		 }
  769: 		 return $a cmp $b;
  770: 	     } (keys(%$fullname))) {
  771: 	my ($uname,$udom)=split(/\:/);
  772: 	foreach my $part (@$parts) {
  773: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  774: 		$contents.=
  775: 		    &Apache::loncommon::start_data_table_row().
  776: 		    '<td>&nbsp;'."\n".
  777: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  778: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  779: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  780: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  781: 		if ($receiptparts) {
  782: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  783: 		}
  784: 		$contents.= 
  785: 		    &Apache::loncommon::end_data_table_row()."\n";
  786: 		
  787: 		$matches++;
  788: 	    }
  789: 	}
  790:     }
  791:     if ($matches == 0) {
  792:         $string = $title
  793:                  .'<p class="LC_warning">'
  794:                  .&mt('No match found for the above receipt number.')
  795:                  .'</p>';
  796:     } else {
  797: 	$string = &jscriptNform($symb).$title.
  798: 	    '<p>'.
  799: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
  800: 	    '</p>'.
  801: 	    $header.
  802: 	    $contents.
  803: 	    &Apache::loncommon::end_data_table()."\n";
  804:     }
  805:     return $string;
  806: }
  807: 
  808: #--- This is called by a number of programs.
  809: #--- Called from the Grading Menu - View/Grade an individual student
  810: #--- Also called directly when one clicks on the subm button 
  811: #    on the problem page.
  812: sub listStudents {
  813:     my ($request,$symb,$submitonly) = @_;
  814: 
  815:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  816:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  817:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  818:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  819:     unless ($submitonly) {
  820:        $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  821:     }
  822: 
  823:     my $result='';
  824:     my $res_error;
  825:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
  826: 
  827:     my %lt = &Apache::lonlocal::texthash (
  828: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
  829: 		'single'   => 'Please select the student before clicking on the Next button.',
  830: 	     );
  831:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
  832:     function checkSelect(checkBox) {
  833: 	var ctr=0;
  834: 	var sense="";
  835: 	if (checkBox.length > 1) {
  836: 	    for (var i=0; i<checkBox.length; i++) {
  837: 		if (checkBox[i].checked) {
  838: 		    ctr++;
  839: 		}
  840: 	    }
  841: 	    sense = '$lt{'multiple'}';
  842: 	} else {
  843: 	    if (checkBox.checked) {
  844: 		ctr = 1;
  845: 	    }
  846: 	    sense = '$lt{'single'}';
  847: 	}
  848: 	if (ctr == 0) {
  849: 	    alert(sense);
  850: 	    return false;
  851: 	}
  852: 	document.gradesub.submit();
  853:     }
  854: 
  855:     function reLoadList(formname) {
  856: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  857: 	formname.command.value = 'submission';
  858: 	formname.submit();
  859:     }
  860: LISTJAVASCRIPT
  861: 
  862:     &commonJSfunctions($request);
  863:     $request->print($result);
  864: 
  865:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  866: 	"\n";
  867: 	
  868:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
  869:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
  870:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
  871:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
  872:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
  873:                   .&Apache::lonhtmlcommon::row_closure();
  874:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
  875:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
  876:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
  877:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
  878:                   .&Apache::lonhtmlcommon::row_closure();
  879: 
  880:     my $submission_options;
  881:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  882:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  883:     $env{'form.Status'} = $saveStatus;
  884:     $submission_options.=
  885:         '<span class="LC_nobreak">'.
  886:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
  887:         &mt('last submission only').' </label></span>'."\n".
  888:         '<span class="LC_nobreak">'.
  889:         '<label><input type="radio" name="lastSub" value="last" /> '.
  890:         &mt('last submission &amp; parts info').' </label></span>'."\n".
  891:         '<span class="LC_nobreak">'.
  892:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
  893:         &mt('by dates and submissions').'</label></span>'."\n".
  894:         '<span class="LC_nobreak">'.
  895:         '<label><input type="radio" name="lastSub" value="all" /> '.
  896:         &mt('all details').'</label></span>';
  897:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
  898:                   .$submission_options
  899:                   .&Apache::lonhtmlcommon::row_closure();
  900: 
  901:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
  902:                   .'<select name="increment">'
  903:                   .'<option value="1">'.&mt('Whole Points').'</option>'
  904:                   .'<option value=".5">'.&mt('Half Points').'</option>'
  905:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
  906:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
  907:                   .'</select>'
  908:                   .&Apache::lonhtmlcommon::row_closure();
  909: 
  910:     $gradeTable .= 
  911:         &build_section_inputs().
  912: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
  913: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  914: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
  915: 
  916:     if (exists($env{'form.Status'})) {
  917: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
  918:     } else {
  919:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
  920:                       .&Apache::lonhtmlcommon::StatusOptions(
  921:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
  922:                       .&Apache::lonhtmlcommon::row_closure();
  923:     }
  924: 
  925:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
  926:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
  927:                   .&Apache::lonhtmlcommon::row_closure(1)
  928:                   .&Apache::lonhtmlcommon::end_pick_box();
  929: 
  930:     $gradeTable .= '<p>'
  931:                   .&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"
  932:                   .'<input type="hidden" name="command" value="processGroup" />'
  933:                   .'</p>';
  934: 
  935: # checkall buttons
  936:     $gradeTable.=&check_script('gradesub', 'stuinfo');
  937:     $gradeTable.='<input type="button" '."\n".
  938:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
  939:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
  940:     $gradeTable.=&check_buttons();
  941:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
  942:     $gradeTable.= &Apache::loncommon::start_data_table().
  943: 	&Apache::loncommon::start_data_table_header_row();
  944:     my $loop = 0;
  945:     while ($loop < 2) {
  946: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
  947: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
  948: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
  949: 	    foreach my $part (sort(@$partlist)) {
  950: 		my $display_part=
  951: 		    &get_display_part((split(/_/,$part))[0],$symb);
  952: 		$gradeTable.=
  953: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
  954: 	    }
  955: 	} elsif ($submitonly eq 'queued') {
  956: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
  957: 	}
  958: 	$loop++;
  959: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
  960:     }
  961:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
  962: 
  963:     my $ctr = 0;
  964:     foreach my $student (sort 
  965: 			 {
  966: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  967: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  968: 			     }
  969: 			     return $a cmp $b;
  970: 			 }
  971: 			 (keys(%$fullname))) {
  972: 	my ($uname,$udom) = split(/:/,$student);
  973: 
  974: 	my %status = ();
  975: 
  976: 	if ($submitonly eq 'queued') {
  977: 	    my %queue_status = 
  978: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
  979: 							$udom,$uname);
  980: 	    next if (!defined($queue_status{'gradingqueue'}));
  981: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
  982: 	}
  983: 
  984: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
  985: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
  986: 	    my $submitted = 0;
  987: 	    my $graded = 0;
  988: 	    my $incorrect = 0;
  989: 	    foreach (keys(%status)) {
  990: 		$submitted = 1 if ($status{$_} ne 'nothing');
  991: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
  992: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
  993: 		
  994: 		my ($foo,$partid,$foo1) = split(/\./,$_);
  995: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
  996: 		    $submitted = 0;
  997: 		    my ($part)=split(/\./,$partid);
  998: 		    $gradeTable.='<input type="hidden" name="'.
  999: 			$student.':'.$part.':submitted_by" value="'.
 1000: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1001: 		}
 1002: 	    }
 1003: 	    
 1004: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1005: 				     $submitonly eq 'incorrect' ||
 1006: 				     $submitonly eq 'graded'));
 1007: 	    next if (!$graded && ($submitonly eq 'graded'));
 1008: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1009: 	}
 1010: 
 1011: 	$ctr++;
 1012: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1013:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1014: 	if ( $perm{'vgr'} eq 'F' ) {
 1015: 	    if ($ctr%2 ==1) {
 1016: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1017: 	    }
 1018: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1019:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1020:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1021: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1022: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1023: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1024: 
 1025: 	    if ($submitonly ne 'all') {
 1026: 		foreach (sort(keys(%status))) {
 1027: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1028: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1029: 		}
 1030: 	    }
 1031: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1032: 	    if ($ctr%2 ==0) {
 1033: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1034: 	    }
 1035: 	}
 1036:     }
 1037:     if ($ctr%2 ==1) {
 1038: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1039: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1040: 		foreach (@$partlist) {
 1041: 		    $gradeTable.='<td>&nbsp;</td>';
 1042: 		}
 1043: 	    } elsif ($submitonly eq 'queued') {
 1044: 		$gradeTable.='<td>&nbsp;</td>';
 1045: 	    }
 1046: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1047:     }
 1048: 
 1049:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1050:         '<input type="button" '.
 1051:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
 1052:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1053:     if ($ctr == 0) {
 1054: 	my $num_students=(scalar(keys(%$fullname)));
 1055: 	if ($num_students eq 0) {
 1056: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1057: 	} else {
 1058: 	    my $submissions='submissions';
 1059: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1060: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1061: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1062: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1063: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
 1064: 		    $num_students).
 1065: 		'</span><br />';
 1066: 	}
 1067:     } elsif ($ctr == 1) {
 1068: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1069:     }
 1070:     $request->print($gradeTable);
 1071:     return '';
 1072: }
 1073: 
 1074: #---- Called from the listStudents routine
 1075: 
 1076: sub check_script {
 1077:     my ($form, $type)=@_;
 1078:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
 1079:     function checkall() {
 1080:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1081:             ele = document.forms.'.$form.'.elements[i];
 1082:             if (ele.name == "'.$type.'") {
 1083:             document.forms.'.$form.'.elements[i].checked=true;
 1084:                                        }
 1085:         }
 1086:     }
 1087: 
 1088:     function checksec() {
 1089:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1090:             ele = document.forms.'.$form.'.elements[i];
 1091:            string = document.forms.'.$form.'.chksec.value;
 1092:            if
 1093:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1094:               document.forms.'.$form.'.elements[i].checked=true;
 1095:             }
 1096:         }
 1097:     }
 1098: 
 1099: 
 1100:     function uncheckall() {
 1101:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1102:             ele = document.forms.'.$form.'.elements[i];
 1103:             if (ele.name == "'.$type.'") {
 1104:             document.forms.'.$form.'.elements[i].checked=false;
 1105:                                        }
 1106:         }
 1107:     }
 1108: 
 1109: '."\n");
 1110:     return $chkallscript;
 1111: }
 1112: 
 1113: sub check_buttons {
 1114:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1115:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1116:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1117:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1118:     return $buttons;
 1119: }
 1120: 
 1121: #     Displays the submissions for one student or a group of students
 1122: sub processGroup {
 1123:     my ($request,$symb)  = @_;
 1124:     my $ctr        = 0;
 1125:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1126:     my $total      = scalar(@stuchecked)-1;
 1127: 
 1128:     foreach my $student (@stuchecked) {
 1129: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1130: 	$env{'form.student'}        = $uname;
 1131: 	$env{'form.userdom'}        = $udom;
 1132: 	$env{'form.fullname'}       = $fullname;
 1133: 	&submission($request,$ctr,$total,$symb);
 1134: 	$ctr++;
 1135:     }
 1136:     return '';
 1137: }
 1138: 
 1139: #------------------------------------------------------------------------------------
 1140: #
 1141: #-------------------------- Next few routines handles grading by student, essentially
 1142: #                           handles essay response type problem/part
 1143: #
 1144: #--- Javascript to handle the submission page functionality ---
 1145: sub sub_page_js {
 1146:     my $request = shift;
 1147: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1148:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1149:     function updateRadio(formname,id,weight) {
 1150: 	var gradeBox = formname["GD_BOX"+id];
 1151: 	var radioButton = formname["RADVAL"+id];
 1152: 	var oldpts = formname["oldpts"+id].value;
 1153: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1154: 	gradeBox.value = pts;
 1155: 	var resetbox = false;
 1156: 	if (isNaN(pts) || pts < 0) {
 1157: 	    alert("$alertmsg"+pts);
 1158: 	    for (var i=0; i<radioButton.length; i++) {
 1159: 		if (radioButton[i].checked) {
 1160: 		    gradeBox.value = i;
 1161: 		    resetbox = true;
 1162: 		}
 1163: 	    }
 1164: 	    if (!resetbox) {
 1165: 		formtextbox.value = "";
 1166: 	    }
 1167: 	    return;
 1168: 	}
 1169: 
 1170: 	if (pts > weight) {
 1171: 	    var resp = confirm("You entered a value ("+pts+
 1172: 			       ") greater than the weight for the part. Accept?");
 1173: 	    if (resp == false) {
 1174: 		gradeBox.value = oldpts;
 1175: 		return;
 1176: 	    }
 1177: 	}
 1178: 
 1179: 	for (var i=0; i<radioButton.length; i++) {
 1180: 	    radioButton[i].checked=false;
 1181: 	    if (pts == i && pts != "") {
 1182: 		radioButton[i].checked=true;
 1183: 	    }
 1184: 	}
 1185: 	updateSelect(formname,id);
 1186: 	formname["stores"+id].value = "0";
 1187:     }
 1188: 
 1189:     function writeBox(formname,id,pts) {
 1190: 	var gradeBox = formname["GD_BOX"+id];
 1191: 	if (checkSolved(formname,id) == 'update') {
 1192: 	    gradeBox.value = pts;
 1193: 	} else {
 1194: 	    var oldpts = formname["oldpts"+id].value;
 1195: 	    gradeBox.value = oldpts;
 1196: 	    var radioButton = formname["RADVAL"+id];
 1197: 	    for (var i=0; i<radioButton.length; i++) {
 1198: 		radioButton[i].checked=false;
 1199: 		if (i == oldpts) {
 1200: 		    radioButton[i].checked=true;
 1201: 		}
 1202: 	    }
 1203: 	}
 1204: 	formname["stores"+id].value = "0";
 1205: 	updateSelect(formname,id);
 1206: 	return;
 1207:     }
 1208: 
 1209:     function clearRadBox(formname,id) {
 1210: 	if (checkSolved(formname,id) == 'noupdate') {
 1211: 	    updateSelect(formname,id);
 1212: 	    return;
 1213: 	}
 1214: 	gradeSelect = formname["GD_SEL"+id];
 1215: 	for (var i=0; i<gradeSelect.length; i++) {
 1216: 	    if (gradeSelect[i].selected) {
 1217: 		var selectx=i;
 1218: 	    }
 1219: 	}
 1220: 	var stores = formname["stores"+id];
 1221: 	if (selectx == stores.value) { return };
 1222: 	var gradeBox = formname["GD_BOX"+id];
 1223: 	gradeBox.value = "";
 1224: 	var radioButton = formname["RADVAL"+id];
 1225: 	for (var i=0; i<radioButton.length; i++) {
 1226: 	    radioButton[i].checked=false;
 1227: 	}
 1228: 	stores.value = selectx;
 1229:     }
 1230: 
 1231:     function checkSolved(formname,id) {
 1232: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1233: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1234: 	    if (!reply) {return "noupdate";}
 1235: 	    formname.overRideScore.value = 'yes';
 1236: 	}
 1237: 	return "update";
 1238:     }
 1239: 
 1240:     function updateSelect(formname,id) {
 1241: 	formname["GD_SEL"+id][0].selected = true;
 1242: 	return;
 1243:     }
 1244: 
 1245: //=========== Check that a point is assigned for all the parts  ============
 1246:     function checksubmit(formname,val,total,parttot) {
 1247: 	formname.gradeOpt.value = val;
 1248: 	if (val == "Save & Next") {
 1249: 	    for (i=0;i<=total;i++) {
 1250: 		for (j=0;j<parttot;j++) {
 1251: 		    var partid = formname["partid"+i+"_"+j].value;
 1252: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1253: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1254: 			if (points == "") {
 1255: 			    var name = formname["name"+i].value;
 1256: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1257: 			    var resp = confirm("You did not assign a score for "+studentID+
 1258: 					       ", part "+partid+". Continue?");
 1259: 			    if (resp == false) {
 1260: 				formname["GD_BOX"+i+"_"+partid].focus();
 1261: 				return false;
 1262: 			    }
 1263: 			}
 1264: 		    }
 1265: 		    
 1266: 		}
 1267: 	    }
 1268: 	    
 1269: 	}
 1270: 	formname.submit();
 1271:     }
 1272: 
 1273: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1274:     function checkSubmitPage(formname,total) {
 1275: 	noscore = new Array(100);
 1276: 	var ptr = 0;
 1277: 	for (i=1;i<total;i++) {
 1278: 	    var partid = formname["q_"+i].value;
 1279: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1280: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1281: 		var status = formname["solved"+i+"_"+partid].value;
 1282: 		if (points == "" && status != "correct_by_student") {
 1283: 		    noscore[ptr] = i;
 1284: 		    ptr++;
 1285: 		}
 1286: 	    }
 1287: 	}
 1288: 	if (ptr != 0) {
 1289: 	    var sense = ptr == 1 ? ": " : "s: ";
 1290: 	    var prolist = "";
 1291: 	    if (ptr == 1) {
 1292: 		prolist = noscore[0];
 1293: 	    } else {
 1294: 		var i = 0;
 1295: 		while (i < ptr-1) {
 1296: 		    prolist += noscore[i]+", ";
 1297: 		    i++;
 1298: 		}
 1299: 		prolist += "and "+noscore[i];
 1300: 	    }
 1301: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1302: 	    if (resp == false) {
 1303: 		return false;
 1304: 	    }
 1305: 	}
 1306: 
 1307: 	formname.submit();
 1308:     }
 1309: SUBJAVASCRIPT
 1310: }
 1311: 
 1312: #--- javascript for essay type problem --
 1313: sub sub_page_kw_js {
 1314:     my $request = shift;
 1315:     my $iconpath = $request->dir_config('lonIconsURL');
 1316:     &commonJSfunctions($request);
 1317: 
 1318:     my $inner_js_msg_central= (<<INNERJS);
 1319: <script type="text/javascript">
 1320:     function checkInput() {
 1321:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1322:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1323:       var usrctr = document.msgcenter.usrctr.value;
 1324:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1325:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1326: 
 1327:       var msgchk = "";
 1328:       if (document.msgcenter.subchk.checked) {
 1329:          msgchk = "msgsub,";
 1330:       }
 1331:       var includemsg = 0;
 1332:       for (var i=1; i<=nmsg; i++) {
 1333:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1334:           var frmmsg = document.msgcenter["msg"+i];
 1335:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1336:           var showflg = opener.document.SCORE["shownOnce"+i];
 1337:           showflg.value = "1";
 1338:           var chkbox = document.msgcenter["msgn"+i];
 1339:           if (chkbox.checked) {
 1340:              msgchk += "savemsg"+i+",";
 1341:              includemsg = 1;
 1342:           }
 1343:       }
 1344:       if (document.msgcenter.newmsgchk.checked) {
 1345:          msgchk += "newmsg"+usrctr;
 1346:          includemsg = 1;
 1347:       }
 1348:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1349:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1350:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1351:       includemsg.value = msgchk;
 1352: 
 1353:       self.close()
 1354: 
 1355:     }
 1356: </script>
 1357: INNERJS
 1358: 
 1359:     my $inner_js_highlight_central= (<<INNERJS);
 1360: <script type="text/javascript">
 1361:     function updateChoice(flag) {
 1362:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1363:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1364:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1365:       opener.document.SCORE.refresh.value = "on";
 1366:       if (opener.document.SCORE.keywords.value!=""){
 1367:          opener.document.SCORE.submit();
 1368:       }
 1369:       self.close()
 1370:     }
 1371: </script>
 1372: INNERJS
 1373: 
 1374:     my $start_page_msg_central = 
 1375:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1376: 				       {'js_ready'  => 1,
 1377: 					'only_body' => 1,
 1378: 					'bgcolor'   =>'#FFFFFF',});
 1379:     my $end_page_msg_central = 
 1380: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1381: 
 1382: 
 1383:     my $start_page_highlight_central = 
 1384:         &Apache::loncommon::start_page('Highlight Central',
 1385: 				       $inner_js_highlight_central,
 1386: 				       {'js_ready'  => 1,
 1387: 					'only_body' => 1,
 1388: 					'bgcolor'   =>'#FFFFFF',});
 1389:     my $end_page_highlight_central = 
 1390: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1391: 
 1392:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1393:     $docopen=~s/^document\.//;
 1394:     my $alertmsg = &mt('Please select a word or group of words from document and then click this link.');
 1395:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1396: 
 1397: //===================== Show list of keywords ====================
 1398:   function keywords(formname) {
 1399:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
 1400:     if (nret==null) return;
 1401:     formname.keywords.value = nret;
 1402: 
 1403:     if (formname.keywords.value != "") {
 1404: 	formname.refresh.value = "on";
 1405: 	formname.submit();
 1406:     }
 1407:     return;
 1408:   }
 1409: 
 1410: //===================== Script to view submitted by ==================
 1411:   function viewSubmitter(submitter) {
 1412:     document.SCORE.refresh.value = "on";
 1413:     document.SCORE.NCT.value = "1";
 1414:     document.SCORE.unamedom0.value = submitter;
 1415:     document.SCORE.submit();
 1416:     return;
 1417:   }
 1418: 
 1419: //===================== Script to add keyword(s) ==================
 1420:   function getSel() {
 1421:     if (document.getSelection) txt = document.getSelection();
 1422:     else if (document.selection) txt = document.selection.createRange().text;
 1423:     else return;
 1424:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1425:     if (cleantxt=="") {
 1426: 	alert("$alertmsg");
 1427: 	return;
 1428:     }
 1429:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
 1430:     if (nret==null) return;
 1431:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1432:     if (document.SCORE.keywords.value != "") {
 1433: 	document.SCORE.refresh.value = "on";
 1434: 	document.SCORE.submit();
 1435:     }
 1436:     return;
 1437:   }
 1438: 
 1439: //====================== Script for composing message ==============
 1440:    // preload images
 1441:    img1 = new Image();
 1442:    img1.src = "$iconpath/mailbkgrd.gif";
 1443:    img2 = new Image();
 1444:    img2.src = "$iconpath/mailto.gif";
 1445: 
 1446:   function msgCenter(msgform,usrctr,fullname) {
 1447:     var Nmsg  = msgform.savemsgN.value;
 1448:     savedMsgHeader(Nmsg,usrctr,fullname);
 1449:     var subject = msgform.msgsub.value;
 1450:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1451:     re = /msgsub/;
 1452:     var shwsel = "";
 1453:     if (re.test(msgchk)) { shwsel = "checked" }
 1454:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1455:     displaySubject(checkEntities(subject),shwsel);
 1456:     for (var i=1; i<=Nmsg; i++) {
 1457: 	var testmsg = "savemsg"+i+",";
 1458: 	re = new RegExp(testmsg,"g");
 1459: 	shwsel = "";
 1460: 	if (re.test(msgchk)) { shwsel = "checked" }
 1461: 	var message = document.SCORE["savemsg"+i].value;
 1462: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1463: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1464: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1465:     }
 1466:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1467:     shwsel = "";
 1468:     re = /newmsg/;
 1469:     if (re.test(msgchk)) { shwsel = "checked" }
 1470:     newMsg(newmsg,shwsel);
 1471:     msgTail(); 
 1472:     return;
 1473:   }
 1474: 
 1475:   function checkEntities(strx) {
 1476:     if (strx.length == 0) return strx;
 1477:     var orgStr = ["&", "<", ">", '"']; 
 1478:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1479:     var counter = 0;
 1480:     while (counter < 4) {
 1481: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1482: 	counter++;
 1483:     }
 1484:     return strx;
 1485:   }
 1486: 
 1487:   function strReplace(strx, orgStr, newStr) {
 1488:     return strx.split(orgStr).join(newStr);
 1489:   }
 1490: 
 1491:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1492:     var height = 70*Nmsg+250;
 1493:     var scrollbar = "no";
 1494:     if (height > 600) {
 1495: 	height = 600;
 1496: 	scrollbar = "yes";
 1497:     }
 1498:     var xpos = (screen.width-600)/2;
 1499:     xpos = (xpos < 0) ? '0' : xpos;
 1500:     var ypos = (screen.height-height)/2-30;
 1501:     ypos = (ypos < 0) ? '0' : ypos;
 1502: 
 1503:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
 1504:     pWin.focus();
 1505:     pDoc = pWin.document;
 1506:     pDoc.$docopen;
 1507:     pDoc.write('$start_page_msg_central');
 1508: 
 1509:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1510:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1511:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
 1512: 
 1513:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1514:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1515:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
 1516: }
 1517:     function displaySubject(msg,shwsel) {
 1518:     pDoc = pWin.document;
 1519:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1520:     pDoc.write("<td>Subject<\\/td>");
 1521:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1522:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1523: }
 1524: 
 1525:   function displaySavedMsg(ctr,msg,shwsel) {
 1526:     pDoc = pWin.document;
 1527:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1528:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1529:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1530:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1531: }
 1532: 
 1533:   function newMsg(newmsg,shwsel) {
 1534:     pDoc = pWin.document;
 1535:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1536:     pDoc.write("<td align=\\"center\\">New<\\/td>");
 1537:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1538:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1539: }
 1540: 
 1541:   function msgTail() {
 1542:     pDoc = pWin.document;
 1543:     pDoc.write("<\\/table>");
 1544:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1545:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1546:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
 1547:     pDoc.write("<\\/form>");
 1548:     pDoc.write('$end_page_msg_central');
 1549:     pDoc.close();
 1550: }
 1551: 
 1552: //====================== Script for keyword highlight options ==============
 1553:   function kwhighlight() {
 1554:     var kwclr    = document.SCORE.kwclr.value;
 1555:     var kwsize   = document.SCORE.kwsize.value;
 1556:     var kwstyle  = document.SCORE.kwstyle.value;
 1557:     var redsel = "";
 1558:     var grnsel = "";
 1559:     var blusel = "";
 1560:     if (kwclr=="red")   {var redsel="checked"};
 1561:     if (kwclr=="green") {var grnsel="checked"};
 1562:     if (kwclr=="blue")  {var blusel="checked"};
 1563:     var sznsel = "";
 1564:     var sz1sel = "";
 1565:     var sz2sel = "";
 1566:     if (kwsize=="0")  {var sznsel="checked"};
 1567:     if (kwsize=="+1") {var sz1sel="checked"};
 1568:     if (kwsize=="+2") {var sz2sel="checked"};
 1569:     var synsel = "";
 1570:     var syisel = "";
 1571:     var sybsel = "";
 1572:     if (kwstyle=="")    {var synsel="checked"};
 1573:     if (kwstyle=="<i>") {var syisel="checked"};
 1574:     if (kwstyle=="<b>") {var sybsel="checked"};
 1575:     highlightCentral();
 1576:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
 1577:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
 1578:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
 1579:     highlightend();
 1580:     return;
 1581:   }
 1582: 
 1583:   function highlightCentral() {
 1584: //    if (window.hwdWin) window.hwdWin.close();
 1585:     var xpos = (screen.width-400)/2;
 1586:     xpos = (xpos < 0) ? '0' : xpos;
 1587:     var ypos = (screen.height-330)/2-30;
 1588:     ypos = (ypos < 0) ? '0' : ypos;
 1589: 
 1590:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1591:     hwdWin.focus();
 1592:     var hDoc = hwdWin.document;
 1593:     hDoc.$docopen;
 1594:     hDoc.write('$start_page_highlight_central');
 1595:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1596:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
 1597: 
 1598:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1599:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1600:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
 1601:   }
 1602: 
 1603:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1604:     var hDoc = hwdWin.document;
 1605:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1606:     hDoc.write("<td align=\\"left\\">");
 1607:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
 1608:     hDoc.write("<td align=\\"left\\">");
 1609:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
 1610:     hDoc.write("<td align=\\"left\\">");
 1611:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
 1612:     hDoc.write("<\\/tr>");
 1613:   }
 1614: 
 1615:   function highlightend() { 
 1616:     var hDoc = hwdWin.document;
 1617:     hDoc.write("<\\/table>");
 1618:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1619:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
 1620:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
 1621:     hDoc.write("<\\/form>");
 1622:     hDoc.write('$end_page_highlight_central');
 1623:     hDoc.close();
 1624:   }
 1625: 
 1626: SUBJAVASCRIPT
 1627: }
 1628: 
 1629: sub get_increment {
 1630:     my $increment = $env{'form.increment'};
 1631:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1632:         $increment != .1) {
 1633:         $increment = 1;
 1634:     }
 1635:     return $increment;
 1636: }
 1637: 
 1638: sub gradeBox_start {
 1639:     return (
 1640:         &Apache::loncommon::start_data_table()
 1641:        .&Apache::loncommon::start_data_table_header_row()
 1642:        .'<th>'.&mt('Part').'</th>'
 1643:        .'<th>'.&mt('Points').'</th>'
 1644:        .'<th>&nbsp;</th>'
 1645:        .'<th>'.&mt('Assign Grade').'</th>'
 1646:        .'<th>'.&mt('Weight').'</th>'
 1647:        .'<th>'.&mt('Grade Status').'</th>'
 1648:        .&Apache::loncommon::end_data_table_header_row()
 1649:     );
 1650: }
 1651: 
 1652: sub gradeBox_end {
 1653:     return (
 1654:         &Apache::loncommon::end_data_table()
 1655:     );
 1656: }
 1657: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1658: sub gradeBox {
 1659:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1660:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1661: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1662:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1663:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1664:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1665:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1666:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1667: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1668:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1669:     my $display_part= &get_display_part($partid,$symb);
 1670:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1671: 				       [$partid]);
 1672:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1673:     if ($last_resets{$partid}) {
 1674:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1675:     }
 1676:     $result.=&Apache::loncommon::start_data_table_row();
 1677:     my $ctr = 0;
 1678:     my $thisweight = 0;
 1679:     my $increment = &get_increment();
 1680: 
 1681:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1682:     while ($thisweight<=$wgt) {
 1683: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1684:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1685: 	    $thisweight.')" value="'.$thisweight.'" '.
 1686: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1687: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1688:         $thisweight += $increment;
 1689: 	$ctr++;
 1690:     }
 1691:     $radio.='</tr></table>';
 1692: 
 1693:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1694: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1695: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1696: 	$wgt.')" /></td>'."\n";
 1697:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1698: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1699: 	' </td>'."\n";
 1700:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1701: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1702:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1703: 	$line.='<option></option>'.
 1704: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1705:     } else {
 1706: 	$line.='<option selected="selected"></option>'.
 1707: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1708:     }
 1709:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1710: 
 1711: 
 1712:     $result .= 
 1713: 	    '<td>'.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 1714:     $result.=&Apache::loncommon::end_data_table_row();
 1715:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1716: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1717: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1718: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1719:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1720:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1721:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1722:         $aggtries.'" />'."\n";
 1723:     my $res_error;
 1724:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 1725:     if ($res_error) {
 1726:         return &navmap_errormsg();
 1727:     }
 1728:     return $result;
 1729: }
 1730: 
 1731: sub handback_box {
 1732:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
 1733:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
 1734:     my (@respids);
 1735:      my @part_response_id = &flatten_responseType($responseType);
 1736:     foreach my $part_response_id (@part_response_id) {
 1737:     	my ($part,$resp) = @{ $part_response_id };
 1738:         if ($part eq $partid) {
 1739:             push(@respids,$resp);
 1740:         }
 1741:     }
 1742:     my $result;
 1743:     foreach my $respid (@respids) {
 1744: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1745: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1746: 	next if (!@$files);
 1747: 	my $file_counter = 1;
 1748: 	foreach my $file (@$files) {
 1749: 	    if ($file =~ /\/portfolio\//) {
 1750:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1751:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1752:     	        $file_disp = "$name.$ext";
 1753:     	        $file = $file_path.$file_disp;
 1754:     	        $result.=&mt('Return commented version of [_1] to student.',
 1755:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1756:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1757:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
 1758:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
 1759:     	        $file_counter++;
 1760: 	    }
 1761: 	}
 1762:     }
 1763:     return $result;    
 1764: }
 1765: 
 1766: sub show_problem {
 1767:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1768:     my $rendered;
 1769:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1770:     &Apache::lonxml::remember_problem_counter();
 1771:     if ($mode eq 'both' or $mode eq 'text') {
 1772: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1773: 						       $env{'request.course.id'},
 1774: 						       undef,\%form);
 1775:     }
 1776:     if ($removeform) {
 1777: 	$rendered=~s|<form(.*?)>||g;
 1778: 	$rendered=~s|</form>||g;
 1779: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1780:     }
 1781:     my $companswer;
 1782:     if ($mode eq 'both' or $mode eq 'answer') {
 1783: 	&Apache::lonxml::restore_problem_counter();
 1784: 	$companswer=
 1785: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1786: 						    $env{'request.course.id'},
 1787: 						    %form);
 1788:     }
 1789:     if ($removeform) {
 1790: 	$companswer=~s|<form(.*?)>||g;
 1791: 	$companswer=~s|</form>||g;
 1792: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1793:     }
 1794:     $rendered=
 1795:         '<div class="LC_Box">'
 1796:        .'<h3 class="LC_hcell">'.&mt('View of the problem').'</h3>'
 1797:        .$rendered
 1798:        .'</div>';
 1799:     $companswer=
 1800:         '<div class="LC_Box">'
 1801:        .'<h3 class="LC_hcell">'.&mt('Correct answer').'</h3>'
 1802:        .$companswer
 1803:        .'</div>';
 1804:     my $result;
 1805:     if ($mode eq 'both') {
 1806:         $result=$rendered.$companswer;
 1807:     } elsif ($mode eq 'text') {
 1808:         $result=$rendered;
 1809:     } elsif ($mode eq 'answer') {
 1810:         $result=$companswer;
 1811:     }
 1812:     return $result;
 1813: }
 1814: 
 1815: sub files_exist {
 1816:     my ($r, $symb) = @_;
 1817:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1818: 
 1819:     foreach my $student (@students) {
 1820:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1821:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1822: 					      $udom,$uname);
 1823:         my ($string,$timestamp)= &get_last_submission(\%record);
 1824:         foreach my $submission (@$string) {
 1825:             my ($partid,$respid) =
 1826: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1827:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1828: 					   \%record);
 1829:             return 1 if (@$files);
 1830:         }
 1831:     }
 1832:     return 0;
 1833: }
 1834: 
 1835: sub download_all_link {
 1836:     my ($r,$symb) = @_;
 1837:     unless (&files_exist($r, $symb)) {
 1838:        $r->print(&mt('There are currently no submitted documents.'));
 1839:        return;
 1840:     }
 1841: 
 1842:     my $all_students = 
 1843: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1844: 
 1845:     my $parts =
 1846: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1847: 
 1848:     my $identifier = &Apache::loncommon::get_cgi_id();
 1849:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 1850:                              'cgi.'.$identifier.'.symb' => $symb,
 1851:                              'cgi.'.$identifier.'.parts' => $parts,});
 1852:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1853: 	      &mt('Download All Submitted Documents').'</a>');
 1854:     return;
 1855: }
 1856: 
 1857: sub submit_download_link {
 1858:     my ($request,$symb) = @_;
 1859:     if (!$symb) { return ''; }
 1860: #FIXME: Figure out which type of problem this is and provide appropriate download
 1861:     &download_all_link($request,$symb);
 1862: }
 1863: 
 1864: sub build_section_inputs {
 1865:     my $section_inputs;
 1866:     if ($env{'form.section'} eq '') {
 1867:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 1868:     } else {
 1869:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 1870:         foreach my $section (@sections) {
 1871:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 1872:         }
 1873:     }
 1874:     return $section_inputs;
 1875: }
 1876: 
 1877: # --------------------------- show submissions of a student, option to grade 
 1878: sub submission {
 1879:     my ($request,$counter,$total,$symb) = @_;
 1880:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 1881:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 1882:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 1883:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 1884: 
 1885:     my $probtitle=&Apache::lonnet::gettitle($symb); 
 1886:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 1887: 
 1888:     if (!&canview($usec)) {
 1889: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
 1890: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
 1891: 			$env{'request.course.id'}.')</span>');
 1892: 	return;
 1893:     }
 1894: 
 1895:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 1896:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 1897:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 1898:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 1899:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1900: 	'" src="'.$request->dir_config('lonIconsURL').
 1901: 	'/check.gif" height="16" border="0" />';
 1902: 
 1903:     my %old_essays;
 1904:     # header info
 1905:     if ($counter == 0) {
 1906: 	&sub_page_js($request);
 1907: 	&sub_page_kw_js($request);
 1908: 
 1909: 	# option to display problem, only once else it cause problems 
 1910:         # with the form later since the problem has a form.
 1911: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 1912: 	    my $mode;
 1913: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 1914: 		$mode='both';
 1915: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 1916: 		$mode='text';
 1917: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 1918: 		$mode='answer';
 1919: 	    }
 1920: 	    &Apache::lonxml::clear_problem_counter();
 1921: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 1922: 	}
 1923: 
 1924: 	# kwclr is the only variable that is guaranteed to be non blank 
 1925:         # if this subroutine has been called once.
 1926: 	my %keyhash = ();
 1927: #	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 1928:         if (1) {
 1929: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 1930: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 1931: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 1932: 
 1933: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 1934: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 1935: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 1936: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 1937: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 1938: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 1939: 		$keyhash{$symb.'_subject'} : $probtitle;
 1940: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 1941: 	}
 1942: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 1943: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 1944: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 1945: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 1946: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 1947: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 1948: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 1949: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 1950: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 1951: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1952: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 1953: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 1954: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 1955: 			&build_section_inputs().
 1956: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 1957: 			'<input type="hidden" name="NCT"'.
 1958: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 1959: #	if ($env{'form.handgrade'} eq 'yes') {
 1960:         if (1) {
 1961: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 1962: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 1963: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 1964: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 1965: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 1966: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 1967: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 1968: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 1969: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 1970: 	    }
 1971: 	}
 1972: 	
 1973: 	my ($cts,$prnmsg) = (1,'');
 1974: 	while ($cts <= $env{'form.savemsgN'}) {
 1975: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 1976: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 1977: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 1978: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 1979: 		'" />'."\n".
 1980: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 1981: 	    $cts++;
 1982: 	}
 1983: 	$request->print($prnmsg);
 1984: 
 1985: #	if ($env{'form.handgrade'} eq 'yes') {
 1986:         if (1) {
 1987: #
 1988: # Print out the keyword options line
 1989: #
 1990: 	    $request->print(<<KEYWORDS);
 1991: &nbsp;<b>Keyword Options:</b>&nbsp;
 1992: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
 1993: <a href="#" onmousedown="javascript:getSel(); return false"
 1994:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
 1995: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
 1996: KEYWORDS
 1997: #
 1998: # Load the other essays for similarity check
 1999: #
 2000:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2001: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2002: 	    $apath=&escape($apath);
 2003: 	    $apath=~s/\W/\_/gs;
 2004: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 2005:         }
 2006:     }
 2007: 
 2008: # This is where output for one specific student would start
 2009:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2010:     $request->print(
 2011:         "\n\n"
 2012:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2013:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2014:        ."\n"
 2015:     );
 2016: 
 2017:     # Show additional functions if allowed
 2018:     if ($perm{'vgr'}) {
 2019:         $request->print(
 2020:             &Apache::loncommon::track_student_link(
 2021:                 &mt('View recent activity'),
 2022:                 $uname,$udom,'check')
 2023:            .' '
 2024:         );
 2025:     }
 2026:     if ($perm{'opa'}) {
 2027:         $request->print(
 2028:             &Apache::loncommon::pprmlink(
 2029:                 &mt('Set/Change parameters'),
 2030:                 $uname,$udom,$symb,'check'));
 2031:     }
 2032: 
 2033:     # Show Problem
 2034:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2035: 	my $mode;
 2036: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2037: 	    $mode='both';
 2038: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2039: 	    $mode='text';
 2040: 	} elsif ($env{'form.vAns'} eq 'all') {
 2041: 	    $mode='answer';
 2042: 	}
 2043: 	&Apache::lonxml::clear_problem_counter();
 2044: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2045:     }
 2046: 
 2047:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2048:     my $res_error;
 2049:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2050:     if ($res_error) {
 2051:         $request->print(&navmap_errormsg());
 2052:         return;
 2053:     }
 2054: 
 2055:     # Display student info
 2056:     $request->print(($counter == 0 ? '' : '<br />'));
 2057: 
 2058:     my $result='<div class="LC_Box">'
 2059:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
 2060:     $result.='<input type="hidden" name="name'.$counter.
 2061:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2062: #    if ($env{'form.handgrade'} eq 'no') {
 2063:     if (1) {
 2064:         $result.='<p class="LC_info">'
 2065:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2066:                 ."</p>\n";
 2067:     }
 2068: 
 2069:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2070:     my $fullname;
 2071:     my $col_fullnames = [];
 2072: #    if ($env{'form.handgrade'} eq 'yes') {
 2073:     if (1) {
 2074: 	(my $sub_result,$fullname,$col_fullnames)=
 2075: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2076: 				 $counter);
 2077: 	$result.=$sub_result;
 2078:     }
 2079:     $request->print($result."\n");
 2080: 
 2081:     # print student answer/submission
 2082:     # Options are (1) Handgraded submission only
 2083:     #             (2) Last submission, includes submission that is not handgraded 
 2084:     #                  (for multi-response type part)
 2085:     #             (3) Last submission plus the parts info
 2086:     #             (4) The whole record for this student
 2087:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
 2088: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2089: 	
 2090: 	my $lastsubonly;
 2091: 
 2092:         if ($$timestamp eq '') {
 2093:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2094:         } else {
 2095:             $lastsubonly =
 2096:                 '<div class="LC_grade_submissions_body">'
 2097:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
 2098: 
 2099: 	    my %seenparts;
 2100: 	    my @part_response_id = &flatten_responseType($responseType);
 2101: 	    foreach my $part (@part_response_id) {
 2102: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2103: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2104: 
 2105: 		my ($partid,$respid) = @{ $part };
 2106: 		my $display_part=&get_display_part($partid,$symb);
 2107: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2108: 		    if (exists($seenparts{$partid})) { next; }
 2109: 		    $seenparts{$partid}=1;
 2110: 		    my $submitby='<b>Part:</b> '.$display_part.
 2111: 			' <b>Collaborative submission by:</b> '.
 2112: 			'<a href="javascript:viewSubmitter(\''.
 2113: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
 2114: 			'\');" target="_self">'.
 2115: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
 2116: 		    $request->print($submitby);
 2117: 		    next;
 2118: 		}
 2119: 		my $responsetype = $responseType->{$partid}->{$respid};
 2120: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2121:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2122:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2123:                         ' <span class="LC_internal_info">'.
 2124:                         '('.&mt('Response ID: [_1]',$respid).')'.
 2125:                         '</span>&nbsp; &nbsp;'.
 2126: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2127: 		    next;
 2128: 		}
 2129: 		foreach my $submission (@$string) {
 2130: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2131: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2132: 		    my ($ressub,$hide,$subval) = split(/:/,$submission,3);
 2133: 		    # Similarity check
 2134: 		    my $similar='';
 2135: 		    if($env{'form.checkPlag'}){
 2136: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2137: 			    &most_similar($uname,$udom,$subval,\%old_essays);
 2138: 			if ($osim) {
 2139: 			    $osim=int($osim*100.0);
 2140: 			    my %old_course_desc = 
 2141: 				&Apache::lonnet::coursedescription($ocrsid,
 2142: 								   {'one_time' => 1});
 2143: 
 2144:                             if ($hide) {
 2145:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2146:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2147:                             } else {
 2148: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
 2149: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2150: 				        $osim,
 2151: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2152: 				        $old_course_desc{'description'},
 2153: 				        $old_course_desc{'num'},
 2154: 				        $old_course_desc{'domain'}).
 2155: 				    '</span></h3><blockquote><i>'.
 2156: 				    &keywords_highlight($oessay).
 2157: 				    '</i></blockquote><hr />';
 2158:                             }
 2159: 			}
 2160: 		    }
 2161: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
 2162: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
 2163: 			($env{'form.lastSub'} eq 'hdgrade' && 
 2164: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2165: 			my $display_part=&get_display_part($partid,$symb);
 2166:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
 2167:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2168:                             ' <span class="LC_internal_info">'.
 2169:                             '('.&mt('Response ID: [_1]',$respid).')'.
 2170:                             '</span>&nbsp; &nbsp;';
 2171: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2172: 			if (@$files) {
 2173:                             if ($hide) {
 2174:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2175:                             } else {
 2176:                                 $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
 2177:                                 foreach my $file (@$files) {
 2178:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2179:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
 2180:                                 }
 2181:                             }
 2182: 			    $lastsubonly.='<br />';
 2183: 			}
 2184:                         if ($hide) {
 2185:                             $lastsubonly.='<b>'.&mt('Anonymous Survey').'</b>'; 
 2186:                         } else {
 2187: 			    $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
 2188: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
 2189: 					     $respid,\%record,$order,undef,$uname,$udom);
 2190:                         }
 2191: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2192: 			$lastsubonly.='</div>';
 2193: 		    }
 2194: 		}
 2195: 	    }
 2196: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2197: 	}
 2198: 	$request->print($lastsubonly);
 2199:    } elsif ($env{'form.lastSub'} eq 'datesub') {
 2200:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2201: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2202:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2203: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2204: 								 $env{'request.course.id'},
 2205: 								 $last,'.submission',
 2206: 								 'Apache::grades::keywords_highlight'));
 2207:     }
 2208:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2209: 	.$udom.'" />'."\n");
 2210:     # return if view submission with no grading option
 2211:     if (!&canmodify($usec)) {
 2212: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
 2213: 	return;
 2214:     } else {
 2215: 	$request->print('</div>'."\n");
 2216:     }
 2217: 
 2218:     # essay grading message center
 2219: #    if ($env{'form.handgrade'} eq 'yes') {
 2220:     if (1) {
 2221: 	my $result='<div class="LC_grade_message_center">';
 2222:     
 2223: 	$result.='<div class="LC_grade_message_center_header">'.
 2224: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2225: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2226: 	my $msgfor = $givenn.' '.$lastname;
 2227: 	if (scalar(@$col_fullnames) > 0) {
 2228: 	    my $lastone = pop(@$col_fullnames);
 2229: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2230: 	}
 2231: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2232: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2233: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2234: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2235: 	    ',\''.$msgfor.'\');" target="_self">'.
 2236: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
 2237: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2238: 	    '<img src="'.$request->dir_config('lonIconsURL').
 2239: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2240: 	    '<br />&nbsp;('.
 2241: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2242: 	$result.='</div></div>';
 2243: 	$request->print($result);
 2244:     }
 2245: 
 2246:     my %seen = ();
 2247:     my @partlist;
 2248:     my @gradePartRespid;
 2249:     my @part_response_id = &flatten_responseType($responseType);
 2250:     $request->print(
 2251:         '<div class="LC_Box">'
 2252:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2253:     );
 2254:     $request->print(&gradeBox_start());
 2255:     foreach my $part_response_id (@part_response_id) {
 2256:     	my ($partid,$respid) = @{ $part_response_id };
 2257: 	my $part_resp = join('_',@{ $part_response_id });
 2258: 	next if ($seen{$partid} > 0);
 2259: 	$seen{$partid}++;
 2260: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2261: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2262: 	push(@partlist,$partid);
 2263: 	push(@gradePartRespid,$partid.'.'.$respid);
 2264: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2265:     }
 2266:     $request->print(&gradeBox_end()); # </div>
 2267:     $request->print('</div>');
 2268: 
 2269:     $request->print('<div class="LC_grade_info_links">');
 2270:     $request->print('</div>');
 2271: 
 2272:     $result='<input type="hidden" name="partlist'.$counter.
 2273: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2274:     $result.='<input type="hidden" name="gradePartRespid'.
 2275: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2276:     my $ctr = 0;
 2277:     while ($ctr < scalar(@partlist)) {
 2278: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2279: 	    $partlist[$ctr].'" />'."\n";
 2280: 	$ctr++;
 2281:     }
 2282:     $request->print($result.''."\n");
 2283: 
 2284: # Done with printing info for one student
 2285: 
 2286:     $request->print('</div>');#LC_grade_show_user
 2287: 
 2288: 
 2289:     # print end of form
 2290:     if ($counter == $total) {
 2291:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2292: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2293: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2294: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2295: 	my $ntstu ='<select name="NTSTU">'.
 2296: 	    '<option>1</option><option>2</option>'.
 2297: 	    '<option>3</option><option>5</option>'.
 2298: 	    '<option>7</option><option>10</option></select>'."\n";
 2299: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2300: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2301:         $endform.=&mt('[_1]student(s)',$ntstu);
 2302: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2303: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2304: 	    '<input type="button" value="'.&mt('Next').'" '.
 2305: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2306:         $endform.='<span class="LC_warning">'.
 2307:                   &mt('(Next and Previous (student) do not save the scores.)').
 2308:                   '</span>'."\n" ;
 2309:         $endform.="<input type='hidden' value='".&get_increment().
 2310:             "' name='increment' />";
 2311: 	$endform.='</td></tr></table></form>';
 2312: 	$request->print($endform);
 2313:     }
 2314:     return '';
 2315: }
 2316: 
 2317: sub check_collaborators {
 2318:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2319:     my ($result,@col_fullnames);
 2320:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2321:     foreach my $part (keys(%$handgrade)) {
 2322: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2323: 					'.maxcollaborators',
 2324: 					$symb,$udom,$uname);
 2325: 	next if ($ncol <= 0);
 2326: 	$part =~ s/\_/\./g;
 2327: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2328: 	my (@good_collaborators, @bad_collaborators);
 2329: 	foreach my $possible_collaborator
 2330: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2331: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2332: 	    next if ($possible_collaborator eq '');
 2333: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
 2334: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2335: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2336: 	    # Doing this grep allows 'fuzzy' specification
 2337: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2338: 			       keys(%$classlist));
 2339: 	    if (! scalar(@matches)) {
 2340: 		push(@bad_collaborators, $possible_collaborator);
 2341: 	    } else {
 2342: 		push(@good_collaborators, @matches);
 2343: 	    }
 2344: 	}
 2345: 	if (scalar(@good_collaborators) != 0) {
 2346: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
 2347: 	    foreach my $name (@good_collaborators) {
 2348: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2349: 		push(@col_fullnames, $givenn.' '.$lastname);
 2350: 		$result.='<li>'.$fullname->{$name}.'</li>';
 2351: 	    }
 2352: 	    $result.='</ol><br />'."\n";
 2353: 	    my ($part)=split(/\./,$part);
 2354: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2355: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2356: 		"\n";
 2357: 	}
 2358: 	if (scalar(@bad_collaborators) > 0) {
 2359: 	    $result.='<div class="LC_warning">';
 2360: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2361: 	    $result .= '</div>';
 2362: 	}         
 2363: 	if (scalar(@bad_collaborators > $ncol)) {
 2364: 	    $result .= '<div class="LC_warning">';
 2365: 	    $result .= &mt('This student has submitted too many '.
 2366: 		'collaborators.  Maximum is [_1].',$ncol);
 2367: 	    $result .= '</div>';
 2368: 	}
 2369:     }
 2370:     return ($result,$fullname,\@col_fullnames);
 2371: }
 2372: 
 2373: #--- Retrieve the last submission for all the parts
 2374: sub get_last_submission {
 2375:     my ($returnhash)=@_;
 2376:     my (@string,$timestamp,%lasthidden);
 2377:     if ($$returnhash{'version'}) {
 2378: 	my %lasthash=();
 2379: 	my ($version);
 2380: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2381: 	    foreach my $key (sort(split(/\:/,
 2382: 					$$returnhash{$version.':keys'}))) {
 2383: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2384: 		$timestamp = 
 2385: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2386: 	    }
 2387: 	}
 2388:         my %typeparts;
 2389:         my $showsurv = 
 2390:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2391:         foreach my $key (sort(keys(%lasthash))) {
 2392:             if ($key =~ /\.type$/) {
 2393:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2394:                     ($lasthash{$key} eq 'anonsurveycred')) {
 2395:                     my ($ign,@parts) = split(/\./,$key);
 2396:                     pop(@parts);
 2397:                     unless ($showsurv) {
 2398:                         my $id = join(',',@parts);
 2399:                         $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2400:                     }
 2401:                     delete($lasthash{$key});
 2402:                 }
 2403:             }
 2404:         }
 2405:         my @hidden = keys(%typeparts);
 2406: 	foreach my $key (keys(%lasthash)) {
 2407: 	    next if ($key !~ /\.submission$/);
 2408:             my $hide;
 2409:             if (@hidden) {
 2410:                 foreach my $id (@hidden) {
 2411:                     if ($key =~ /^\Q$id\E/) {
 2412:                         $hide = 1;
 2413:                         last;
 2414:                     }
 2415:                 }
 2416:             }
 2417: 	    my ($partid,$foo) = split(/submission$/,$key);
 2418: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 2419: 		'<span class="LC_warning">Draft Copy</span> ' : '';
 2420: 	    push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
 2421: 	}
 2422:     }
 2423:     if (!@string) {
 2424: 	$string[0] =
 2425: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2426:     }
 2427:     return (\@string,\$timestamp);
 2428: }
 2429: 
 2430: #--- High light keywords, with style choosen by user.
 2431: sub keywords_highlight {
 2432:     my $string    = shift;
 2433:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2434:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2435:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2436:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2437:     foreach my $keyword (@keylist) {
 2438: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2439:     }
 2440:     return $string;
 2441: }
 2442: 
 2443: #--- Called from submission routine
 2444: sub processHandGrade {
 2445:     my ($request,$symb) = @_;
 2446:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2447:     my $button = $env{'form.gradeOpt'};
 2448:     my $ngrade = $env{'form.NCT'};
 2449:     my $ntstu  = $env{'form.NTSTU'};
 2450:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2451:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2452: 
 2453:     if ($button eq 'Save & Next') {
 2454: 	my $ctr = 0;
 2455: 	while ($ctr < $ngrade) {
 2456: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2457: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2458: 	    if ($errorflag eq 'no_score') {
 2459: 		$ctr++;
 2460: 		next;
 2461: 	    }
 2462: 	    if ($errorflag eq 'not_allowed') {
 2463: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
 2464: 		$ctr++;
 2465: 		next;
 2466: 	    }
 2467: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2468: 	    my ($subject,$message,$msgstatus) = ('','','');
 2469: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2470:             my ($feedurl,$showsymb) =
 2471: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2472: 	    my $messagetail;
 2473: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2474: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2475: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2476: 		$subject.=' ['.$restitle.']';
 2477: 		my (@msgnum) = split(/,/,$includemsg);
 2478: 		foreach (@msgnum) {
 2479: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2480: 		}
 2481: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2482: 		if ($env{'form.withgrades'.$ctr}) {
 2483: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2484: 		    $messagetail = " for <a href=\"".
 2485: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
 2486: 		}
 2487: 		$msgstatus = 
 2488:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2489: 						     $message.$messagetail,
 2490:                                                      undef,$feedurl,undef,
 2491:                                                      undef,undef,$showsymb,
 2492:                                                      $restitle);
 2493: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 2494: 				$msgstatus);
 2495: 	    }
 2496: 	    if ($env{'form.collaborator'.$ctr}) {
 2497: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2498: 		foreach my $collabstr (@collabstrs) {
 2499: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2500: 		    foreach my $collaborator (@collaborators) {
 2501: 			my ($errorflag,$pts,$wgt) = 
 2502: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2503: 					   $env{'form.unamedom'.$ctr},$part);
 2504: 			if ($errorflag eq 'not_allowed') {
 2505: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2506: 			    next;
 2507: 			} elsif ($message ne '') {
 2508: 			    my ($baseurl,$showsymb) = 
 2509: 				&get_feedurl_and_symb($symb,$collaborator,
 2510: 						      $udom);
 2511: 			    if ($env{'form.withgrades'.$ctr}) {
 2512: 				$messagetail = " for <a href=\"".
 2513:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
 2514: 			    }
 2515: 			    $msgstatus = 
 2516: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2517: 			}
 2518: 		    }
 2519: 		}
 2520: 	    }
 2521: 	    $ctr++;
 2522: 	}
 2523:     }
 2524: 
 2525: #    if ($env{'form.handgrade'} eq 'yes') {
 2526:     if (1) {
 2527: 	# Keywords sorted in alphabatical order
 2528: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2529: 	my %keyhash = ();
 2530: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2531: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2532: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2533: 	$env{'form.keywords'} = join(' ',@keywords);
 2534: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2535: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2536: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2537: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2538: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2539: 
 2540: 	# message center - Order of message gets changed. Blank line is eliminated.
 2541: 	# New messages are saved in env for the next student.
 2542: 	# All messages are saved in nohist_handgrade.db
 2543: 	my ($ctr,$idx) = (1,1);
 2544: 	while ($ctr <= $env{'form.savemsgN'}) {
 2545: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2546: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2547: 		$idx++;
 2548: 	    }
 2549: 	    $ctr++;
 2550: 	}
 2551: 	$ctr = 0;
 2552: 	while ($ctr < $ngrade) {
 2553: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2554: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2555: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2556: 		$idx++;
 2557: 	    }
 2558: 	    $ctr++;
 2559: 	}
 2560: 	$env{'form.savemsgN'} = --$idx;
 2561: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2562: 	my $putresult = &Apache::lonnet::put
 2563: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2564:     }
 2565:     # Called by Save & Refresh from Highlight Attribute Window
 2566:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2567:     if ($env{'form.refresh'} eq 'on') {
 2568: 	my ($ctr,$total) = (0,0);
 2569: 	while ($ctr < $ngrade) {
 2570: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2571: 	    $ctr++;
 2572: 	}
 2573: 	$env{'form.NTSTU'}=$ngrade;
 2574: 	$ctr = 0;
 2575: 	while ($ctr < $total) {
 2576: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2577: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2578: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2579: 	    &submission($request,$ctr,$total-1,$symb);
 2580: 	    $ctr++;
 2581: 	}
 2582: 	return '';
 2583:     }
 2584: 
 2585:     # Get the next/previous one or group of students
 2586:     my $firststu = $env{'form.unamedom0'};
 2587:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2588:     my $ctr = 2;
 2589:     while ($laststu eq '') {
 2590: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2591: 	$ctr++;
 2592: 	$laststu = $firststu if ($ctr > $ngrade);
 2593:     }
 2594: 
 2595:     my (@parsedlist,@nextlist);
 2596:     my ($nextflg) = 0;
 2597:     foreach my $item (sort 
 2598: 	     {
 2599: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2600: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2601: 		 }
 2602: 		 return $a cmp $b;
 2603: 	     } (keys(%$fullname))) {
 2604: # FIXME: this is fishy, looks like the button label
 2605: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2606: 	    push(@parsedlist,$item);
 2607: 	}
 2608: 	$nextflg = 1 if ($item eq $laststu);
 2609: 	if ($button eq 'Previous') {
 2610: 	    last if ($item eq $firststu);
 2611: 	    push(@parsedlist,$item);
 2612: 	}
 2613:     }
 2614:     $ctr = 0;
 2615: # FIXME: this is fishy, looks like the button label
 2616:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2617:     my $res_error;
 2618:     my ($partlist) = &response_type($symb,\$res_error);
 2619:     if ($res_error) {
 2620:         $request->print(&navmap_errormsg());
 2621:         return;
 2622:     }
 2623:     foreach my $student (@parsedlist) {
 2624: 	my $submitonly=$env{'form.submitonly'};
 2625: 	my ($uname,$udom) = split(/:/,$student);
 2626: 	
 2627: 	if ($submitonly eq 'queued') {
 2628: 	    my %queue_status = 
 2629: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2630: 							$udom,$uname);
 2631: 	    next if (!defined($queue_status{'gradingqueue'}));
 2632: 	}
 2633: 
 2634: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2635: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2636: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2637: 	    my $submitted = 0;
 2638: 	    my $ungraded = 0;
 2639: 	    my $incorrect = 0;
 2640: 	    foreach my $item (keys(%status)) {
 2641: 		$submitted = 1 if ($status{$item} ne 'nothing');
 2642: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 2643: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 2644: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 2645: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2646: 		    $submitted = 0;
 2647: 		}
 2648: 	    }
 2649: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2650: 				     $submitonly eq 'incorrect' ||
 2651: 				     $submitonly eq 'graded'));
 2652: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2653: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2654: 	}
 2655: 	push(@nextlist,$student) if ($ctr < $ntstu);
 2656: 	last if ($ctr == $ntstu);
 2657: 	$ctr++;
 2658:     }
 2659: 
 2660:     $ctr = 0;
 2661:     my $total = scalar(@nextlist)-1;
 2662: 
 2663:     foreach (sort(@nextlist)) {
 2664: 	my ($uname,$udom,$submitter) = split(/:/);
 2665: 	$env{'form.student'}  = $uname;
 2666: 	$env{'form.userdom'}  = $udom;
 2667: 	$env{'form.fullname'} = $$fullname{$_};
 2668: 	&submission($request,$ctr,$total,$symb);
 2669: 	$ctr++;
 2670:     }
 2671:     if ($total < 0) {
 2672: 	my $the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
 2673: 	$request->print($the_end);
 2674:     }
 2675:     return '';
 2676: }
 2677: 
 2678: #---- Save the score and award for each student, if changed
 2679: sub saveHandGrade {
 2680:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 2681:     my @version_parts;
 2682:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 2683: 					   $env{'request.course.id'});
 2684:     if (!&canmodify($usec)) { return('not_allowed'); }
 2685:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 2686:     my @parts_graded;
 2687:     my %newrecord  = ();
 2688:     my ($pts,$wgt) = ('','');
 2689:     my %aggregate = ();
 2690:     my $aggregateflag = 0;
 2691:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 2692:     foreach my $new_part (@parts) {
 2693: 	#collaborator ($submi may vary for different parts
 2694: 	if ($submitter && $new_part ne $part) { next; }
 2695: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 2696: 	if ($dropMenu eq 'excused') {
 2697: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 2698: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 2699: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 2700: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 2701: 		}
 2702: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 2703: 	    }
 2704: 	} elsif ($dropMenu eq 'reset status'
 2705: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 2706: 	    foreach my $key (keys(%record)) {
 2707: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 2708: 	    }
 2709: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2710: 		"$env{'user.name'}:$env{'user.domain'}";
 2711:             my $totaltries = $record{'resource.'.$part.'.tries'};
 2712: 
 2713:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2714: 					       [$new_part]);
 2715:             my $aggtries =$totaltries;
 2716:             if ($last_resets{$new_part}) {
 2717:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 2718: 					   $new_part);
 2719:             }
 2720: 
 2721:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 2722:             if ($aggtries > 0) {
 2723:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 2724:                 $aggregateflag = 1;
 2725:             }
 2726: 	} elsif ($dropMenu eq '') {
 2727: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 2728: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 2729: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 2730: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 2731: 		next;
 2732: 	    }
 2733: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 2734: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 2735: 	    my $partial= $pts/$wgt;
 2736: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 2737: 		#do not update score for part if not changed.
 2738:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 2739: 		next;
 2740: 	    } else {
 2741: 	        push(@parts_graded,$new_part);
 2742: 	    }
 2743: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 2744: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 2745: 	    }
 2746: 	    my $reckey = 'resource.'.$new_part.'.solved';
 2747: 	    if ($partial == 0) {
 2748: 		if ($record{$reckey} ne 'incorrect_by_override') {
 2749: 		    $newrecord{$reckey} = 'incorrect_by_override';
 2750: 		}
 2751: 	    } else {
 2752: 		if ($record{$reckey} ne 'correct_by_override') {
 2753: 		    $newrecord{$reckey} = 'correct_by_override';
 2754: 		}
 2755: 	    }	    
 2756: 	    if ($submitter && 
 2757: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 2758: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 2759: 	    }
 2760: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2761: 		"$env{'user.name'}:$env{'user.domain'}";
 2762: 	}
 2763: 	# unless problem has been graded, set flag to version the submitted files
 2764: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 2765: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 2766: 	        $dropMenu eq 'reset status')
 2767: 	   {
 2768: 	    push(@version_parts,$new_part);
 2769: 	}
 2770:     }
 2771:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2772:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2773: 
 2774:     if (%newrecord) {
 2775:         if (@version_parts) {
 2776:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 2777:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 2778: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 2779: 	    foreach my $new_part (@version_parts) {
 2780: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 2781: 				$new_part,\%newrecord);
 2782: 	    }
 2783:         }
 2784: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 2785: 				$env{'request.course.id'},$domain,$stuname);
 2786: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 2787: 				     $cdom,$cnum,$domain,$stuname);
 2788:     }
 2789:     if ($aggregateflag) {
 2790:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 2791: 			      $cdom,$cnum);
 2792:     }
 2793:     return ('',$pts,$wgt);
 2794: }
 2795: 
 2796: sub check_and_remove_from_queue {
 2797:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 2798:     my @ungraded_parts;
 2799:     foreach my $part (@{$parts}) {
 2800: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 2801: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 2802: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 2803: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 2804: 		) {
 2805: 	    push(@ungraded_parts, $part);
 2806: 	}
 2807:     }
 2808:     if ( !@ungraded_parts ) {
 2809: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 2810: 					       $cnum,$domain,$stuname);
 2811:     }
 2812: }
 2813: 
 2814: sub handback_files {
 2815:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 2816:     my $portfolio_root = '/userfiles/portfolio';
 2817:     my $res_error;
 2818:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2819:     if ($res_error) {
 2820:         $request->print('<br />'.&navmap_errormsg().'<br />');
 2821:         return;
 2822:     }
 2823:     my @part_response_id = &flatten_responseType($responseType);
 2824:     foreach my $part_response_id (@part_response_id) {
 2825:     	my ($part_id,$resp_id) = @{ $part_response_id };
 2826: 	my $part_resp = join('_',@{ $part_response_id });
 2827:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
 2828:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 2829:                 my $file_counter = 1;
 2830: 		my $file_msg;
 2831:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
 2832:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
 2833:                     my ($directory,$answer_file) = 
 2834:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
 2835:                     my ($answer_name,$answer_ver,$answer_ext) =
 2836: 		        &file_name_version_ext($answer_file);
 2837: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 2838:                     my $getpropath = 1;
 2839: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
 2840: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2841:                     # fix file name
 2842:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 2843:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 2844:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
 2845:             	                                $save_file_name);
 2846:                     if ($result !~ m|^/uploaded/|) {
 2847:                         $request->print('<br /><span class="LC_error">'.
 2848:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 2849:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
 2850:                                         '</span>');
 2851:                     } else {
 2852:                         # mark the file as read only
 2853:                         my @files = ($save_file_name);
 2854:                         my @what = ($symb,$env{'request.course.id'},'handback');
 2855:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
 2856: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 2857: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 2858: 			}
 2859:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 2860: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
 2861: 
 2862:                     }
 2863:                     $request->print("<br />".$fname." will be the uploaded file name");
 2864:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
 2865:                     $file_counter++;
 2866:                 }
 2867: 		my $subject = "File Handed Back by Instructor ";
 2868: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
 2869: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
 2870: 		$message .= ' The returned file(s) are named: '. $file_msg;
 2871: 		$message .= " and can be found in your portfolio space.";
 2872: 		my ($feedurl,$showsymb) = 
 2873: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
 2874:                 my $restitle = &Apache::lonnet::gettitle($symb);
 2875: 		my $msgstatus = 
 2876:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
 2877: 			 ' (File Returned) ['.$restitle.']',$message,undef,
 2878:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
 2879:             }
 2880:         }
 2881:     return;
 2882: }
 2883: 
 2884: sub get_feedurl_and_symb {
 2885:     my ($symb,$uname,$udom) = @_;
 2886:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2887:     $url = &Apache::lonnet::clutter($url);
 2888:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 2889: 					$symb,$udom,$uname);
 2890:     if ($encrypturl =~ /^yes$/i) {
 2891: 	&Apache::lonenc::encrypted(\$url,1);
 2892: 	&Apache::lonenc::encrypted(\$symb,1);
 2893:     }
 2894:     return ($url,$symb);
 2895: }
 2896: 
 2897: sub get_submitted_files {
 2898:     my ($udom,$uname,$partid,$respid,$record) = @_;
 2899:     my @files;
 2900:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 2901:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 2902:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 2903:     	    push(@files,$file_url.$file);
 2904:         }
 2905:     }
 2906:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 2907:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 2908:     }
 2909:     return (\@files);
 2910: }
 2911: 
 2912: # ----------- Provides number of tries since last reset.
 2913: sub get_num_tries {
 2914:     my ($record,$last_reset,$part) = @_;
 2915:     my $timestamp = '';
 2916:     my $num_tries = 0;
 2917:     if ($$record{'version'}) {
 2918:         for (my $version=$$record{'version'};$version>=1;$version--) {
 2919:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 2920:                 $timestamp = $$record{$version.':timestamp'};
 2921:                 if ($timestamp > $last_reset) {
 2922:                     $num_tries ++;
 2923:                 } else {
 2924:                     last;
 2925:                 }
 2926:             }
 2927:         }
 2928:     }
 2929:     return $num_tries;
 2930: }
 2931: 
 2932: # ----------- Determine decrements required in aggregate totals 
 2933: sub decrement_aggs {
 2934:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 2935:     my %decrement = (
 2936:                         attempts => 0,
 2937:                         users => 0,
 2938:                         correct => 0
 2939:                     );
 2940:     $decrement{'attempts'} = $aggtries;
 2941:     if ($solvedstatus =~ /^correct/) {
 2942:         $decrement{'correct'} = 1;
 2943:     }
 2944:     if ($aggtries == $totaltries) {
 2945:         $decrement{'users'} = 1;
 2946:     }
 2947:     foreach my $type (keys(%decrement)) {
 2948:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 2949:     }
 2950:     return;
 2951: }
 2952: 
 2953: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 2954: sub get_last_resets {
 2955:     my ($symb,$courseid,$partids) =@_;
 2956:     my %last_resets;
 2957:     my $cdom = $env{'course.'.$courseid.'.domain'};
 2958:     my $cname = $env{'course.'.$courseid.'.num'};
 2959:     my @keys;
 2960:     foreach my $part (@{$partids}) {
 2961: 	push(@keys,"$symb\0$part\0resettime");
 2962:     }
 2963:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 2964: 				     $cdom,$cname);
 2965:     foreach my $part (@{$partids}) {
 2966: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 2967:     }
 2968:     return %last_resets;
 2969: }
 2970: 
 2971: # ----------- Handles creating versions for portfolio files as answers
 2972: sub version_portfiles {
 2973:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 2974:     my $version_parts = join('|',@$v_flag);
 2975:     my @returned_keys;
 2976:     my $parts = join('|', @$parts_graded);
 2977:     my $portfolio_root = '/userfiles/portfolio';
 2978:     foreach my $key (keys(%$record)) {
 2979:         my $new_portfiles;
 2980:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 2981:             my @versioned_portfiles;
 2982:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 2983:             foreach my $file (@portfiles) {
 2984:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 2985:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 2986: 		my ($answer_name,$answer_ver,$answer_ext) =
 2987: 		    &file_name_version_ext($answer_file);
 2988:                 my $getpropath = 1;    
 2989:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
 2990:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2991:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 2992:                 if ($new_answer ne 'problem getting file') {
 2993:                     push(@versioned_portfiles, $directory.$new_answer);
 2994:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 2995:                         [$directory.$new_answer],
 2996:                         [$symb,$env{'request.course.id'},'graded']);
 2997:                 }
 2998:             }
 2999:             $$record{$key} = join(',',@versioned_portfiles);
 3000:             push(@returned_keys,$key);
 3001:         }
 3002:     } 
 3003:     return (@returned_keys);   
 3004: }
 3005: 
 3006: sub get_next_version {
 3007:     my ($answer_name, $answer_ext, $dir_list) = @_;
 3008:     my $version;
 3009:     foreach my $row (@$dir_list) {
 3010:         my ($file) = split(/\&/,$row,2);
 3011:         my ($file_name,$file_version,$file_ext) =
 3012: 	    &file_name_version_ext($file);
 3013:         if (($file_name eq $answer_name) && 
 3014: 	    ($file_ext eq $answer_ext)) {
 3015:                 # gets here if filename and extension match, regardless of version
 3016:                 if ($file_version ne '') {
 3017:                 # a versioned file is found  so save it for later
 3018:                 if ($file_version > $version) {
 3019: 		    $version = $file_version;
 3020: 	        }
 3021:             }
 3022:         }
 3023:     } 
 3024:     $version ++;
 3025:     return($version);
 3026: }
 3027: 
 3028: sub version_selected_portfile {
 3029:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3030:     my ($answer_name,$answer_ver,$answer_ext) =
 3031:         &file_name_version_ext($file_name);
 3032:     my $new_answer;
 3033:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3034:     if($env{'form.copy'} eq '-1') {
 3035:         $new_answer = 'problem getting file';
 3036:     } else {
 3037:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3038:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3039:                             $stu_name,$domain,'copy',
 3040: 		        '/portfolio'.$directory.$new_answer);
 3041:     }    
 3042:     return ($new_answer);
 3043: }
 3044: 
 3045: sub file_name_version_ext {
 3046:     my ($file)=@_;
 3047:     my @file_parts = split(/\./, $file);
 3048:     my ($name,$version,$ext);
 3049:     if (@file_parts > 1) {
 3050: 	$ext=pop(@file_parts);
 3051: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3052: 	    $version=pop(@file_parts);
 3053: 	}
 3054: 	$name=join('.',@file_parts);
 3055:     } else {
 3056: 	$name=join('.',@file_parts);
 3057:     }
 3058:     return($name,$version,$ext);
 3059: }
 3060: 
 3061: #--------------------------------------------------------------------------------------
 3062: #
 3063: #-------------------------- Next few routines handles grading by section or whole class
 3064: #
 3065: #--- Javascript to handle grading by section or whole class
 3066: sub viewgrades_js {
 3067:     my ($request) = shift;
 3068: 
 3069:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3070:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
 3071:    function writePoint(partid,weight,point) {
 3072: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3073: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3074: 	if (point == "textval") {
 3075: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3076: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3077: 		alert("$alertmsg"+parseFloat(point));
 3078: 		var resetbox = false;
 3079: 		for (var i=0; i<radioButton.length; i++) {
 3080: 		    if (radioButton[i].checked) {
 3081: 			textbox.value = i;
 3082: 			resetbox = true;
 3083: 		    }
 3084: 		}
 3085: 		if (!resetbox) {
 3086: 		    textbox.value = "";
 3087: 		}
 3088: 		return;
 3089: 	    }
 3090: 	    if (parseFloat(point) > parseFloat(weight)) {
 3091: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3092: 				   ") greater than the weight for the part. Accept?");
 3093: 		if (resp == false) {
 3094: 		    textbox.value = "";
 3095: 		    return;
 3096: 		}
 3097: 	    }
 3098: 	    for (var i=0; i<radioButton.length; i++) {
 3099: 		radioButton[i].checked=false;
 3100: 		if (parseFloat(point) == i) {
 3101: 		    radioButton[i].checked=true;
 3102: 		}
 3103: 	    }
 3104: 
 3105: 	} else {
 3106: 	    textbox.value = parseFloat(point);
 3107: 	}
 3108: 	for (i=0;i<document.classgrade.total.value;i++) {
 3109: 	    var user = document.classgrade["ctr"+i].value;
 3110: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3111: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3112: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3113: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3114: 	    if (saveval != "correct") {
 3115: 		scorename.value = point;
 3116: 		if (selname[0].selected != true) {
 3117: 		    selname[0].selected = true;
 3118: 		}
 3119: 	    }
 3120: 	}
 3121: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3122:     }
 3123: 
 3124:     function writeRadText(partid,weight) {
 3125: 	var selval   = document.classgrade["SELVAL_"+partid];
 3126: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3127:         var override = document.classgrade["FORCE_"+partid].checked;
 3128: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3129: 	if (selval[1].selected || selval[2].selected) {
 3130: 	    for (var i=0; i<radioButton.length; i++) {
 3131: 		radioButton[i].checked=false;
 3132: 
 3133: 	    }
 3134: 	    textbox.value = "";
 3135: 
 3136: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3137: 		var user = document.classgrade["ctr"+i].value;
 3138: 		user = user.replace(new RegExp(':', 'g'),"_");
 3139: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3140: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3141: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3142: 		if ((saveval != "correct") || override) {
 3143: 		    scorename.value = "";
 3144: 		    if (selval[1].selected) {
 3145: 			selname[1].selected = true;
 3146: 		    } else {
 3147: 			selname[2].selected = true;
 3148: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3149: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3150: 		    }
 3151: 		}
 3152: 	    }
 3153: 	} else {
 3154: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3155: 		var user = document.classgrade["ctr"+i].value;
 3156: 		user = user.replace(new RegExp(':', 'g'),"_");
 3157: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3158: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3159: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3160: 		if ((saveval != "correct") || override) {
 3161: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3162: 		    selname[0].selected = true;
 3163: 		}
 3164: 	    }
 3165: 	}	    
 3166:     }
 3167: 
 3168:     function changeSelect(partid,user) {
 3169: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3170: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3171: 	var point  = textbox.value;
 3172: 	var weight = document.classgrade["weight_"+partid].value;
 3173: 
 3174: 	if (isNaN(point) || parseFloat(point) < 0) {
 3175: 	    alert("$alertmsg"+parseFloat(point));
 3176: 	    textbox.value = "";
 3177: 	    return;
 3178: 	}
 3179: 	if (parseFloat(point) > parseFloat(weight)) {
 3180: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3181: 			       ") greater than the weight of the part. Accept?");
 3182: 	    if (resp == false) {
 3183: 		textbox.value = "";
 3184: 		return;
 3185: 	    }
 3186: 	}
 3187: 	selval[0].selected = true;
 3188:     }
 3189: 
 3190:     function changeOneScore(partid,user) {
 3191: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3192: 	if (selval[1].selected || selval[2].selected) {
 3193: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3194: 	    if (selval[2].selected) {
 3195: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3196: 	    }
 3197:         }
 3198:     }
 3199: 
 3200:     function resetEntry(numpart) {
 3201: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3202: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3203: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3204: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3205: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3206: 	    for (var i=0; i<radioButton.length; i++) {
 3207: 		radioButton[i].checked=false;
 3208: 
 3209: 	    }
 3210: 	    textbox.value = "";
 3211: 	    selval[0].selected = true;
 3212: 
 3213: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3214: 		var user = document.classgrade["ctr"+i].value;
 3215: 		user = user.replace(new RegExp(':', 'g'),"_");
 3216: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3217: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3218: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3219: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3220: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3221: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3222: 		if (saveselval == "excused") {
 3223: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3224: 		} else {
 3225: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3226: 		}
 3227: 	    }
 3228: 	}
 3229:     }
 3230: 
 3231: VIEWJAVASCRIPT
 3232: }
 3233: 
 3234: #--- show scores for a section or whole class w/ option to change/update a score
 3235: sub viewgrades {
 3236:     my ($request,$symb) = @_;
 3237:     &viewgrades_js($request);
 3238: 
 3239:     #need to make sure we have the correct data for later EXT calls, 
 3240:     #thus invalidate the cache
 3241:     &Apache::lonnet::devalidatecourseresdata(
 3242:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3243:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3244:     &Apache::lonnet::clear_EXT_cache_status();
 3245: 
 3246:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3247: 
 3248:     #view individual student submission form - called using Javascript viewOneStudent
 3249:     $result.=&jscriptNform($symb);
 3250: 
 3251:     #beginning of class grading form
 3252:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3253:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3254: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3255: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3256: 	&build_section_inputs().
 3257: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3258: 
 3259:     my ($common_header,$specific_header);
 3260:     if ($env{'form.section'} eq 'all') {
 3261: 	$common_header = &mt('Assign Common Grade to Class');
 3262:         $specific_header = &mt('Assign Grade to Specific Students in Class');
 3263:     } elsif ($env{'form.section'} eq 'none') {
 3264:         $common_header = &mt('Assign Common Grade to Students in no Section');
 3265: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
 3266:     } else {
 3267:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3268:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3269: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3270:     }
 3271:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
 3272:     #radio buttons/text box for assigning points for a section or class.
 3273:     #handles different parts of a problem
 3274:     my $res_error;
 3275:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3276:     if ($res_error) {
 3277:         return &navmap_errormsg();
 3278:     }
 3279:     my %weight = ();
 3280:     my $ctsparts = 0;
 3281:     my %seen = ();
 3282:     my @part_response_id = &flatten_responseType($responseType);
 3283:     foreach my $part_response_id (@part_response_id) {
 3284:     	my ($partid,$respid) = @{ $part_response_id };
 3285: 	my $part_resp = join('_',@{ $part_response_id });
 3286: 	next if $seen{$partid};
 3287: 	$seen{$partid}++;
 3288: 	my $handgrade=$$handgrade{$part_resp};
 3289: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3290: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3291: 
 3292: 	my $display_part=&get_display_part($partid,$symb);
 3293: 	my $radio.='<table border="0"><tr>';  
 3294: 	my $ctr = 0;
 3295: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3296: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3297: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3298: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3299: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3300: 	    $ctr++;
 3301: 	}
 3302: 	$radio.='</tr></table>';
 3303: 	my $line = '<input type="text" name="TEXTVAL_'.
 3304: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 3305: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3306: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3307: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
 3308: 	    'onchange="javascript:writeRadText(\''.$partid.'\','.
 3309: 		$weight{$partid}.')"> '.
 3310: 	    '<option selected="selected"> </option>'.
 3311: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3312: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3313: 	    '</select></td>'.
 3314:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3315: 	$line.='<input type="hidden" name="partid_'.
 3316: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3317: 	$line.='<input type="hidden" name="weight_'.
 3318: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3319: 
 3320: 	$result.=
 3321: 	    &Apache::loncommon::start_data_table_row()."\n".
 3322: 	    '<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>'.
 3323: 	    &Apache::loncommon::end_data_table_row()."\n";
 3324: 	$ctsparts++;
 3325:     }
 3326:     $result.=&Apache::loncommon::end_data_table()."\n".
 3327: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3328:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3329: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 3330: 
 3331:     #table listing all the students in a section/class
 3332:     #header of table
 3333:     $result.= '<h3>'.$specific_header.'</h3>'.
 3334:               &Apache::loncommon::start_data_table().
 3335: 	      &Apache::loncommon::start_data_table_header_row().
 3336: 	      '<th>'.&mt('No.').'</th>'.
 3337: 	      '<th>'.&nameUserString('header')."</th>\n";
 3338:     my $partserror;
 3339:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3340:     if ($partserror) {
 3341:         return &navmap_errormsg();
 3342:     }
 3343:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3344:     my @partids = ();
 3345:     foreach my $part (@parts) {
 3346: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3347:         my $narrowtext = &mt('Tries');
 3348: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3349: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3350: 	my ($partid) = &split_part_type($part);
 3351:         push(@partids,$partid);
 3352: #
 3353: # FIXME: Looks like $display looks at English text
 3354: #
 3355: 	my $display_part=&get_display_part($partid,$symb);
 3356: 	if ($display =~ /^Partial Credit Factor/) {
 3357: 	    $result.='<th>'.
 3358: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
 3359: 		    $display_part,$weight{$partid}).'</th>'."\n";
 3360: 	    next;
 3361: 	    
 3362: 	} else {
 3363: 	    if ($display =~ /Problem Status/) {
 3364: 		my $grade_status_mt = &mt('Grade Status');
 3365: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3366: 	    }
 3367: 	    my $part_mt = &mt('Part:');
 3368: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3369: 	}
 3370: 
 3371: 	$result.='<th>'.$display.'</th>'."\n";
 3372:     }
 3373:     $result.=&Apache::loncommon::end_data_table_header_row();
 3374: 
 3375:     my %last_resets = 
 3376: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3377: 
 3378:     #get info for each student
 3379:     #list all the students - with points and grade status
 3380:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3381:     my $ctr = 0;
 3382:     foreach (sort 
 3383: 	     {
 3384: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3385: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3386: 		 }
 3387: 		 return $a cmp $b;
 3388: 	     } (keys(%$fullname))) {
 3389: 	$ctr++;
 3390: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3391: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3392:     }
 3393:     $result.=&Apache::loncommon::end_data_table();
 3394:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3395:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3396: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 3397:     if (scalar(%$fullname) eq 0) {
 3398: 	my $colspan=3+scalar(@parts);
 3399: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3400:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3401: 	$result='<span class="LC_warning">'.
 3402: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3403: 	        $section_display, $stu_status).
 3404: 	    '</span>';
 3405:     }
 3406:     return $result;
 3407: }
 3408: 
 3409: #--- call by previous routine to display each student
 3410: sub viewstudentgrade {
 3411:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3412:     my ($uname,$udom) = split(/:/,$student);
 3413:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3414:     my %aggregates = (); 
 3415:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3416: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3417: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3418: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3419: 	'\');" target="_self">'.$fullname.'</a> '.
 3420: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3421:     $student=~s/:/_/; # colon doen't work in javascript for names
 3422:     foreach my $apart (@$parts) {
 3423: 	my ($part,$type) = &split_part_type($apart);
 3424: 	my $score=$record{"resource.$part.$type"};
 3425:         $result.='<td align="center">';
 3426:         my ($aggtries,$totaltries);
 3427:         unless (exists($aggregates{$part})) {
 3428: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3429: 
 3430: 	    $aggtries = $totaltries;
 3431:             if ($$last_resets{$part}) {  
 3432:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3433: 					   $part);
 3434:             }
 3435:             $result.='<input type="hidden" name="'.
 3436:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3437:             $result.='<input type="hidden" name="'.
 3438:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3439:             $aggregates{$part} = 1;
 3440:         }
 3441: 	if ($type eq 'awarded') {
 3442: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3443: 	    $result.='<input type="hidden" name="'.
 3444: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3445: 	    $result.='<input type="text" name="'.
 3446: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3447:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3448: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3449: 	} elsif ($type eq 'solved') {
 3450: 	    my ($status,$foo)=split(/_/,$score,2);
 3451: 	    $status = 'nothing' if ($status eq '');
 3452: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3453: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3454: 	    $result.='&nbsp;<select name="'.
 3455: 		'GD_'.$student.'_'.$part.'_solved" '.
 3456:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3457: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3458: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3459: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3460: 	    $result.="</select>&nbsp;</td>\n";
 3461: 	} else {
 3462: 	    $result.='<input type="hidden" name="'.
 3463: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3464: 		    "\n";
 3465: 	    $result.='<input type="text" name="'.
 3466: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3467: 		'value="'.$score.'" size="4" /></td>'."\n";
 3468: 	}
 3469:     }
 3470:     $result.=&Apache::loncommon::end_data_table_row();
 3471:     return $result;
 3472: }
 3473: 
 3474: #--- change scores for all the students in a section/class
 3475: #    record does not get update if unchanged
 3476: sub editgrades {
 3477:     my ($request,$symb) = @_;
 3478: 
 3479:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3480:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3481:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3482: 
 3483:     my $result= &Apache::loncommon::start_data_table().
 3484: 	&Apache::loncommon::start_data_table_header_row().
 3485: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3486: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3487:     my %scoreptr = (
 3488: 		    'correct'  =>'correct_by_override',
 3489: 		    'incorrect'=>'incorrect_by_override',
 3490: 		    'excused'  =>'excused',
 3491: 		    'ungraded' =>'ungraded_attempted',
 3492:                     'credited' =>'credit_attempted',
 3493: 		    'nothing'  => '',
 3494: 		    );
 3495:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3496: 
 3497:     my (@partid);
 3498:     my %weight = ();
 3499:     my %columns = ();
 3500:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3501: 
 3502:     my $partserror;
 3503:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3504:     if ($partserror) {
 3505:         return &navmap_errormsg();
 3506:     }
 3507:     my $header;
 3508:     while ($ctr < $env{'form.totalparts'}) {
 3509: 	my $partid = $env{'form.partid_'.$ctr};
 3510: 	push(@partid,$partid);
 3511: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3512: 	$ctr++;
 3513:     }
 3514:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3515:     foreach my $partid (@partid) {
 3516: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3517: 	    '<th align="center">'.&mt('New Score').'</th>';
 3518: 	$columns{$partid}=2;
 3519: 	foreach my $stores (@parts) {
 3520: 	    my ($part,$type) = &split_part_type($stores);
 3521: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3522: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3523: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3524: 	    $display =~ s/\[Part: \Q$part\E\]//;
 3525:             my $narrowtext = &mt('Tries');
 3526: 	    $display =~ s/Number of Attempts/$narrowtext/;
 3527: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 3528: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 3529: 	    $columns{$partid}+=2;
 3530: 	}
 3531:     }
 3532:     foreach my $partid (@partid) {
 3533: 	my $display_part=&get_display_part($partid,$symb);
 3534: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3535: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3536: 	    '</th>';
 3537: 
 3538:     }
 3539:     $result .= &Apache::loncommon::end_data_table_header_row().
 3540: 	&Apache::loncommon::start_data_table_header_row().
 3541: 	$header.
 3542: 	&Apache::loncommon::end_data_table_header_row();
 3543:     my @noupdate;
 3544:     my ($updateCtr,$noupdateCtr) = (1,1);
 3545:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3546: 	my $line;
 3547: 	my $user = $env{'form.ctr'.$i};
 3548: 	my ($uname,$udom)=split(/:/,$user);
 3549: 	my %newrecord;
 3550: 	my $updateflag = 0;
 3551: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3552: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3553: 	if (!&canmodify($usec)) {
 3554: 	    my $numcols=scalar(@partid)*4+2;
 3555: 	    push(@noupdate,
 3556: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 3557: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 3558: 	    next;
 3559: 	}
 3560:         my %aggregate = ();
 3561:         my $aggregateflag = 0;
 3562: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3563: 	foreach (@partid) {
 3564: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3565: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3566: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3567: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3568: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3569: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3570: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3571: 	    my $score;
 3572: 	    if ($partial eq '') {
 3573: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3574: 	    } elsif ($partial > 0) {
 3575: 		$score = 'correct_by_override';
 3576: 	    } elsif ($partial == 0) {
 3577: 		$score = 'incorrect_by_override';
 3578: 	    }
 3579: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3580: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3581: 
 3582: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3583: 		"$env{'user.name'}:$env{'user.domain'}";
 3584: 	    if ($dropMenu eq 'reset status' &&
 3585: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3586: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3587: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3588: 		$newrecord{'resource.'.$_.'.award'} = '';
 3589: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3590: 		$updateflag = 1;
 3591:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3592:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3593:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3594:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3595:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3596:                     $aggregateflag = 1;
 3597:                 }
 3598: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3599: 		$updateflag = 1;
 3600: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3601: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3602: 		$rec_update++;
 3603: 	    }
 3604: 
 3605: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3606: 		'<td align="center">'.$awarded.
 3607: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3608: 
 3609: 
 3610: 	    my $partid=$_;
 3611: 	    foreach my $stores (@parts) {
 3612: 		my ($part,$type) = &split_part_type($stores);
 3613: 		if ($part !~ m/^\Q$partid\E/) { next;}
 3614: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 3615: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 3616: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 3617: 		if ($awarded ne '' && $awarded ne $old_aw) {
 3618: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 3619: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3620: 		    $updateflag=1;
 3621: 		}
 3622: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3623: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 3624: 	    }
 3625: 	}
 3626: 	$line.="\n";
 3627: 
 3628: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3629: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3630: 
 3631: 	if ($updateflag) {
 3632: 	    $count++;
 3633: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 3634: 				    $udom,$uname);
 3635: 
 3636: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 3637: 					      $cnum,$udom,$uname)) {
 3638: 		# need to figure out if should be in queue.
 3639: 		my %record =  
 3640: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3641: 					     $udom,$uname);
 3642: 		my $all_graded = 1;
 3643: 		my $none_graded = 1;
 3644: 		foreach my $part (@parts) {
 3645: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 3646: 			$all_graded = 0;
 3647: 		    } else {
 3648: 			$none_graded = 0;
 3649: 		    }
 3650: 		}
 3651: 
 3652: 		if ($all_graded || $none_graded) {
 3653: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 3654: 							   $symb,$cdom,$cnum,
 3655: 							   $udom,$uname);
 3656: 		}
 3657: 	    }
 3658: 
 3659: 	    $result.=&Apache::loncommon::start_data_table_row().
 3660: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 3661: 		&Apache::loncommon::end_data_table_row();
 3662: 	    $updateCtr++;
 3663: 	} else {
 3664: 	    push(@noupdate,
 3665: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 3666: 	    $noupdateCtr++;
 3667: 	}
 3668:         if ($aggregateflag) {
 3669:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3670: 				  $cdom,$cnum);
 3671:         }
 3672:     }
 3673:     if (@noupdate) {
 3674: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 3675: 	my $numcols=scalar(@partid)*4+2;
 3676: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 3677: 	    '<td align="center" colspan="'.$numcols.'">'.
 3678: 	    &mt('No Changes Occurred For the Students Below').
 3679: 	    '</td>'.
 3680: 	    &Apache::loncommon::end_data_table_row();
 3681: 	foreach my $line (@noupdate) {
 3682: 	    $result.=
 3683: 		&Apache::loncommon::start_data_table_row().
 3684: 		$line.
 3685: 		&Apache::loncommon::end_data_table_row();
 3686: 	}
 3687:     }
 3688:     $result .= &Apache::loncommon::end_data_table();
 3689:     my $msg = '<p><b>'.
 3690: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 3691: 	    $rec_update,$count).'</b><br />'.
 3692: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 3693: 	'</b></p>';
 3694:     return $title.$msg.$result;
 3695: }
 3696: 
 3697: sub split_part_type {
 3698:     my ($partstr) = @_;
 3699:     my ($temp,@allparts)=split(/_/,$partstr);
 3700:     my $type=pop(@allparts);
 3701:     my $part=join('_',@allparts);
 3702:     return ($part,$type);
 3703: }
 3704: 
 3705: #------------- end of section for handling grading by section/class ---------
 3706: #
 3707: #----------------------------------------------------------------------------
 3708: 
 3709: 
 3710: #----------------------------------------------------------------------------
 3711: #
 3712: #-------------------------- Next few routines handles grading by csv upload
 3713: #
 3714: #--- Javascript to handle csv upload
 3715: sub csvupload_javascript_reverse_associate {
 3716:     my $error1=&mt('You need to specify the username or the student/employee ID');
 3717:     my $error2=&mt('You need to specify at least one grading field');
 3718:   return(<<ENDPICK);
 3719:   function verify(vf) {
 3720:     var foundsomething=0;
 3721:     var founduname=0;
 3722:     var foundID=0;
 3723:     for (i=0;i<=vf.nfields.value;i++) {
 3724:       tw=eval('vf.f'+i+'.selectedIndex');
 3725:       if (i==0 && tw!=0) { foundID=1; }
 3726:       if (i==1 && tw!=0) { founduname=1; }
 3727:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 3728:     }
 3729:     if (founduname==0 && foundID==0) {
 3730: 	alert('$error1');
 3731: 	return;
 3732:     }
 3733:     if (foundsomething==0) {
 3734: 	alert('$error2');
 3735: 	return;
 3736:     }
 3737:     vf.submit();
 3738:   }
 3739:   function flip(vf,tf) {
 3740:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3741:     var i;
 3742:     for (i=0;i<=vf.nfields.value;i++) {
 3743:       //can not pick the same destination field for both name and domain
 3744:       if (((i ==0)||(i ==1)) && 
 3745:           ((tf==0)||(tf==1)) && 
 3746:           (i!=tf) &&
 3747:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3748:         eval('vf.f'+i+'.selectedIndex=0;')
 3749:       }
 3750:     }
 3751:   }
 3752: ENDPICK
 3753: }
 3754: 
 3755: sub csvupload_javascript_forward_associate {
 3756:     my $error1=&mt('You need to specify the username or the student/employee ID');
 3757:     my $error2=&mt('You need to specify at least one grading field');
 3758:   return(<<ENDPICK);
 3759:   function verify(vf) {
 3760:     var foundsomething=0;
 3761:     var founduname=0;
 3762:     var foundID=0;
 3763:     for (i=0;i<=vf.nfields.value;i++) {
 3764:       tw=eval('vf.f'+i+'.selectedIndex');
 3765:       if (tw==1) { foundID=1; }
 3766:       if (tw==2) { founduname=1; }
 3767:       if (tw>3) { foundsomething=1; }
 3768:     }
 3769:     if (founduname==0 && foundID==0) {
 3770: 	alert('$error1');
 3771: 	return;
 3772:     }
 3773:     if (foundsomething==0) {
 3774: 	alert('$error2');
 3775: 	return;
 3776:     }
 3777:     vf.submit();
 3778:   }
 3779:   function flip(vf,tf) {
 3780:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3781:     var i;
 3782:     //can not pick the same destination field twice
 3783:     for (i=0;i<=vf.nfields.value;i++) {
 3784:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3785:         eval('vf.f'+i+'.selectedIndex=0;')
 3786:       }
 3787:     }
 3788:   }
 3789: ENDPICK
 3790: }
 3791: 
 3792: sub csvuploadmap_header {
 3793:     my ($request,$symb,$datatoken,$distotal)= @_;
 3794:     my $javascript;
 3795:     if ($env{'form.upfile_associate'} eq 'reverse') {
 3796: 	$javascript=&csvupload_javascript_reverse_associate();
 3797:     } else {
 3798: 	$javascript=&csvupload_javascript_forward_associate();
 3799:     }
 3800: 
 3801:     $symb = &Apache::lonenc::check_encrypt($symb);
 3802:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
 3803:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
 3804:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
 3805:     my $reverse=&mt("Reverse Association");
 3806:     $request->print(<<ENDPICK);
 3807: <br />
 3808: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 3809: <input type="hidden" name="associate"  value="" />
 3810: <input type="hidden" name="phase"      value="three" />
 3811: <input type="hidden" name="datatoken"  value="$datatoken" />
 3812: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 3813: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 3814: <input type="hidden" name="upfile_associate" 
 3815:                                        value="$env{'form.upfile_associate'}" />
 3816: <input type="hidden" name="symb"       value="$symb" />
 3817: <input type="hidden" name="command"    value="csvuploadoptions" />
 3818: <hr />
 3819: ENDPICK
 3820:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
 3821:     return '';
 3822: 
 3823: }
 3824: 
 3825: sub csvupload_fields {
 3826:     my ($symb,$errorref) = @_;
 3827:     my (@parts) = &getpartlist($symb,$errorref);
 3828:     if (ref($errorref)) {
 3829:         if ($$errorref) {
 3830:             return;
 3831:         }
 3832:     }
 3833: 
 3834:     my @fields=(['ID','Student/Employee ID'],
 3835: 		['username','Student Username'],
 3836: 		['domain','Student Domain']);
 3837:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3838:     foreach my $part (sort(@parts)) {
 3839: 	my @datum;
 3840: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3841: 	my $name=$part;
 3842: 	if  (!$display) { $display = $name; }
 3843: 	@datum=($name,$display);
 3844: 	if ($name=~/^stores_(.*)_awarded/) {
 3845: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 3846: 	}
 3847: 	push(@fields,\@datum);
 3848:     }
 3849:     return (@fields);
 3850: }
 3851: 
 3852: sub csvuploadmap_footer {
 3853:     my ($request,$i,$keyfields) =@_;
 3854:     $request->print(<<ENDPICK);
 3855: </table>
 3856: <input type="hidden" name="nfields" value="$i" />
 3857: <input type="hidden" name="keyfields" value="$keyfields" />
 3858: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
 3859: </form>
 3860: ENDPICK
 3861: }
 3862: 
 3863: sub checkforfile_js {
 3864:     my $alertmsg = &mt('Please use the "Choose File" button to select a file from your local directory.');
 3865:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
 3866:     function checkUpload(formname) {
 3867: 	if (formname.upfile.value == "") {
 3868: 	    alert("$alertmsg");
 3869: 	    return false;
 3870: 	}
 3871: 	formname.submit();
 3872:     }
 3873: CSVFORMJS
 3874:     return $result;
 3875: }
 3876: 
 3877: sub upcsvScores_form {
 3878:     my ($request,$symb) = @_;
 3879:     if (!$symb) {return '';}
 3880:     my $result=&checkforfile_js();
 3881:     $result.=&Apache::loncommon::start_data_table().
 3882:              &Apache::loncommon::start_data_table_header_row().
 3883:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
 3884:              &Apache::loncommon::end_data_table_header_row().
 3885:              &Apache::loncommon::start_data_table_row().'<td>';
 3886:     my $upload=&mt("Upload Scores");
 3887:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 3888:     my $ignore=&mt('Ignore First Line');
 3889:     $symb = &Apache::lonenc::check_encrypt($symb);
 3890:     $result.=<<ENDUPFORM;
 3891: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3892: <input type="hidden" name="symb" value="$symb" />
 3893: <input type="hidden" name="command" value="csvuploadmap" />
 3894: $upfile_select
 3895: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 3896: </form>
 3897: ENDUPFORM
 3898:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 3899:                            &mt("How do I create a CSV file from a spreadsheet")).
 3900:              '</td>'.
 3901:             &Apache::loncommon::end_data_table_row().
 3902:             &Apache::loncommon::end_data_table();
 3903:     return $result;
 3904: }
 3905: 
 3906: 
 3907: sub csvuploadmap {
 3908:     my ($request,$symb)= @_;
 3909:     if (!$symb) {return '';}
 3910: 
 3911:     my $datatoken;
 3912:     if (!$env{'form.datatoken'}) {
 3913: 	$datatoken=&Apache::loncommon::upfile_store($request);
 3914:     } else {
 3915: 	$datatoken=$env{'form.datatoken'};
 3916: 	&Apache::loncommon::load_tmp_file($request);
 3917:     }
 3918:     my @records=&Apache::loncommon::upfile_record_sep();
 3919:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 3920:     my ($i,$keyfields);
 3921:     if (@records) {
 3922:         my $fieldserror;
 3923: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 3924:         if ($fieldserror) {
 3925:             $request->print(&navmap_errormsg());
 3926:             return;
 3927:         }
 3928: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 3929: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 3930: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 3931: 							  \@fields);
 3932: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 3933: 	    chop($keyfields);
 3934: 	} else {
 3935: 	    unshift(@fields,['none','']);
 3936: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 3937: 							    \@fields);
 3938:             foreach my $rec (@records) {
 3939:                 my %temp = &Apache::loncommon::record_sep($rec);
 3940:                 if (%temp) {
 3941:                     $keyfields=join(',',sort(keys(%temp)));
 3942:                     last;
 3943:                 }
 3944:             }
 3945: 	}
 3946:     }
 3947:     &csvuploadmap_footer($request,$i,$keyfields);
 3948: 
 3949:     return '';
 3950: }
 3951: 
 3952: sub csvuploadoptions {
 3953:     my ($request,$symb)= @_;
 3954:     my $overwrite=&mt('Overwrite any existing score');
 3955:     $request->print(<<ENDPICK);
 3956: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3957: <input type="hidden" name="command"    value="csvuploadassign" />
 3958: <p>
 3959: <label>
 3960:    <input type="checkbox" name="overwite_scores" checked="checked" />
 3961:    $overwrite
 3962: </label>
 3963: </p>
 3964: ENDPICK
 3965:     my %fields=&get_fields();
 3966:     if (!defined($fields{'domain'})) {
 3967: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 3968: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
 3969:     }
 3970:     foreach my $key (sort(keys(%env))) {
 3971: 	if ($key !~ /^form\.(.*)$/) { next; }
 3972: 	my $cleankey=$1;
 3973: 	if ($cleankey eq 'command') { next; }
 3974: 	$request->print('<input type="hidden" name="'.$cleankey.
 3975: 			'"  value="'.$env{$key}.'" />'."\n");
 3976:     }
 3977:     # FIXME do a check for any duplicated user ids...
 3978:     # FIXME do a check for any invalid user ids?...
 3979:     $request->print('<input type="submit" value="Assign Grades" /><br />
 3980: <hr /></form>'."\n");
 3981:     return '';
 3982: }
 3983: 
 3984: sub get_fields {
 3985:     my %fields;
 3986:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 3987:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 3988: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 3989: 	    if ($env{'form.f'.$i} ne 'none') {
 3990: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 3991: 	    }
 3992: 	} else {
 3993: 	    if ($env{'form.f'.$i} ne 'none') {
 3994: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 3995: 	    }
 3996: 	}
 3997:     }
 3998:     return %fields;
 3999: }
 4000: 
 4001: sub csvuploadassign {
 4002:     my ($request,$symb)= @_;
 4003:     if (!$symb) {return '';}
 4004:     my $error_msg = '';
 4005:     &Apache::loncommon::load_tmp_file($request);
 4006:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4007:     my %fields=&get_fields();
 4008:     my $courseid=$env{'request.course.id'};
 4009:     my ($classlist) = &getclasslist('all',0);
 4010:     my @notallowed;
 4011:     my @skipped;
 4012:     my $countdone=0;
 4013:     foreach my $grade (@gradedata) {
 4014: 	my %entries=&Apache::loncommon::record_sep($grade);
 4015: 	my $domain;
 4016: 	if ($entries{$fields{'domain'}}) {
 4017: 	    $domain=$entries{$fields{'domain'}};
 4018: 	} else {
 4019: 	    $domain=$env{'form.default_domain'};
 4020: 	}
 4021: 	$domain=~s/\s//g;
 4022: 	my $username=$entries{$fields{'username'}};
 4023: 	$username=~s/\s//g;
 4024: 	if (!$username) {
 4025: 	    my $id=$entries{$fields{'ID'}};
 4026: 	    $id=~s/\s//g;
 4027: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4028: 	    $username=$ids{$id};
 4029: 	}
 4030: 	if (!exists($$classlist{"$username:$domain"})) {
 4031: 	    my $id=$entries{$fields{'ID'}};
 4032: 	    $id=~s/\s//g;
 4033: 	    if ($id) {
 4034: 		push(@skipped,"$id:$domain");
 4035: 	    } else {
 4036: 		push(@skipped,"$username:$domain");
 4037: 	    }
 4038: 	    next;
 4039: 	}
 4040: 	my $usec=$classlist->{"$username:$domain"}[5];
 4041: 	if (!&canmodify($usec)) {
 4042: 	    push(@notallowed,"$username:$domain");
 4043: 	    next;
 4044: 	}
 4045: 	my %points;
 4046: 	my %grades;
 4047: 	foreach my $dest (keys(%fields)) {
 4048: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4049: 		$dest eq 'domain') { next; }
 4050: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4051: 	    if ($dest=~/stores_(.*)_points/) {
 4052: 		my $part=$1;
 4053: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4054: 					      $symb,$domain,$username);
 4055:                 if ($wgt) {
 4056:                     $entries{$fields{$dest}}=~s/\s//g;
 4057:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4058:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4059:                                           : 'correct_by_override';
 4060:                     $grades{"resource.$part.awarded"}=$pcr;
 4061:                     $grades{"resource.$part.solved"}=$award;
 4062:                     $points{$part}=1;
 4063:                 } else {
 4064:                     $error_msg = "<br />" .
 4065:                         &mt("Some point values were assigned"
 4066:                             ." for problems with a weight "
 4067:                             ."of zero. These values were "
 4068:                             ."ignored.");
 4069:                 }
 4070: 	    } else {
 4071: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4072: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4073: 		my $store_key=$dest;
 4074: 		$store_key=~s/^stores/resource/;
 4075: 		$store_key=~s/_/\./g;
 4076: 		$grades{$store_key}=$entries{$fields{$dest}};
 4077: 	    }
 4078: 	}
 4079: 	if (! %grades) { 
 4080:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4081:         } else {
 4082: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4083: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4084: 					   $env{'request.course.id'},
 4085: 					   $domain,$username);
 4086: 	   if ($result eq 'ok') {
 4087: # Successfully stored
 4088: 	      $request->print('.');
 4089: # Remove from grading queue
 4090:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
 4091:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
 4092:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
 4093:                                              $domain,$username);
 4094:               $countdone++;
 4095:            } else {
 4096: 	      $request->print("<p><span class=\"LC_error\">".
 4097:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4098:                                   "$username:$domain",$result)."</span></p>");
 4099: 	   }
 4100: 	   $request->rflush();
 4101:         }
 4102:     }
 4103:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 4104:     if (@skipped) {
 4105: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 4106:         $request->print(join(', ',@skipped));
 4107:     }
 4108:     if (@notallowed) {
 4109: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 4110: 	$request->print(join(', ',@notallowed));
 4111:     }
 4112:     $request->print("<br />\n");
 4113:     return $error_msg;
 4114: }
 4115: #------------- end of section for handling csv file upload ---------
 4116: #
 4117: #-------------------------------------------------------------------
 4118: #
 4119: #-------------- Next few routines handle grading by page/sequence
 4120: #
 4121: #--- Select a page/sequence and a student to grade
 4122: sub pickStudentPage {
 4123:     my ($request,$symb) = @_;
 4124: 
 4125:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4126:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
 4127: 
 4128: function checkPickOne(formname) {
 4129:     if (radioSelection(formname.student) == null) {
 4130: 	alert("$alertmsg");
 4131: 	return;
 4132:     }
 4133:     ptr = pullDownSelection(formname.selectpage);
 4134:     formname.page.value = formname["page"+ptr].value;
 4135:     formname.title.value = formname["title"+ptr].value;
 4136:     formname.submit();
 4137: }
 4138: 
 4139: LISTJAVASCRIPT
 4140:     &commonJSfunctions($request);
 4141: 
 4142:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4143:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4144:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4145: 
 4146:     my $result='<h3><span class="LC_info">&nbsp;'.
 4147: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4148: 
 4149:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4150:     my $map_error;
 4151:     my ($titles,$symbx) = &getSymbMap($map_error);
 4152:     if ($map_error) {
 4153:         $request->print(&navmap_errormsg());
 4154:         return; 
 4155:     }
 4156:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4157: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4158: #    my $type=($curpage =~ /\.(page|sequence)/);
 4159:     my $select = '<select name="selectpage">'."\n";
 4160:     my $ctr=0;
 4161:     foreach (@$titles) {
 4162: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4163: 	$select.='<option value="'.$ctr.'" '.
 4164: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4165: 	    '>'.$showtitle.'</option>'."\n";
 4166: 	$ctr++;
 4167:     }
 4168:     $select.= '</select>';
 4169:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
 4170: 
 4171:     $ctr=0;
 4172:     foreach (@$titles) {
 4173: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4174: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4175: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4176: 	$ctr++;
 4177:     }
 4178:     $result.='<input type="hidden" name="page" />'."\n".
 4179: 	'<input type="hidden" name="title" />'."\n";
 4180: 
 4181:     my $options =
 4182: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
 4183: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
 4184:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
 4185: 
 4186:     $options =
 4187: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
 4188: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
 4189: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
 4190:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
 4191:     
 4192:     $result.=&build_section_inputs();
 4193:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4194:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4195: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4196: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."<br />\n";
 4197: 
 4198:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
 4199: 
 4200:     $result.='&nbsp;<input type="button" '.
 4201:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4202: 
 4203:     $request->print($result);
 4204: 
 4205:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4206: 	&Apache::loncommon::start_data_table().
 4207: 	&Apache::loncommon::start_data_table_header_row().
 4208: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4209: 	'<th>'.&nameUserString('header').'</th>'.
 4210: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4211: 	'<th>'.&nameUserString('header').'</th>'.
 4212: 	&Apache::loncommon::end_data_table_header_row();
 4213:  
 4214:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4215:     my $ptr = 1;
 4216:     foreach my $student (sort 
 4217: 			 {
 4218: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4219: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4220: 			     }
 4221: 			     return $a cmp $b;
 4222: 			 } (keys(%$fullname))) {
 4223: 	my ($uname,$udom) = split(/:/,$student);
 4224: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4225:                                   : '</td>');
 4226: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4227: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4228: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4229: 	$studentTable.=
 4230: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4231:                          : '');
 4232: 	$ptr++;
 4233:     }
 4234:     if ($ptr%2 == 0) {
 4235: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4236: 	    &Apache::loncommon::end_data_table_row();
 4237:     }
 4238:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4239:     $studentTable.='<input type="button" '.
 4240:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4241: 
 4242:     $request->print($studentTable);
 4243: 
 4244:     return '';
 4245: }
 4246: 
 4247: sub getSymbMap {
 4248:     my ($map_error) = @_;
 4249:     my $navmap = Apache::lonnavmaps::navmap->new();
 4250:     unless (ref($navmap)) {
 4251:         if (ref($map_error)) {
 4252:             $$map_error = 'navmap';
 4253:         }
 4254:         return;
 4255:     }
 4256:     my %symbx = ();
 4257:     my @titles = ();
 4258:     my $minder = 0;
 4259: 
 4260:     # Gather every sequence that has problems.
 4261:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4262: 					       1,0,1);
 4263:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4264: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4265: 	    my $title = $minder.'.'.
 4266: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4267: 	    push(@titles, $title); # minder in case two titles are identical
 4268: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4269: 	    $minder++;
 4270: 	}
 4271:     }
 4272:     return \@titles,\%symbx;
 4273: }
 4274: 
 4275: #
 4276: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4277: sub displayPage {
 4278:     my ($request,$symb) = @_;
 4279:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4280:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4281:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4282:     my $pageTitle = $env{'form.page'};
 4283:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4284:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4285:     my $usec=$classlist->{$env{'form.student'}}[5];
 4286: 
 4287:     #need to make sure we have the correct data for later EXT calls, 
 4288:     #thus invalidate the cache
 4289:     &Apache::lonnet::devalidatecourseresdata(
 4290:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4291:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4292:     &Apache::lonnet::clear_EXT_cache_status();
 4293: 
 4294:     if (!&canview($usec)) {
 4295: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
 4296: 	return;
 4297:     }
 4298:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4299:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4300: 	'</h3>'."\n";
 4301:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4302:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4303: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4304:     } else {
 4305: 	delete($env{'form.CODE'});
 4306:     }
 4307:     &sub_page_js($request);
 4308:     $request->print($result);
 4309: 
 4310:     my $navmap = Apache::lonnavmaps::navmap->new();
 4311:     unless (ref($navmap)) {
 4312:         $request->print(&navmap_errormsg());
 4313:         return;
 4314:     }
 4315:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4316:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4317:     if (!$map) {
 4318: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4319: 	return; 
 4320:     }
 4321:     my $iterator = $navmap->getIterator($map->map_start(),
 4322: 					$map->map_finish());
 4323: 
 4324:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4325: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4326: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4327: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4328: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4329: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4330: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4331: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
 4332: 
 4333:     if (defined($env{'form.CODE'})) {
 4334: 	$studentTable.=
 4335: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4336:     }
 4337:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4338: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4339: 
 4340:     $studentTable.='&nbsp;<span class="LC_info">'.
 4341:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 4342:         '</span>'."\n".
 4343: 	&Apache::loncommon::start_data_table().
 4344: 	&Apache::loncommon::start_data_table_header_row().
 4345: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
 4346: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4347: 	&Apache::loncommon::end_data_table_header_row();
 4348: 
 4349:     &Apache::lonxml::clear_problem_counter();
 4350:     my ($depth,$question,$prob) = (1,1,1);
 4351:     $iterator->next(); # skip the first BEGIN_MAP
 4352:     my $curRes = $iterator->next(); # for "current resource"
 4353:     while ($depth > 0) {
 4354:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4355:         if($curRes == $iterator->END_MAP) { $depth--; }
 4356: 
 4357:         if (ref($curRes) && $curRes->is_problem()) {
 4358: 	    my $parts = $curRes->parts();
 4359:             my $title = $curRes->compTitle();
 4360: 	    my $symbx = $curRes->symb();
 4361: 	    $studentTable.=
 4362: 		&Apache::loncommon::start_data_table_row().
 4363: 		'<td align="center" valign="top" >'.$prob.
 4364: 		(scalar(@{$parts}) == 1 ? '' 
 4365: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
 4366: 							scalar(@{$parts}))
 4367: 		 ).
 4368: 		 '</td>';
 4369: 	    $studentTable.='<td valign="top">';
 4370: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4371: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4372: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4373: 					     undef,'both',\%form);
 4374: 	    } else {
 4375: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4376: 		$companswer =~ s|<form(.*?)>||g;
 4377: 		$companswer =~ s|</form>||g;
 4378: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4379: #		    $companswer =~ s/$1/ /ms;
 4380: #		    $request->print('match='.$1."<br />\n");
 4381: #		}
 4382: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4383: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 4384: 	    }
 4385: 
 4386: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4387: 
 4388: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4389: 		if ($record{'version'} eq '') {
 4390: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4391: 		} else {
 4392: 		    my %responseType = ();
 4393: 		    foreach my $partid (@{$parts}) {
 4394: 			my @responseIds =$curRes->responseIds($partid);
 4395: 			my @responseType =$curRes->responseType($partid);
 4396: 			my %responseIds;
 4397: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4398: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4399: 			}
 4400: 			$responseType{$partid} = \%responseIds;
 4401: 		    }
 4402: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4403: 
 4404: 		}
 4405: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4406: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4407: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4408: 									$env{'request.course.id'},
 4409: 									'','.submission');
 4410:  
 4411: 	    }
 4412: 	    if (&canmodify($usec)) {
 4413:             $studentTable.=&gradeBox_start();
 4414: 		foreach my $partid (@{$parts}) {
 4415: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4416: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4417: 		    $question++;
 4418: 		}
 4419:             $studentTable.=&gradeBox_end();
 4420: 		$prob++;
 4421: 	    }
 4422: 	    $studentTable.='</td></tr>';
 4423: 
 4424: 	}
 4425:         $curRes = $iterator->next();
 4426:     }
 4427: 
 4428:     $studentTable.=
 4429:         '</table>'."\n".
 4430:         '<input type="button" value="'.&mt('Save').'" '.
 4431:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4432:         '</form>'."\n";
 4433:     $request->print($studentTable);
 4434: 
 4435:     return '';
 4436: }
 4437: 
 4438: sub displaySubByDates {
 4439:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4440:     my $isCODE=0;
 4441:     my $isTask = ($symb =~/\.task$/);
 4442:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4443:     my $studentTable=&Apache::loncommon::start_data_table().
 4444: 	&Apache::loncommon::start_data_table_header_row().
 4445: 	'<th>'.&mt('Date/Time').'</th>'.
 4446: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4447: 	'<th>'.&mt('Submission').'</th>'.
 4448: 	'<th>'.&mt('Status').'</th>'.
 4449: 	&Apache::loncommon::end_data_table_header_row();
 4450:     my ($version);
 4451:     my %mark;
 4452:     my %orders;
 4453:     $mark{'correct_by_student'} = $checkIcon;
 4454:     if (!exists($$record{'1:timestamp'})) {
 4455: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 4456:     }
 4457: 
 4458:     my $interaction;
 4459:     my $no_increment = 1;
 4460:     for ($version=1;$version<=$$record{'version'};$version++) {
 4461: 	my $timestamp = 
 4462: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4463: 	if (exists($$record{$version.':resource.0.version'})) {
 4464: 	    $interaction = $$record{$version.':resource.0.version'};
 4465: 	}
 4466: 
 4467: 	my $where = ($isTask ? "$version:resource.$interaction"
 4468: 		             : "$version:resource");
 4469: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4470: 	    '<td>'.$timestamp.'</td>';
 4471: 	if ($isCODE) {
 4472: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4473: 	}
 4474: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4475: 	my @displaySub = ();
 4476: 	foreach my $partid (@{$parts}) {
 4477:             my $hidden;
 4478:             if (($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurvey') ||
 4479:                 ($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurveycred')) {
 4480:                 $hidden = 1;
 4481:             }
 4482: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4483: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4484: 	    
 4485: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4486: 	    my $display_part=&get_display_part($partid,$symb);
 4487: 	    foreach my $matchKey (@matchKey) {
 4488: 		if (exists($$record{$version.':'.$matchKey}) &&
 4489: 		    $$record{$version.':'.$matchKey} ne '') {
 4490:                     
 4491: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4492: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4493:                     $displaySub[0].='<span class="LC_nobreak"';
 4494:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 4495:                                    .' <span class="LC_internal_info">'
 4496:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
 4497:                                    .'</span>'
 4498:                                    .' <b>';
 4499:                     if ($hidden) {
 4500:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
 4501:                     } else {
 4502: 		        if ($$record{"$where.$partid.tries"} eq '') {
 4503: 			    $displaySub[0].=&mt('Trial not counted');
 4504: 		        } else {
 4505: 			    $displaySub[0].=&mt('Trial: [_1]',
 4506: 					    $$record{"$where.$partid.tries"});
 4507: 		        }
 4508: 		        my $responseType=($isTask ? 'Task'
 4509:                                               : $responseType->{$partid}->{$responseId});
 4510: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4511: 		        if (!exists($orders{$partid}->{$responseId})) {
 4512: 			    $orders{$partid}->{$responseId}=
 4513: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
 4514:                                            $no_increment);
 4515: 		        }
 4516: 		        $displaySub[0].='</b></span>'; # /nobreak
 4517: 		        $displaySub[0].='&nbsp; '.
 4518: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
 4519:                     }
 4520: 		}
 4521: 	    }
 4522: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4523: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 4524: 				    $$record{"$where.$partid.checkedin"},
 4525: 				    $$record{"$where.$partid.checkedin.slot"}).
 4526: 					'<br />';
 4527: 	    }
 4528: 	    if (exists $$record{"$where.$partid.award"}) {
 4529: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 4530: 		    lc($$record{"$where.$partid.award"}).' '.
 4531: 		    $mark{$$record{"$where.$partid.solved"}}.
 4532: 		    '<br />';
 4533: 	    }
 4534: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4535: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4536: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4537: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4538: 		$displaySub[2].=
 4539: 		    $$record{"$version:resource.$partid.regrader"}.
 4540: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4541: 	    }
 4542: 	}
 4543: 	# needed because old essay regrader has not parts info
 4544: 	if (exists $$record{"$version:resource.regrader"}) {
 4545: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 4546: 	}
 4547: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 4548: 	if ($displaySub[2]) {
 4549: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 4550: 	}
 4551: 	$studentTable.='&nbsp;</td>'.
 4552: 	    &Apache::loncommon::end_data_table_row();
 4553:     }
 4554:     $studentTable.=&Apache::loncommon::end_data_table();
 4555:     return $studentTable;
 4556: }
 4557: 
 4558: sub updateGradeByPage {
 4559:     my ($request,$symb) = @_;
 4560: 
 4561:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4562:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4563:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4564:     my $pageTitle = $env{'form.page'};
 4565:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4566:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4567:     my $usec=$classlist->{$env{'form.student'}}[5];
 4568:     if (!&canmodify($usec)) {
 4569: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 4570: 	return;
 4571:     }
 4572:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4573:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 4574: 	'</h3>'."\n";
 4575: 
 4576:     $request->print($result);
 4577: 
 4578: 
 4579:     my $navmap = Apache::lonnavmaps::navmap->new();
 4580:     unless (ref($navmap)) {
 4581:         $request->print(&navmap_errormsg());
 4582:         return;
 4583:     }
 4584:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 4585:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4586:     if (!$map) {
 4587: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 4588: 	return; 
 4589:     }
 4590:     my $iterator = $navmap->getIterator($map->map_start(),
 4591: 					$map->map_finish());
 4592: 
 4593:     my $studentTable=
 4594: 	&Apache::loncommon::start_data_table().
 4595: 	&Apache::loncommon::start_data_table_header_row().
 4596: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 4597: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 4598: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 4599: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 4600: 	&Apache::loncommon::end_data_table_header_row();
 4601: 
 4602:     $iterator->next(); # skip the first BEGIN_MAP
 4603:     my $curRes = $iterator->next(); # for "current resource"
 4604:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 4605:     while ($depth > 0) {
 4606:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4607:         if($curRes == $iterator->END_MAP) { $depth--; }
 4608: 
 4609:         if (ref($curRes) && $curRes->is_problem()) {
 4610: 	    my $parts = $curRes->parts();
 4611:             my $title = $curRes->compTitle();
 4612: 	    my $symbx = $curRes->symb();
 4613: 	    $studentTable.=
 4614: 		&Apache::loncommon::start_data_table_row().
 4615: 		'<td align="center" valign="top" >'.$prob.
 4616: 		(scalar(@{$parts}) == 1 ? '' 
 4617:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
 4618: 		.')').'</td>';
 4619: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 4620: 
 4621: 	    my %newrecord=();
 4622: 	    my @displayPts=();
 4623:             my %aggregate = ();
 4624:             my $aggregateflag = 0;
 4625: 	    foreach my $partid (@{$parts}) {
 4626: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 4627: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 4628: 
 4629: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 4630: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 4631: 		my $partial = $newpts/$wgt;
 4632: 		my $score;
 4633: 		if ($partial > 0) {
 4634: 		    $score = 'correct_by_override';
 4635: 		} elsif ($newpts ne '') { #empty is taken as 0
 4636: 		    $score = 'incorrect_by_override';
 4637: 		}
 4638: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 4639: 		if ($dropMenu eq 'excused') {
 4640: 		    $partial = '';
 4641: 		    $score = 'excused';
 4642: 		} elsif ($dropMenu eq 'reset status'
 4643: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 4644: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 4645: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 4646: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 4647: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 4648: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 4649: 		    $changeflag++;
 4650: 		    $newpts = '';
 4651:                     
 4652:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 4653:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 4654:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 4655:                     if ($aggtries > 0) {
 4656:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4657:                         $aggregateflag = 1;
 4658:                     }
 4659: 		}
 4660: 		my $display_part=&get_display_part($partid,$curRes->symb());
 4661: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 4662: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4663: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 4664: 		    '&nbsp;<br />';
 4665: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4666: 		     (($score eq 'excused') ? 'excused' : $newpts).
 4667: 		    '&nbsp;<br />';
 4668: 		$question++;
 4669: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 4670: 
 4671: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 4672: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 4673: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 4674: 		    if (scalar(keys(%newrecord)) > 0);
 4675: 
 4676: 		$changeflag++;
 4677: 	    }
 4678: 	    if (scalar(keys(%newrecord)) > 0) {
 4679: 		my %record = 
 4680: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 4681: 					     $udom,$uname);
 4682: 
 4683: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 4684: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 4685: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 4686: 		    $newrecord{'resource.CODE'} = '';
 4687: 		}
 4688: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 4689: 					$udom,$uname);
 4690: 		%record = &Apache::lonnet::restore($symbx,
 4691: 						   $env{'request.course.id'},
 4692: 						   $udom,$uname);
 4693: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 4694: 					     $cdom,$cnum,$udom,$uname);
 4695: 	    }
 4696: 	    
 4697:             if ($aggregateflag) {
 4698:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4699:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 4700:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 4701:             }
 4702: 
 4703: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 4704: 		'<td valign="top">'.$displayPts[1].'</td>'.
 4705: 		&Apache::loncommon::end_data_table_row();
 4706: 
 4707: 	    $prob++;
 4708: 	}
 4709:         $curRes = $iterator->next();
 4710:     }
 4711: 
 4712:     $studentTable.=&Apache::loncommon::end_data_table();
 4713:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 4714: 		  &mt('The scores were changed for [quant,_1,problem].',
 4715: 		  $changeflag));
 4716:     $request->print($grademsg.$studentTable);
 4717: 
 4718:     return '';
 4719: }
 4720: 
 4721: #-------- end of section for handling grading by page/sequence ---------
 4722: #
 4723: #-------------------------------------------------------------------
 4724: 
 4725: #-------------------- Bubblesheet (Scantron) Grading -------------------
 4726: #
 4727: #------ start of section for handling grading by page/sequence ---------
 4728: 
 4729: =pod
 4730: 
 4731: =head1 Bubble sheet grading routines
 4732: 
 4733:   For this documentation:
 4734: 
 4735:    'scanline' refers to the full line of characters
 4736:    from the file that we are parsing that represents one entire sheet
 4737: 
 4738:    'bubble line' refers to the data
 4739:    representing the line of bubbles that are on the physical bubble sheet
 4740: 
 4741: 
 4742: The overall process is that a scanned in bubble sheet data is uploaded
 4743: into a course. When a user wants to grade, they select a
 4744: sequence/folder of resources, a file of bubble sheet info, and pick
 4745: one of the predefined configurations for what each scanline looks
 4746: like.
 4747: 
 4748: Next each scanline is checked for any errors of either 'missing
 4749: bubbles' (it's an error because it may have been mis-scanned
 4750: because too light bubbling), 'double bubble' (each bubble line should
 4751: have no more that one letter picked), invalid or duplicated CODE,
 4752: invalid student/employee ID
 4753: 
 4754: If the CODE option is used that determines the randomization of the
 4755: homework problems, either way the student/employee ID is looked up into a
 4756: username:domain.
 4757: 
 4758: During the validation phase the instructor can choose to skip scanlines. 
 4759: 
 4760: After the validation phase, there are now 3 bubble sheet files
 4761: 
 4762:   scantron_original_filename (unmodified original file)
 4763:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 4764:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 4765: 
 4766: Also there is a separate hash nohist_scantrondata that contains extra
 4767: correction information that isn't representable in the bubble sheet
 4768: file (see &scantron_getfile() for more information)
 4769: 
 4770: After all scanlines are either valid, marked as valid or skipped, then
 4771: foreach line foreach problem in the picked sequence, an ssi request is
 4772: made that simulates a user submitting their selected letter(s) against
 4773: the homework problem.
 4774: 
 4775: =over 4
 4776: 
 4777: 
 4778: 
 4779: =item defaultFormData
 4780: 
 4781:   Returns html hidden inputs used to hold context/default values.
 4782: 
 4783:  Arguments:
 4784:   $symb - $symb of the current resource 
 4785: 
 4786: =cut
 4787: 
 4788: sub defaultFormData {
 4789:     my ($symb)=@_;
 4790:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
 4791: }
 4792: 
 4793: 
 4794: =pod 
 4795: 
 4796: =item getSequenceDropDown
 4797: 
 4798:    Return html dropdown of possible sequences to grade
 4799:  
 4800:  Arguments:
 4801:    $symb - $symb of the current resource
 4802:    $map_error - ref to scalar which will container error if
 4803:                 $navmap object is unavailable in &getSymbMap().
 4804: 
 4805: =cut
 4806: 
 4807: sub getSequenceDropDown {
 4808:     my ($symb,$map_error)=@_;
 4809:     my $result='<select name="selectpage">'."\n";
 4810:     my ($titles,$symbx) = &getSymbMap($map_error);
 4811:     if (ref($map_error)) {
 4812:         return if ($$map_error);
 4813:     }
 4814:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 4815:     my $ctr=0;
 4816:     foreach (@$titles) {
 4817: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4818: 	$result.='<option value="'.$$symbx{$_}.'" '.
 4819: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4820: 	    '>'.$showtitle.'</option>'."\n";
 4821: 	$ctr++;
 4822:     }
 4823:     $result.= '</select>';
 4824:     return $result;
 4825: }
 4826: 
 4827: my %bubble_lines_per_response;     # no. bubble lines for each response.
 4828:                                    # key is zero-based index - 0, 1, 2 ...
 4829: 
 4830: my %first_bubble_line;             # First bubble line no. for each bubble.
 4831: 
 4832: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 4833:                                    # matchresponse or rankresponse, where 
 4834:                                    # an individual response can have multiple 
 4835:                                    # lines
 4836: 
 4837: my %responsetype_per_response;     # responsetype for each response
 4838: 
 4839: # Save and restore the bubble lines array to the form env.
 4840: 
 4841: 
 4842: sub save_bubble_lines {
 4843:     foreach my $line (keys(%bubble_lines_per_response)) {
 4844: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 4845: 	$env{"form.scantron.first_bubble_line.$line"} =
 4846: 	    $first_bubble_line{$line};
 4847:         $env{"form.scantron.sub_bubblelines.$line"} = 
 4848:             $subdivided_bubble_lines{$line};
 4849:         $env{"form.scantron.responsetype.$line"} =
 4850:             $responsetype_per_response{$line};
 4851:     }
 4852: }
 4853: 
 4854: 
 4855: sub restore_bubble_lines {
 4856:     my $line = 0;
 4857:     %bubble_lines_per_response = ();
 4858:     while ($env{"form.scantron.bubblelines.$line"}) {
 4859: 	my $value = $env{"form.scantron.bubblelines.$line"};
 4860: 	$bubble_lines_per_response{$line} = $value;
 4861: 	$first_bubble_line{$line}  =
 4862: 	    $env{"form.scantron.first_bubble_line.$line"};
 4863:         $subdivided_bubble_lines{$line} =
 4864:             $env{"form.scantron.sub_bubblelines.$line"};
 4865:         $responsetype_per_response{$line} =
 4866:             $env{"form.scantron.responsetype.$line"};
 4867: 	$line++;
 4868:     }
 4869: }
 4870: 
 4871: #  Given the parsed scanline, get the response for 
 4872: #  'answer' number n:
 4873: 
 4874: sub get_response_bubbles {
 4875:     my ($parsed_line, $response)  = @_;
 4876: 
 4877:     my $bubble_line = $first_bubble_line{$response-1} +1;
 4878:     my $bubble_lines= $bubble_lines_per_response{$response-1};
 4879:     
 4880:     my $selected = "";
 4881: 
 4882:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
 4883: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
 4884: 	$bubble_line++;
 4885:     }
 4886:     return $selected;
 4887: }
 4888: 
 4889: =pod 
 4890: 
 4891: =item scantron_filenames
 4892: 
 4893:    Returns a list of the scantron files in the current course 
 4894: 
 4895: =cut
 4896: 
 4897: sub scantron_filenames {
 4898:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4899:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4900:     my $getpropath = 1;
 4901:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
 4902:                                        $getpropath);
 4903:     my @possiblenames;
 4904:     foreach my $filename (sort(@files)) {
 4905: 	($filename)=split(/&/,$filename);
 4906: 	if ($filename!~/^scantron_orig_/) { next ; }
 4907: 	$filename=~s/^scantron_orig_//;
 4908: 	push(@possiblenames,$filename);
 4909:     }
 4910:     return @possiblenames;
 4911: }
 4912: 
 4913: =pod 
 4914: 
 4915: =item scantron_uploads
 4916: 
 4917:    Returns  html drop-down list of scantron files in current course.
 4918: 
 4919:  Arguments:
 4920:    $file2grade - filename to set as selected in the dropdown
 4921: 
 4922: =cut
 4923: 
 4924: sub scantron_uploads {
 4925:     my ($file2grade) = @_;
 4926:     my $result=	'<select name="scantron_selectfile">';
 4927:     $result.="<option></option>";
 4928:     foreach my $filename (sort(&scantron_filenames())) {
 4929: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 4930:     }
 4931:     $result.="</select>";
 4932:     return $result;
 4933: }
 4934: 
 4935: =pod 
 4936: 
 4937: =item scantron_scantab
 4938: 
 4939:   Returns html drop down of the scantron formats in the scantronformat.tab
 4940:   file.
 4941: 
 4942: =cut
 4943: 
 4944: sub scantron_scantab {
 4945:     my $result='<select name="scantron_format">'."\n";
 4946:     $result.='<option></option>'."\n";
 4947:     my @lines = &get_scantronformat_file();
 4948:     if (@lines > 0) {
 4949:         foreach my $line (@lines) {
 4950:             next if (($line =~ /^\#/) || ($line eq ''));
 4951: 	    my ($name,$descrip)=split(/:/,$line);
 4952: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 4953:         }
 4954:     }
 4955:     $result.='</select>'."\n";
 4956:     return $result;
 4957: }
 4958: 
 4959: =pod
 4960: 
 4961: =item get_scantronformat_file
 4962: 
 4963:   Returns an array containing lines from the scantron format file for
 4964:   the domain of the course.
 4965: 
 4966:   If a url for a custom.tab file is listed in domain's configuration.db, 
 4967:   lines are from this file.
 4968: 
 4969:   Otherwise, if a default.tab has been published in RES space by the 
 4970:   domainconfig user, lines are from this file.
 4971: 
 4972:   Otherwise, fall back to getting lines from the legacy file on the
 4973:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 4974: 
 4975: =cut
 4976: 
 4977: sub get_scantronformat_file {
 4978:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 4979:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 4980:     my $gottab = 0;
 4981:     my @lines;
 4982:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 4983:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 4984:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 4985:             if ($formatfile ne '-1') {
 4986:                 @lines = split("\n",$formatfile,-1);
 4987:                 $gottab = 1;
 4988:             }
 4989:         }
 4990:     }
 4991:     if (!$gottab) {
 4992:         my $confname = $cdom.'-domainconfig';
 4993:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 4994:         my $formatfile =  &Apache::lonnet::getfile($default);
 4995:         if ($formatfile ne '-1') {
 4996:             @lines = split("\n",$formatfile,-1);
 4997:             $gottab = 1;
 4998:         }
 4999:     }
 5000:     if (!$gottab) {
 5001:         my @domains = &Apache::lonnet::current_machine_domains();
 5002:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5003:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5004:             @lines = <$fh>;
 5005:             close($fh);
 5006:         } else {
 5007:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 5008:             @lines = <$fh>;
 5009:             close($fh);
 5010:         }
 5011:     }
 5012:     return @lines;
 5013: }
 5014: 
 5015: =pod 
 5016: 
 5017: =item scantron_CODElist
 5018: 
 5019:   Returns html drop down of the saved CODE lists from current course,
 5020:   generated from earlier printings.
 5021: 
 5022: =cut
 5023: 
 5024: sub scantron_CODElist {
 5025:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5026:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5027:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5028:     my $namechoice='<option></option>';
 5029:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5030: 	if ($name =~ /^error: 2 /) { next; }
 5031: 	if ($name =~ /^type\0/) { next; }
 5032: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5033:     }
 5034:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5035:     return $namechoice;
 5036: }
 5037: 
 5038: =pod 
 5039: 
 5040: =item scantron_CODEunique
 5041: 
 5042:   Returns the html for "Each CODE to be used once" radio.
 5043: 
 5044: =cut
 5045: 
 5046: sub scantron_CODEunique {
 5047:     my $result='<span class="LC_nobreak">
 5048:                  <label><input type="radio" name="scantron_CODEunique"
 5049:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5050:                 </span>
 5051:                 <span class="LC_nobreak">
 5052:                  <label><input type="radio" name="scantron_CODEunique"
 5053:                         value="no" />'.&mt('No').' </label>
 5054:                 </span>';
 5055:     return $result;
 5056: }
 5057: 
 5058: =pod 
 5059: 
 5060: =item scantron_selectphase
 5061: 
 5062:   Generates the initial screen to start the bubble sheet process.
 5063:   Allows for - starting a grading run.
 5064:              - downloading existing scan data (original, corrected
 5065:                                                 or skipped info)
 5066: 
 5067:              - uploading new scan data
 5068: 
 5069:  Arguments:
 5070:   $r          - The Apache request object
 5071:   $file2grade - name of the file that contain the scanned data to score
 5072: 
 5073: =cut
 5074: 
 5075: sub scantron_selectphase {
 5076:     my ($r,$file2grade,$symb) = @_;
 5077:     if (!$symb) {return '';}
 5078:     my $map_error;
 5079:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 5080:     if ($map_error) {
 5081:         $r->print('<br />'.&navmap_errormsg().'<br />');
 5082:         return;
 5083:     }
 5084:     my $default_form_data=&defaultFormData($symb);
 5085:     my $file_selector=&scantron_uploads($file2grade);
 5086:     my $format_selector=&scantron_scantab();
 5087:     my $CODE_selector=&scantron_CODElist();
 5088:     my $CODE_unique=&scantron_CODEunique();
 5089:     my $result;
 5090: 
 5091:     $ssi_error = 0;
 5092: 
 5093:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5094:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5095: 
 5096: 	# Chunk of form to prompt for a scantron file upload.
 5097: 
 5098:         $r->print('
 5099:     <br />
 5100:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5101:        '.&Apache::loncommon::start_data_table_header_row().'
 5102:             <th>
 5103:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 5104:             </th>
 5105:        '.&Apache::loncommon::end_data_table_header_row().'
 5106:        '.&Apache::loncommon::start_data_table_row().'
 5107:             <td>
 5108: ');
 5109:     my $default_form_data=&defaultFormData($symb);
 5110:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5111:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5112:     $r->print(&Apache::lonhtmlcommon::scripttag('
 5113:     function checkUpload(formname) {
 5114: 	if (formname.upfile.value == "") {
 5115: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 5116: 	    return false;
 5117: 	}
 5118: 	formname.submit();
 5119:     }'));
 5120:     $r->print('
 5121:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5122:                 '.$default_form_data.'
 5123:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5124:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5125:                 <input name="command" value="scantronupload_save" type="hidden" />
 5126:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5127:                 <br />
 5128:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 5129:               </form>
 5130: ');
 5131: 
 5132:         $r->print('
 5133:             </td>
 5134:        '.&Apache::loncommon::end_data_table_row().'
 5135:        '.&Apache::loncommon::end_data_table().'
 5136: ');
 5137:     }
 5138: 
 5139:     # Chunk of form to prompt for a file to grade and how:
 5140: 
 5141:     $result.= '
 5142:     <br />
 5143:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5144:     <input type="hidden" name="command" value="scantron_warning" />
 5145:     '.$default_form_data.'
 5146:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5147:        '.&Apache::loncommon::start_data_table_header_row().'
 5148:             <th colspan="2">
 5149:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5150:             </th>
 5151:        '.&Apache::loncommon::end_data_table_header_row().'
 5152:        '.&Apache::loncommon::start_data_table_row().'
 5153:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5154:        '.&Apache::loncommon::end_data_table_row().'
 5155:        '.&Apache::loncommon::start_data_table_row().'
 5156:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 5157:        '.&Apache::loncommon::end_data_table_row().'
 5158:        '.&Apache::loncommon::start_data_table_row().'
 5159:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 5160:        '.&Apache::loncommon::end_data_table_row().'
 5161:        '.&Apache::loncommon::start_data_table_row().'
 5162:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5163:        '.&Apache::loncommon::end_data_table_row().'
 5164:        '.&Apache::loncommon::start_data_table_row().'
 5165:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5166:        '.&Apache::loncommon::end_data_table_row().'
 5167:        '.&Apache::loncommon::start_data_table_row().'
 5168: 	    <td> '.&mt('Options:').' </td>
 5169:             <td>
 5170: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5171:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5172:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5173: 	    </td>
 5174:        '.&Apache::loncommon::end_data_table_row().'
 5175:        '.&Apache::loncommon::start_data_table_row().'
 5176:             <td colspan="2">
 5177:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 5178:             </td>
 5179:        '.&Apache::loncommon::end_data_table_row().'
 5180:     '.&Apache::loncommon::end_data_table().'
 5181:     </form>
 5182: ';
 5183:    
 5184:     $r->print($result);
 5185: 
 5186: 
 5187: 
 5188:     # Chunk of the form that prompts to view a scoring office file,
 5189:     # corrected file, skipped records in a file.
 5190: 
 5191:     $r->print('
 5192:    <br />
 5193:    <form action="/adm/grades" name="scantron_download">
 5194:      '.$default_form_data.'
 5195:      <input type="hidden" name="command" value="scantron_download" />
 5196:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5197:        '.&Apache::loncommon::start_data_table_header_row().'
 5198:               <th>
 5199:                 &nbsp;'.&mt('Download a scoring office file').'
 5200:               </th>
 5201:        '.&Apache::loncommon::end_data_table_header_row().'
 5202:        '.&Apache::loncommon::start_data_table_row().'
 5203:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5204:                 <br />
 5205:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5206:        '.&Apache::loncommon::end_data_table_row().'
 5207:      '.&Apache::loncommon::end_data_table().'
 5208:    </form>
 5209:    <br />
 5210: ');
 5211: 
 5212:     &Apache::lonpickcode::code_list($r,2);
 5213: 
 5214:     $r->print('<br /><form method="post" name="checkscantron">'.
 5215:              $default_form_data."\n".
 5216:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5217:              &Apache::loncommon::start_data_table_header_row()."\n".
 5218:              '<th colspan="2">
 5219:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 5220:              '</th>'."\n".
 5221:               &Apache::loncommon::end_data_table_header_row()."\n".
 5222:               &Apache::loncommon::start_data_table_row()."\n".
 5223:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5224:               '<td> '.$sequence_selector.' </td>'.
 5225:               &Apache::loncommon::end_data_table_row()."\n".
 5226:               &Apache::loncommon::start_data_table_row()."\n".
 5227:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5228:               '<td> '.$file_selector.' </td>'."\n".
 5229:               &Apache::loncommon::end_data_table_row()."\n".
 5230:               &Apache::loncommon::start_data_table_row()."\n".
 5231:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5232:               '<td> '.$format_selector.' </td>'."\n".
 5233:               &Apache::loncommon::end_data_table_row()."\n".
 5234:               &Apache::loncommon::start_data_table_row()."\n".
 5235:               '<td> '.&mt('Options').' </td>'."\n".
 5236:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 5237:               &Apache::loncommon::end_data_table_row()."\n".
 5238:               &Apache::loncommon::start_data_table_row()."\n".
 5239:               '<td colspan="2">'."\n".
 5240:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5241:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 5242:               '</td>'."\n".
 5243:               &Apache::loncommon::end_data_table_row()."\n".
 5244:               &Apache::loncommon::end_data_table()."\n".
 5245:               '</form><br />');
 5246:     return;
 5247: }
 5248: 
 5249: =pod
 5250: 
 5251: =item get_scantron_config
 5252: 
 5253:    Parse and return the scantron configuration line selected as a
 5254:    hash of configuration file fields.
 5255: 
 5256:  Arguments:
 5257:     which - the name of the configuration to parse from the file.
 5258: 
 5259: 
 5260:  Returns:
 5261:             If the named configuration is not in the file, an empty
 5262:             hash is returned.
 5263:     a hash with the fields
 5264:       name         - internal name for the this configuration setup
 5265:       description  - text to display to operator that describes this config
 5266:       CODElocation - if 0 or the string 'none'
 5267:                           - no CODE exists for this config
 5268:                      if -1 || the string 'letter'
 5269:                           - a CODE exists for this config and is
 5270:                             a string of letters
 5271:                      Unsupported value (but planned for future support)
 5272:                           if a positive integer
 5273:                                - The CODE exists as the first n items from
 5274:                                  the question section of the form
 5275:                           if the string 'number'
 5276:                                - The CODE exists for this config and is
 5277:                                  a string of numbers
 5278:       CODEstart   - (only matter if a CODE exists) column in the line where
 5279:                      the CODE starts
 5280:       CODElength  - length of the CODE
 5281:       IDstart     - column where the student/employee ID starts
 5282:       IDlength    - length of the student/employee ID info
 5283:       Qstart      - column where the information from the bubbled
 5284:                     'questions' start
 5285:       Qlength     - number of columns comprising a single bubble line from
 5286:                     the sheet. (usually either 1 or 10)
 5287:       Qon         - either a single character representing the character used
 5288:                     to signal a bubble was chosen in the positional setup, or
 5289:                     the string 'letter' if the letter of the chosen bubble is
 5290:                     in the final, or 'number' if a number representing the
 5291:                     chosen bubble is in the file (1->A 0->J)
 5292:       Qoff        - the character used to represent that a bubble was
 5293:                     left blank
 5294:       PaperID     - if the scanning process generates a unique number for each
 5295:                     sheet scanned the column that this ID number starts in
 5296:       PaperIDlength - number of columns that comprise the unique ID number
 5297:                       for the sheet of paper
 5298:       FirstName   - column that the first name starts in
 5299:       FirstNameLength - number of columns that the first name spans
 5300:  
 5301:       LastName    - column that the last name starts in
 5302:       LastNameLength - number of columns that the last name spans
 5303: 
 5304: =cut
 5305: 
 5306: sub get_scantron_config {
 5307:     my ($which) = @_;
 5308:     my @lines = &get_scantronformat_file();
 5309:     my %config;
 5310:     #FIXME probably should move to XML it has already gotten a bit much now
 5311:     foreach my $line (@lines) {
 5312: 	my ($name,$descrip)=split(/:/,$line);
 5313: 	if ($name ne $which ) { next; }
 5314: 	chomp($line);
 5315: 	my @config=split(/:/,$line);
 5316: 	$config{'name'}=$config[0];
 5317: 	$config{'description'}=$config[1];
 5318: 	$config{'CODElocation'}=$config[2];
 5319: 	$config{'CODEstart'}=$config[3];
 5320: 	$config{'CODElength'}=$config[4];
 5321: 	$config{'IDstart'}=$config[5];
 5322: 	$config{'IDlength'}=$config[6];
 5323: 	$config{'Qstart'}=$config[7];
 5324:  	$config{'Qlength'}=$config[8];
 5325: 	$config{'Qoff'}=$config[9];
 5326: 	$config{'Qon'}=$config[10];
 5327: 	$config{'PaperID'}=$config[11];
 5328: 	$config{'PaperIDlength'}=$config[12];
 5329: 	$config{'FirstName'}=$config[13];
 5330: 	$config{'FirstNamelength'}=$config[14];
 5331: 	$config{'LastName'}=$config[15];
 5332: 	$config{'LastNamelength'}=$config[16];
 5333: 	last;
 5334:     }
 5335:     return %config;
 5336: }
 5337: 
 5338: =pod 
 5339: 
 5340: =item username_to_idmap
 5341: 
 5342:     creates a hash keyed by student/employee ID with values of the corresponding
 5343:     student username:domain.
 5344: 
 5345:   Arguments:
 5346: 
 5347:     $classlist - reference to the class list hash. This is a hash
 5348:                  keyed by student name:domain  whose elements are references
 5349:                  to arrays containing various chunks of information
 5350:                  about the student. (See loncoursedata for more info).
 5351: 
 5352:   Returns
 5353:     %idmap - the constructed hash
 5354: 
 5355: =cut
 5356: 
 5357: sub username_to_idmap {
 5358:     my ($classlist)= @_;
 5359:     my %idmap;
 5360:     foreach my $student (keys(%$classlist)) {
 5361: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5362: 	    $student;
 5363:     }
 5364:     return %idmap;
 5365: }
 5366: 
 5367: =pod
 5368: 
 5369: =item scantron_fixup_scanline
 5370: 
 5371:    Process a requested correction to a scanline.
 5372: 
 5373:   Arguments:
 5374:     $scantron_config   - hash from &get_scantron_config()
 5375:     $scan_data         - hash of correction information 
 5376:                           (see &scantron_getfile())
 5377:     $line              - existing scanline
 5378:     $whichline         - line number of the passed in scanline
 5379:     $field             - type of change to process 
 5380:                          (either 
 5381:                           'ID'     -> correct the student/employee ID
 5382:                           'CODE'   -> correct the CODE
 5383:                           'answer' -> fixup the submitted answers)
 5384:     
 5385:    $args               - hash of additional info,
 5386:                           - 'ID' 
 5387:                                'newid' -> studentID to use in replacement
 5388:                                           of existing one
 5389:                           - 'CODE' 
 5390:                                'CODE_ignore_dup' - set to true if duplicates
 5391:                                                    should be ignored.
 5392: 	                       'CODE' - is new code or 'use_unfound'
 5393:                                         if the existing unfound code should
 5394:                                         be used as is
 5395:                           - 'answer'
 5396:                                'response' - new answer or 'none' if blank
 5397:                                'question' - the bubble line to change
 5398:                                'questionnum' - the question identifier,
 5399:                                                may include subquestion. 
 5400: 
 5401:   Returns:
 5402:     $line - the modified scanline
 5403: 
 5404:   Side effects: 
 5405:     $scan_data - may be updated
 5406: 
 5407: =cut
 5408: 
 5409: 
 5410: sub scantron_fixup_scanline {
 5411:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5412:     if ($field eq 'ID') {
 5413: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5414: 	    return ($line,1,'New value too large');
 5415: 	}
 5416: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5417: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5418: 				     $args->{'newid'});
 5419: 	}
 5420: 	substr($line,$$scantron_config{'IDstart'}-1,
 5421: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5422: 	if ($args->{'newid'}=~/^\s*$/) {
 5423: 	    &scan_data($scan_data,"$whichline.user",
 5424: 		       $args->{'username'}.':'.$args->{'domain'});
 5425: 	}
 5426:     } elsif ($field eq 'CODE') {
 5427: 	if ($args->{'CODE_ignore_dup'}) {
 5428: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5429: 	}
 5430: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5431: 	if ($args->{'CODE'} ne 'use_unfound') {
 5432: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5433: 		return ($line,1,'New CODE value too large');
 5434: 	    }
 5435: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5436: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5437: 	    }
 5438: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5439: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5440: 	}
 5441:     } elsif ($field eq 'answer') {
 5442: 	my $length=$scantron_config->{'Qlength'};
 5443: 	my $off=$scantron_config->{'Qoff'};
 5444: 	my $on=$scantron_config->{'Qon'};
 5445: 	my $answer=${off}x$length;
 5446: 	if ($args->{'response'} eq 'none') {
 5447: 	    &scan_data($scan_data,
 5448: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5449: 	} else {
 5450: 	    if ($on eq 'letter') {
 5451: 		my @alphabet=('A'..'Z');
 5452: 		$answer=$alphabet[$args->{'response'}];
 5453: 	    } elsif ($on eq 'number') {
 5454: 		$answer=$args->{'response'}+1;
 5455: 		if ($answer == 10) { $answer = '0'; }
 5456: 	    } else {
 5457: 		substr($answer,$args->{'response'},1)=$on;
 5458: 	    }
 5459: 	    &scan_data($scan_data,
 5460: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5461: 	}
 5462: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5463: 	substr($line,$where-1,$length)=$answer;
 5464:     }
 5465:     return $line;
 5466: }
 5467: 
 5468: =pod
 5469: 
 5470: =item scan_data
 5471: 
 5472:     Edit or look up  an item in the scan_data hash.
 5473: 
 5474:   Arguments:
 5475:     $scan_data  - The hash (see scantron_getfile)
 5476:     $key        - shorthand of the key to edit (actual key is
 5477:                   scantronfilename_key).
 5478:     $data        - New value of the hash entry.
 5479:     $delete      - If true, the entry is removed from the hash.
 5480: 
 5481:   Returns:
 5482:     The new value of the hash table field (undefined if deleted).
 5483: 
 5484: =cut
 5485: 
 5486: 
 5487: sub scan_data {
 5488:     my ($scan_data,$key,$value,$delete)=@_;
 5489:     my $filename=$env{'form.scantron_selectfile'};
 5490:     if (defined($value)) {
 5491: 	$scan_data->{$filename.'_'.$key} = $value;
 5492:     }
 5493:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5494:     return $scan_data->{$filename.'_'.$key};
 5495: }
 5496: 
 5497: # ----- These first few routines are general use routines.----
 5498: 
 5499: # Return the number of occurences of a pattern in a string.
 5500: 
 5501: sub occurence_count {
 5502:     my ($string, $pattern) = @_;
 5503: 
 5504:     my @matches = ($string =~ /$pattern/g);
 5505: 
 5506:     return scalar(@matches);
 5507: }
 5508: 
 5509: 
 5510: # Take a string known to have digits and convert all the
 5511: # digits into letters in the range J,A..I.
 5512: 
 5513: sub digits_to_letters {
 5514:     my ($input) = @_;
 5515: 
 5516:     my @alphabet = ('J', 'A'..'I');
 5517: 
 5518:     my @input    = split(//, $input);
 5519:     my $output ='';
 5520:     for (my $i = 0; $i < scalar(@input); $i++) {
 5521: 	if ($input[$i] =~ /\d/) {
 5522: 	    $output .= $alphabet[$input[$i]];
 5523: 	} else {
 5524: 	    $output .= $input[$i];
 5525: 	}
 5526:     }
 5527:     return $output;
 5528: }
 5529: 
 5530: =pod 
 5531: 
 5532: =item scantron_parse_scanline
 5533: 
 5534:   Decodes a scanline from the selected scantron file
 5535: 
 5536:  Arguments:
 5537:     line             - The text of the scantron file line to process
 5538:     whichline        - Line number
 5539:     scantron_config  - Hash describing the format of the scantron lines.
 5540:     scan_data        - Hash of extra information about the scanline
 5541:                        (see scantron_getfile for more information)
 5542:     just_header      - True if should not process question answers but only
 5543:                        the stuff to the left of the answers.
 5544:  Returns:
 5545:    Hash containing the result of parsing the scanline
 5546: 
 5547:    Keys are all proceeded by the string 'scantron.'
 5548: 
 5549:        CODE    - the CODE in use for this scanline
 5550:        useCODE - 1 if the CODE is invalid but it usage has been forced
 5551:                  by the operator
 5552:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 5553:                             CODEs were selected, but the usage has been
 5554:                             forced by the operator
 5555:        ID  - student/employee ID
 5556:        PaperID - if used, the ID number printed on the sheet when the 
 5557:                  paper was scanned
 5558:        FirstName - first name from the sheet
 5559:        LastName  - last name from the sheet
 5560: 
 5561:      if just_header was not true these key may also exist
 5562: 
 5563:        missingerror - a list of bubble ranges that are considered to be answers
 5564:                       to a single question that don't have any bubbles filled in.
 5565:                       Of the form questionnumber:firstbubblenumber:count.
 5566:        doubleerror  - a list of bubble ranges that are considered to be answers
 5567:                       to a single question that have more than one bubble filled in.
 5568:                       Of the form questionnumber::firstbubblenumber:count
 5569:    
 5570:                 In the above, count is the number of bubble responses in the
 5571:                 input line needed to represent the possible answers to the question.
 5572:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 5573:                 per line would have count = 2.
 5574: 
 5575:        maxquest     - the number of the last bubble line that was parsed
 5576: 
 5577:        (<number> starts at 1)
 5578:        <number>.answer - zero or more letters representing the selected
 5579:                          letters from the scanline for the bubble line 
 5580:                          <number>.
 5581:                          if blank there was either no bubble or there where
 5582:                          multiple bubbles, (consult the keys missingerror and
 5583:                          doubleerror if this is an error condition)
 5584: 
 5585: =cut
 5586: 
 5587: sub scantron_parse_scanline {
 5588:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
 5589: 
 5590:     my %record;
 5591:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 5592:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 5593:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
 5594:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 5595: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 5596: 	if ($$scantron_config{'CODElocation'} < 0 ||
 5597: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 5598: 	    $$scantron_config{'CODElocation'} eq 'number') {
 5599: 	    $record{'scantron.CODE'}=substr($data,
 5600: 					    $$scantron_config{'CODEstart'}-1,
 5601: 					    $$scantron_config{'CODElength'});
 5602: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 5603: 		$record{'scantron.useCODE'}=1;
 5604: 	    }
 5605: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 5606: 		$record{'scantron.CODE_ignore_dup'}=1;
 5607: 	    }
 5608: 	} else {
 5609: 	    #FIXME interpret first N questions
 5610: 	}
 5611:     }
 5612:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 5613: 				  $$scantron_config{'IDlength'});
 5614:     $record{'scantron.PaperID'}=
 5615: 	substr($data,$$scantron_config{'PaperID'}-1,
 5616: 	       $$scantron_config{'PaperIDlength'});
 5617:     $record{'scantron.FirstName'}=
 5618: 	substr($data,$$scantron_config{'FirstName'}-1,
 5619: 	       $$scantron_config{'FirstNamelength'});
 5620:     $record{'scantron.LastName'}=
 5621: 	substr($data,$$scantron_config{'LastName'}-1,
 5622: 	       $$scantron_config{'LastNamelength'});
 5623:     if ($just_header) { return \%record; }
 5624: 
 5625:     my @alphabet=('A'..'Z');
 5626:     my $questnum=0;
 5627:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 5628: 
 5629:     chomp($questions);		# Get rid of any trailing \n.
 5630:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 5631:     while (length($questions)) {
 5632: 	my $answers_needed = $bubble_lines_per_response{$questnum};
 5633:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 5634:                              || 1;
 5635:         $questnum++;
 5636:         my $quest_id = $questnum;
 5637:         my $currentquest = substr($questions,0,$answer_length);
 5638:         $questions       = substr($questions,$answer_length);
 5639:         if (length($currentquest) < $answer_length) { next; }
 5640: 
 5641:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
 5642:             my $subquestnum = 1;
 5643:             my $subquestions = $currentquest;
 5644:             my @subanswers_needed = 
 5645:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
 5646:             foreach my $subans (@subanswers_needed) {
 5647:                 my $subans_length =
 5648:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 5649:                 my $currsubquest = substr($subquestions,0,$subans_length);
 5650:                 $subquestions   = substr($subquestions,$subans_length);
 5651:                 $quest_id = "$questnum.$subquestnum";
 5652:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 5653:                     ($$scantron_config{'Qon'} eq 'number')) {
 5654:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 5655:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 5656:                         \@alphabet,\%record,$scantron_config,$scan_data);
 5657:                 } else {
 5658:                     $ansnum = &scantron_validator_positional($ansnum,
 5659:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
 5660:                 }
 5661:                 $subquestnum ++;
 5662:             }
 5663:         } else {
 5664:             if (($$scantron_config{'Qon'} eq 'letter') ||
 5665:                 ($$scantron_config{'Qon'} eq 'number')) {
 5666:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 5667:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5668:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5669:             } else {
 5670:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 5671:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5672:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5673:             }
 5674:         }
 5675:     }
 5676:     $record{'scantron.maxquest'}=$questnum;
 5677:     return \%record;
 5678: }
 5679: 
 5680: sub scantron_validator_lettnum {
 5681:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 5682:         $alphabet,$record,$scantron_config,$scan_data) = @_;
 5683: 
 5684:     # Qon 'letter' implies for each slot in currquest we have:
 5685:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 5686:     #    about anything else (esp. a value of Qoff) for missing
 5687:     #    bubbles.
 5688:     #
 5689:     # Qon 'number' implies each slot gives a digit that indexes the
 5690:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 5691:     #    and * or ? for double bubbles on a single line.
 5692:     #
 5693: 
 5694:     my $matchon;
 5695:     if ($$scantron_config{'Qon'} eq 'letter') {
 5696:         $matchon = '[A-Z]';
 5697:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 5698:         $matchon = '\d';
 5699:     }
 5700:     my $occurrences = 0;
 5701:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5702:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5703:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5704:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5705:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5706:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5707:         my @singlelines = split('',$currquest);
 5708:         foreach my $entry (@singlelines) {
 5709:             $occurrences = &occurence_count($entry,$matchon);
 5710:             if ($occurrences > 1) {
 5711:                 last;
 5712:             }
 5713:         } 
 5714:     } else {
 5715:         $occurrences = &occurence_count($currquest,$matchon); 
 5716:     }
 5717:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 5718:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5719:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5720:             my $bubble = substr($currquest,$ans,1);
 5721:             if ($bubble =~ /$matchon/ ) {
 5722:                 if ($$scantron_config{'Qon'} eq 'number') {
 5723:                     if ($bubble == 0) {
 5724:                         $bubble = 10; 
 5725:                     }
 5726:                     $record->{"scantron.$ansnum.answer"} = 
 5727:                         $alphabet->[$bubble-1];
 5728:                 } else {
 5729:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 5730:                 }
 5731:             } else {
 5732:                 $record->{"scantron.$ansnum.answer"}='';
 5733:             }
 5734:             $ansnum++;
 5735:         }
 5736:     } elsif (!defined($currquest)
 5737:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 5738:             || (&occurence_count($currquest,$matchon) == 0)) {
 5739:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5740:             $record->{"scantron.$ansnum.answer"}='';
 5741:             $ansnum++;
 5742:         }
 5743:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5744:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 5745:         }
 5746:     } else {
 5747:         if ($$scantron_config{'Qon'} eq 'number') {
 5748:             $currquest = &digits_to_letters($currquest);            
 5749:         }
 5750:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5751:             my $bubble = substr($currquest,$ans,1);
 5752:             $record->{"scantron.$ansnum.answer"} = $bubble;
 5753:             $ansnum++;
 5754:         }
 5755:     }
 5756:     return $ansnum;
 5757: }
 5758: 
 5759: sub scantron_validator_positional {
 5760:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 5761:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
 5762: 
 5763:     # Otherwise there's a positional notation;
 5764:     # each bubble line requires Qlength items, and there are filled in
 5765:     # bubbles for each case where there 'Qon' characters.
 5766:     #
 5767: 
 5768:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 5769: 
 5770:     # If the split only gives us one element.. the full length of the
 5771:     # answer string, no bubbles are filled in:
 5772: 
 5773:     if ($answers_needed eq '') {
 5774:         return;
 5775:     }
 5776: 
 5777:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 5778:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5779:             $record->{"scantron.$ansnum.answer"}='';
 5780:             $ansnum++;
 5781:         }
 5782:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5783:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 5784:         }
 5785:     } elsif (scalar(@array) == 2) {
 5786:         my $location = length($array[0]);
 5787:         my $line_num = int($location / $$scantron_config{'Qlength'});
 5788:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 5789:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5790:             if ($ans eq $line_num) {
 5791:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 5792:             } else {
 5793:                 $record->{"scantron.$ansnum.answer"} = ' ';
 5794:             }
 5795:             $ansnum++;
 5796:          }
 5797:     } else {
 5798:         #  If there's more than one instance of a bubble character
 5799:         #  That's a double bubble; with positional notation we can
 5800:         #  record all the bubbles filled in as well as the
 5801:         #  fact this response consists of multiple bubbles.
 5802:         #
 5803:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5804:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5805:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5806:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5807:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5808:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5809:             my $doubleerror = 0;
 5810:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 5811:                    (!$doubleerror)) {
 5812:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 5813:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 5814:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 5815:                if (length(@currarray) > 2) {
 5816:                    $doubleerror = 1;
 5817:                } 
 5818:             }
 5819:             if ($doubleerror) {
 5820:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5821:             }
 5822:         } else {
 5823:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5824:         }
 5825:         my $item = $ansnum;
 5826:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5827:             $record->{"scantron.$item.answer"} = '';
 5828:             $item ++;
 5829:         }
 5830: 
 5831:         my @ans=@array;
 5832:         my $i=0;
 5833:         my $increment = 0;
 5834:         while ($#ans) {
 5835:             $i+=length($ans[0]) + $increment;
 5836:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 5837:             my $bubble = $i%$$scantron_config{'Qlength'};
 5838:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 5839:             shift(@ans);
 5840:             $increment = 1;
 5841:         }
 5842:         $ansnum += $answers_needed;
 5843:     }
 5844:     return $ansnum;
 5845: }
 5846: 
 5847: =pod
 5848: 
 5849: =item scantron_add_delay
 5850: 
 5851:    Adds an error message that occurred during the grading phase to a
 5852:    queue of messages to be shown after grading pass is complete
 5853: 
 5854:  Arguments:
 5855:    $delayqueue  - arrary ref of hash ref of error messages
 5856:    $scanline    - the scanline that caused the error
 5857:    $errormesage - the error message
 5858:    $errorcode   - a numeric code for the error
 5859: 
 5860:  Side Effects:
 5861:    updates the $delayqueue to have a new hash ref of the error
 5862: 
 5863: =cut
 5864: 
 5865: sub scantron_add_delay {
 5866:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 5867:     push(@$delayqueue,
 5868: 	 {'line' => $scanline, 'emsg' => $errormessage,
 5869: 	  'ecode' => $errorcode }
 5870: 	 );
 5871: }
 5872: 
 5873: =pod
 5874: 
 5875: =item scantron_find_student
 5876: 
 5877:    Finds the username for the current scanline
 5878: 
 5879:   Arguments:
 5880:    $scantron_record - hash result from scantron_parse_scanline
 5881:    $scan_data       - hash of correction information 
 5882:                       (see &scantron_getfile() form more information)
 5883:    $idmap           - hash from &username_to_idmap()
 5884:    $line            - number of current scanline
 5885:  
 5886:   Returns:
 5887:    Either 'username:domain' or undef if unknown
 5888: 
 5889: =cut
 5890: 
 5891: sub scantron_find_student {
 5892:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 5893:     my $scanID=$$scantron_record{'scantron.ID'};
 5894:     if ($scanID =~ /^\s*$/) {
 5895:  	return &scan_data($scan_data,"$line.user");
 5896:     }
 5897:     foreach my $id (keys(%$idmap)) {
 5898:  	if (lc($id) eq lc($scanID)) {
 5899:  	    return $$idmap{$id};
 5900:  	}
 5901:     }
 5902:     return undef;
 5903: }
 5904: 
 5905: =pod
 5906: 
 5907: =item scantron_filter
 5908: 
 5909:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 5910:    hidden resources was selected
 5911: 
 5912: =cut
 5913: 
 5914: sub scantron_filter {
 5915:     my ($curres)=@_;
 5916: 
 5917:     if (ref($curres) && $curres->is_problem()) {
 5918: 	# if the user has asked to not have either hidden
 5919: 	# or 'randomout' controlled resources to be graded
 5920: 	# don't include them
 5921: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 5922: 	    && $curres->randomout) {
 5923: 	    return 0;
 5924: 	}
 5925: 	return 1;
 5926:     }
 5927:     return 0;
 5928: }
 5929: 
 5930: =pod
 5931: 
 5932: =item scantron_process_corrections
 5933: 
 5934:    Gets correction information out of submitted form data and corrects
 5935:    the scanline
 5936: 
 5937: =cut
 5938: 
 5939: sub scantron_process_corrections {
 5940:     my ($r) = @_;
 5941:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 5942:     my ($scanlines,$scan_data)=&scantron_getfile();
 5943:     my $classlist=&Apache::loncoursedata::get_classlist();
 5944:     my $which=$env{'form.scantron_line'};
 5945:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 5946:     my ($skip,$err,$errmsg);
 5947:     if ($env{'form.scantron_skip_record'}) {
 5948: 	$skip=1;
 5949:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 5950: 	my $newstudent=$env{'form.scantron_username'}.':'.
 5951: 	    $env{'form.scantron_domain'};
 5952: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 5953: 	($line,$err,$errmsg)=
 5954: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 5955: 				     'ID',{'newid'=>$newid,
 5956: 				    'username'=>$env{'form.scantron_username'},
 5957: 				    'domain'=>$env{'form.scantron_domain'}});
 5958:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 5959: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 5960: 	my $newCODE;
 5961: 	my %args;
 5962: 	if      ($resolution eq 'use_unfound') {
 5963: 	    $newCODE='use_unfound';
 5964: 	} elsif ($resolution eq 'use_found') {
 5965: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 5966: 	} elsif ($resolution eq 'use_typed') {
 5967: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 5968: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 5969: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 5970: 	}
 5971: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 5972: 	    $args{'CODE_ignore_dup'}=1;
 5973: 	}
 5974: 	$args{'CODE'}=$newCODE;
 5975: 	($line,$err,$errmsg)=
 5976: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 5977: 				     'CODE',\%args);
 5978:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 5979: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 5980: 	    ($line,$err,$errmsg)=
 5981: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 5982: 					 $which,'answer',
 5983: 					 { 'question'=>$question,
 5984: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 5985:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 5986: 	    if ($err) { last; }
 5987: 	}
 5988:     }
 5989:     if ($err) {
 5990: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
 5991:     } else {
 5992: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 5993: 	&scantron_putfile($scanlines,$scan_data);
 5994:     }
 5995: }
 5996: 
 5997: =pod
 5998: 
 5999: =item reset_skipping_status
 6000: 
 6001:    Forgets the current set of remember skipped scanlines (and thus
 6002:    reverts back to considering all lines in the
 6003:    scantron_skipped_<filename> file)
 6004: 
 6005: =cut
 6006: 
 6007: sub reset_skipping_status {
 6008:     my ($scanlines,$scan_data)=&scantron_getfile();
 6009:     &scan_data($scan_data,'remember_skipping',undef,1);
 6010:     &scantron_putfile(undef,$scan_data);
 6011: }
 6012: 
 6013: =pod
 6014: 
 6015: =item start_skipping
 6016: 
 6017:    Marks a scanline to be skipped. 
 6018: 
 6019: =cut
 6020: 
 6021: sub start_skipping {
 6022:     my ($scan_data,$i)=@_;
 6023:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6024:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6025: 	$remembered{$i}=2;
 6026:     } else {
 6027: 	$remembered{$i}=1;
 6028:     }
 6029:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6030: }
 6031: 
 6032: =pod
 6033: 
 6034: =item should_be_skipped
 6035: 
 6036:    Checks whether a scanline should be skipped.
 6037: 
 6038: =cut
 6039: 
 6040: sub should_be_skipped {
 6041:     my ($scanlines,$scan_data,$i)=@_;
 6042:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6043: 	# not redoing old skips
 6044: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6045: 	return 0;
 6046:     }
 6047:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6048: 
 6049:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6050: 	return 0;
 6051:     }
 6052:     return 1;
 6053: }
 6054: 
 6055: =pod
 6056: 
 6057: =item remember_current_skipped
 6058: 
 6059:    Discovers what scanlines are in the scantron_skipped_<filename>
 6060:    file and remembers them into scan_data for later use.
 6061: 
 6062: =cut
 6063: 
 6064: sub remember_current_skipped {
 6065:     my ($scanlines,$scan_data)=&scantron_getfile();
 6066:     my %to_remember;
 6067:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6068: 	if ($scanlines->{'skipped'}[$i]) {
 6069: 	    $to_remember{$i}=1;
 6070: 	}
 6071:     }
 6072: 
 6073:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6074:     &scantron_putfile(undef,$scan_data);
 6075: }
 6076: 
 6077: =pod
 6078: 
 6079: =item check_for_error
 6080: 
 6081:     Checks if there was an error when attempting to remove a specific
 6082:     scantron_.. bubble sheet data file. Prints out an error if
 6083:     something went wrong.
 6084: 
 6085: =cut
 6086: 
 6087: sub check_for_error {
 6088:     my ($r,$result)=@_;
 6089:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6090: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6091:     }
 6092: }
 6093: 
 6094: =pod
 6095: 
 6096: =item scantron_warning_screen
 6097: 
 6098:    Interstitial screen to make sure the operator has selected the
 6099:    correct options before we start the validation phase.
 6100: 
 6101: =cut
 6102: 
 6103: sub scantron_warning_screen {
 6104:     my ($button_text)=@_;
 6105:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6106:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6107:     my $CODElist;
 6108:     if ($scantron_config{'CODElocation'} &&
 6109: 	$scantron_config{'CODEstart'} &&
 6110: 	$scantron_config{'CODElength'}) {
 6111: 	$CODElist=$env{'form.scantron_CODElist'};
 6112: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
 6113: 	$CODElist=
 6114: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6115: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6116:     }
 6117:     return ('
 6118: <p>
 6119: <span class="LC_warning">
 6120: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
 6121: </p>
 6122: <table>
 6123: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6124: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6125: '.$CODElist.'
 6126: </table>
 6127: <br />
 6128: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
 6129: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
 6130: 
 6131: <br />
 6132: ');
 6133: }
 6134: 
 6135: =pod
 6136: 
 6137: =item scantron_do_warning
 6138: 
 6139:    Check if the operator has picked something for all required
 6140:    fields. Error out if something is missing.
 6141: 
 6142: =cut
 6143: 
 6144: sub scantron_do_warning {
 6145:     my ($r,$symb)=@_;
 6146:     if (!$symb) {return '';}
 6147:     my $default_form_data=&defaultFormData($symb);
 6148:     $r->print(&scantron_form_start().$default_form_data);
 6149:     if ( $env{'form.selectpage'} eq '' ||
 6150: 	 $env{'form.scantron_selectfile'} eq '' ||
 6151: 	 $env{'form.scantron_format'} eq '' ) {
 6152: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
 6153: 	if ( $env{'form.selectpage'} eq '') {
 6154: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6155: 	} 
 6156: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6157: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a file that contains the student\'s response data.').'</span></p>');
 6158: 	} 
 6159: 	if ( $env{'form.scantron_format'} eq '') {
 6160: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a the format of the student\'s response data.').'</span></p>');
 6161: 	} 
 6162:     } else {
 6163: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
 6164: 	$r->print('
 6165: '.$warning.'
 6166: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6167: <input type="hidden" name="command" value="scantron_validate" />
 6168: ');
 6169:     }
 6170:     $r->print("</form><br />");
 6171:     return '';
 6172: }
 6173: 
 6174: =pod
 6175: 
 6176: =item scantron_form_start
 6177: 
 6178:     html hidden input for remembering all selected grading options
 6179: 
 6180: =cut
 6181: 
 6182: sub scantron_form_start {
 6183:     my ($max_bubble)=@_;
 6184:     my $result= <<SCANTRONFORM;
 6185: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6186:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6187:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6188:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6189:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6190:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6191:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6192:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6193:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6194:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6195: SCANTRONFORM
 6196: 
 6197:   my $line = 0;
 6198:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6199:        my $chunk =
 6200: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6201:        $chunk .=
 6202: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6203:        $chunk .= 
 6204:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6205:        $chunk .=
 6206:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6207:        $result .= $chunk;
 6208:        $line++;
 6209:    }
 6210:     return $result;
 6211: }
 6212: 
 6213: =pod
 6214: 
 6215: =item scantron_validate_file
 6216: 
 6217:     Dispatch routine for doing validation of a bubble sheet data file.
 6218: 
 6219:     Also processes any necessary information resets that need to
 6220:     occur before validation begins (ignore previous corrections,
 6221:     restarting the skipped records processing)
 6222: 
 6223: =cut
 6224: 
 6225: sub scantron_validate_file {
 6226:     my ($r,$symb) = @_;
 6227:     if (!$symb) {return '';}
 6228:     my $default_form_data=&defaultFormData($symb);
 6229:     
 6230:     # do the detection of only doing skipped records first befroe we delete
 6231:     # them when doing the corrections reset
 6232:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6233: 	&reset_skipping_status();
 6234:     }
 6235:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6236: 	&remember_current_skipped();
 6237: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6238:     }
 6239: 
 6240:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6241: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6242: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6243: 	&check_for_error($r,&scantron_remove_scan_data());
 6244: 	$env{'form.scantron_options_ignore'}='done';
 6245:     }
 6246: 
 6247:     if ($env{'form.scantron_corrections'}) {
 6248: 	&scantron_process_corrections($r);
 6249:     }
 6250:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6251:     #get the student pick code ready
 6252:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6253:     my $nav_error;
 6254:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
 6255:     if ($nav_error) {
 6256:         $r->print(&navmap_errormsg());
 6257:         return '';
 6258:     }
 6259:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6260:     $r->print($result);
 6261:     
 6262:     my @validate_phases=( 'sequence',
 6263: 			  'ID',
 6264: 			  'CODE',
 6265: 			  'doublebubble',
 6266: 			  'missingbubbles');
 6267:     if (!$env{'form.validatepass'}) {
 6268: 	$env{'form.validatepass'} = 0;
 6269:     }
 6270:     my $currentphase=$env{'form.validatepass'};
 6271: 
 6272: 
 6273:     my $stop=0;
 6274:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6275: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6276: 	$r->rflush();
 6277: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6278: 	{
 6279: 	    no strict 'refs';
 6280: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6281: 	}
 6282:     }
 6283:     if (!$stop) {
 6284: 	my $warning=&scantron_warning_screen('Start Grading');
 6285: 	$r->print(&mt('Validation process complete.').'<br />'.
 6286:                   $warning.
 6287:                   &mt('Perform verification for each student after storage of submissions?').
 6288:                   '&nbsp;<span class="LC_nobreak"><label>'.
 6289:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 6290:                   ('&nbsp;'x3).'<label>'.
 6291:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 6292:                   '</label></span><br />'.
 6293:                   &mt('Grading will take longer if you use verification.').'<br />'.
 6294:                   &mt("Alternatively, the 'Review bubblesheet data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
 6295:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 6296:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 6297:     } else {
 6298: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6299: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6300:     }
 6301:     if ($stop) {
 6302: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6303: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 6304: 	    $r->print(' '.&mt('this error').' <br />');
 6305: 
 6306: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
 6307: 	} else {
 6308:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6309: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 6310:             } else {
 6311:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 6312:             }
 6313: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6314: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6315: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6316: 	}
 6317:     }
 6318:     $r->print(" </form><br />");
 6319:     return '';
 6320: }
 6321: 
 6322: 
 6323: =pod
 6324: 
 6325: =item scantron_remove_file
 6326: 
 6327:    Removes the requested bubble sheet data file, makes sure that
 6328:    scantron_original_<filename> is never removed
 6329: 
 6330: 
 6331: =cut
 6332: 
 6333: sub scantron_remove_file {
 6334:     my ($which)=@_;
 6335:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6336:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6337:     my $file='scantron_';
 6338:     if ($which eq 'corrected' || $which eq 'skipped') {
 6339: 	$file.=$which.'_';
 6340:     } else {
 6341: 	return 'refused';
 6342:     }
 6343:     $file.=$env{'form.scantron_selectfile'};
 6344:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6345: }
 6346: 
 6347: 
 6348: =pod
 6349: 
 6350: =item scantron_remove_scan_data
 6351: 
 6352:    Removes all scan_data correction for the requested bubble sheet
 6353:    data file.  (In the case that both the are doing skipped records we need
 6354:    to remember the old skipped lines for the time being so that element
 6355:    persists for a while.)
 6356: 
 6357: =cut
 6358: 
 6359: sub scantron_remove_scan_data {
 6360:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6361:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6362:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6363:     my @todelete;
 6364:     my $filename=$env{'form.scantron_selectfile'};
 6365:     foreach my $key (@keys) {
 6366: 	if ($key=~/^\Q$filename\E_/) {
 6367: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6368: 		$key=~/remember_skipping/) {
 6369: 		next;
 6370: 	    }
 6371: 	    push(@todelete,$key);
 6372: 	}
 6373:     }
 6374:     my $result;
 6375:     if (@todelete) {
 6376: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6377: 				       \@todelete,$cdom,$cname);
 6378:     } else {
 6379: 	$result = 'ok';
 6380:     }
 6381:     return $result;
 6382: }
 6383: 
 6384: 
 6385: =pod
 6386: 
 6387: =item scantron_getfile
 6388: 
 6389:     Fetches the requested bubble sheet data file (all 3 versions), and
 6390:     the scan_data hash
 6391:   
 6392:   Arguments:
 6393:     None
 6394: 
 6395:   Returns:
 6396:     2 hash references
 6397: 
 6398:      - first one has 
 6399:          orig      -
 6400:          corrected -
 6401:          skipped   -  each of which points to an array ref of the specified
 6402:                       file broken up into individual lines
 6403:          count     - number of scanlines
 6404:  
 6405:      - second is the scan_data hash possible keys are
 6406:        ($number refers to scanline numbered $number and thus the key affects
 6407:         only that scanline
 6408:         $bubline refers to the specific bubble line element and the aspects
 6409:         refers to that specific bubble line element)
 6410: 
 6411:        $number.user - username:domain to use
 6412:        $number.CODE_ignore_dup 
 6413:                     - ignore the duplicate CODE error 
 6414:        $number.useCODE
 6415:                     - use the CODE in the scanline as is
 6416:        $number.no_bubble.$bubline
 6417:                     - it is valid that there is no bubbled in bubble
 6418:                       at $number $bubline
 6419:        remember_skipping
 6420:                     - a frozen hash containing keys of $number and values
 6421:                       of either 
 6422:                         1 - we are on a 'do skipped records pass' and plan
 6423:                             on processing this line
 6424:                         2 - we are on a 'do skipped records pass' and this
 6425:                             scanline has been marked to skip yet again
 6426: 
 6427: =cut
 6428: 
 6429: sub scantron_getfile {
 6430:     #FIXME really would prefer a scantron directory
 6431:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6432:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6433:     my $lines;
 6434:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6435: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 6436:     my %scanlines;
 6437:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 6438:     my $temp=$scanlines{'orig'};
 6439:     $scanlines{'count'}=$#$temp;
 6440: 
 6441:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6442: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 6443:     if ($lines eq '-1') {
 6444: 	$scanlines{'corrected'}=[];
 6445:     } else {
 6446: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 6447:     }
 6448:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6449: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 6450:     if ($lines eq '-1') {
 6451: 	$scanlines{'skipped'}=[];
 6452:     } else {
 6453: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 6454:     }
 6455:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 6456:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 6457:     my %scan_data = @tmp;
 6458:     return (\%scanlines,\%scan_data);
 6459: }
 6460: 
 6461: =pod
 6462: 
 6463: =item lonnet_putfile
 6464: 
 6465:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 6466: 
 6467:  Arguments:
 6468:    $contents - data to store
 6469:    $filename - filename to store $contents into
 6470: 
 6471:  Returns:
 6472:    result value from &Apache::lonnet::finishuserfileupload
 6473: 
 6474: =cut
 6475: 
 6476: sub lonnet_putfile {
 6477:     my ($contents,$filename)=@_;
 6478:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6479:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6480:     $env{'form.sillywaytopassafilearound'}=$contents;
 6481:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 6482: 
 6483: }
 6484: 
 6485: =pod
 6486: 
 6487: =item scantron_putfile
 6488: 
 6489:     Stores the current version of the bubble sheet data files, and the
 6490:     scan_data hash. (Does not modify the original version only the
 6491:     corrected and skipped versions.
 6492: 
 6493:  Arguments:
 6494:     $scanlines - hash ref that looks like the first return value from
 6495:                  &scantron_getfile()
 6496:     $scan_data - hash ref that looks like the second return value from
 6497:                  &scantron_getfile()
 6498: 
 6499: =cut
 6500: 
 6501: sub scantron_putfile {
 6502:     my ($scanlines,$scan_data) = @_;
 6503:     #FIXME really would prefer a scantron directory
 6504:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6505:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6506:     if ($scanlines) {
 6507: 	my $prefix='scantron_';
 6508: # no need to update orig, shouldn't change
 6509: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 6510: #		    $env{'form.scantron_selectfile'});
 6511: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 6512: 			$prefix.'corrected_'.
 6513: 			$env{'form.scantron_selectfile'});
 6514: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 6515: 			$prefix.'skipped_'.
 6516: 			$env{'form.scantron_selectfile'});
 6517:     }
 6518:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 6519: }
 6520: 
 6521: =pod
 6522: 
 6523: =item scantron_get_line
 6524: 
 6525:    Returns the correct version of the scanline
 6526: 
 6527:  Arguments:
 6528:     $scanlines - hash ref that looks like the first return value from
 6529:                  &scantron_getfile()
 6530:     $scan_data - hash ref that looks like the second return value from
 6531:                  &scantron_getfile()
 6532:     $i         - number of the requested line (starts at 0)
 6533: 
 6534:  Returns:
 6535:    A scanline, (either the original or the corrected one if it
 6536:    exists), or undef if the requested scanline should be
 6537:    skipped. (Either because it's an skipped scanline, or it's an
 6538:    unskipped scanline and we are not doing a 'do skipped scanlines'
 6539:    pass.
 6540: 
 6541: =cut
 6542: 
 6543: sub scantron_get_line {
 6544:     my ($scanlines,$scan_data,$i)=@_;
 6545:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 6546:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 6547:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 6548:     return $scanlines->{'orig'}[$i]; 
 6549: }
 6550: 
 6551: =pod
 6552: 
 6553: =item scantron_todo_count
 6554: 
 6555:     Counts the number of scanlines that need processing.
 6556: 
 6557:  Arguments:
 6558:     $scanlines - hash ref that looks like the first return value from
 6559:                  &scantron_getfile()
 6560:     $scan_data - hash ref that looks like the second return value from
 6561:                  &scantron_getfile()
 6562: 
 6563:  Returns:
 6564:     $count - number of scanlines to process
 6565: 
 6566: =cut
 6567: 
 6568: sub get_todo_count {
 6569:     my ($scanlines,$scan_data)=@_;
 6570:     my $count=0;
 6571:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6572: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6573: 	if ($line=~/^[\s\cz]*$/) { next; }
 6574: 	$count++;
 6575:     }
 6576:     return $count;
 6577: }
 6578: 
 6579: =pod
 6580: 
 6581: =item scantron_put_line
 6582: 
 6583:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
 6584:     data file.
 6585: 
 6586:  Arguments:
 6587:     $scanlines - hash ref that looks like the first return value from
 6588:                  &scantron_getfile()
 6589:     $scan_data - hash ref that looks like the second return value from
 6590:                  &scantron_getfile()
 6591:     $i         - line number to update
 6592:     $newline   - contents of the updated scanline
 6593:     $skip      - if true make the line for skipping and update the
 6594:                  'skipped' file
 6595: 
 6596: =cut
 6597: 
 6598: sub scantron_put_line {
 6599:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 6600:     if ($skip) {
 6601: 	$scanlines->{'skipped'}[$i]=$newline;
 6602: 	&start_skipping($scan_data,$i);
 6603: 	return;
 6604:     }
 6605:     $scanlines->{'corrected'}[$i]=$newline;
 6606: }
 6607: 
 6608: =pod
 6609: 
 6610: =item scantron_clear_skip
 6611: 
 6612:    Remove a line from the 'skipped' file
 6613: 
 6614:  Arguments:
 6615:     $scanlines - hash ref that looks like the first return value from
 6616:                  &scantron_getfile()
 6617:     $scan_data - hash ref that looks like the second return value from
 6618:                  &scantron_getfile()
 6619:     $i         - line number to update
 6620: 
 6621: =cut
 6622: 
 6623: sub scantron_clear_skip {
 6624:     my ($scanlines,$scan_data,$i)=@_;
 6625:     if (exists($scanlines->{'skipped'}[$i])) {
 6626: 	undef($scanlines->{'skipped'}[$i]);
 6627: 	return 1;
 6628:     }
 6629:     return 0;
 6630: }
 6631: 
 6632: =pod
 6633: 
 6634: =item scantron_filter_not_exam
 6635: 
 6636:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 6637:    filter out resources that are not marked as 'exam' mode
 6638: 
 6639: =cut
 6640: 
 6641: sub scantron_filter_not_exam {
 6642:     my ($curres)=@_;
 6643:     
 6644:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 6645: 	# if the user has asked to not have either hidden
 6646: 	# or 'randomout' controlled resources to be graded
 6647: 	# don't include them
 6648: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6649: 	    && $curres->randomout) {
 6650: 	    return 0;
 6651: 	}
 6652: 	return 1;
 6653:     }
 6654:     return 0;
 6655: }
 6656: 
 6657: =pod
 6658: 
 6659: =item scantron_validate_sequence
 6660: 
 6661:     Validates the selected sequence, checking for resource that are
 6662:     not set to exam mode.
 6663: 
 6664: =cut
 6665: 
 6666: sub scantron_validate_sequence {
 6667:     my ($r,$currentphase) = @_;
 6668: 
 6669:     my $navmap=Apache::lonnavmaps::navmap->new();
 6670:     unless (ref($navmap)) {
 6671:         $r->print(&navmap_errormsg());
 6672:         return (1,$currentphase);
 6673:     }
 6674:     my (undef,undef,$sequence)=
 6675: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6676: 
 6677:     my $map=$navmap->getResourceByUrl($sequence);
 6678: 
 6679:     $r->print('<input type="hidden" name="validate_sequence_exam"
 6680:                                     value="ignore" />');
 6681:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 6682: 	my @resources=
 6683: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 6684: 	if (@resources) {
 6685: 	    $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>");
 6686: 	    return (1,$currentphase);
 6687: 	}
 6688:     }
 6689: 
 6690:     return (0,$currentphase+1);
 6691: }
 6692: 
 6693: 
 6694: 
 6695: sub scantron_validate_ID {
 6696:     my ($r,$currentphase) = @_;
 6697:     
 6698:     #get student info
 6699:     my $classlist=&Apache::loncoursedata::get_classlist();
 6700:     my %idmap=&username_to_idmap($classlist);
 6701: 
 6702:     #get scantron line setup
 6703:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6704:     my ($scanlines,$scan_data)=&scantron_getfile();
 6705: 
 6706:     my $nav_error;
 6707:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble_lines.. array.
 6708:     if ($nav_error) {
 6709:         $r->print(&navmap_errormsg());
 6710:         return(1,$currentphase);
 6711:     }
 6712: 
 6713:     my %found=('ids'=>{},'usernames'=>{});
 6714:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6715: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6716: 	if ($line=~/^[\s\cz]*$/) { next; }
 6717: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6718: 						 $scan_data);
 6719: 	my $id=$$scan_record{'scantron.ID'};
 6720: 	my $found;
 6721: 	foreach my $checkid (keys(%idmap)) {
 6722: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 6723: 	}
 6724: 	if ($found) {
 6725: 	    my $username=$idmap{$found};
 6726: 	    if ($found{'ids'}{$found}) {
 6727: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6728: 					 $line,'duplicateID',$found);
 6729: 		return(1,$currentphase);
 6730: 	    } elsif ($found{'usernames'}{$username}) {
 6731: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6732: 					 $line,'duplicateID',$username);
 6733: 		return(1,$currentphase);
 6734: 	    }
 6735: 	    #FIXME store away line we previously saw the ID on to use above
 6736: 	    $found{'ids'}{$found}++;
 6737: 	    $found{'usernames'}{$username}++;
 6738: 	} else {
 6739: 	    if ($id =~ /^\s*$/) {
 6740: 		my $username=&scan_data($scan_data,"$i.user");
 6741: 		if (defined($username) && $found{'usernames'}{$username}) {
 6742: 		    &scantron_get_correction($r,$i,$scan_record,
 6743: 					     \%scantron_config,
 6744: 					     $line,'duplicateID',$username);
 6745: 		    return(1,$currentphase);
 6746: 		} elsif (!defined($username)) {
 6747: 		    &scantron_get_correction($r,$i,$scan_record,
 6748: 					     \%scantron_config,
 6749: 					     $line,'incorrectID');
 6750: 		    return(1,$currentphase);
 6751: 		}
 6752: 		$found{'usernames'}{$username}++;
 6753: 	    } else {
 6754: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6755: 					 $line,'incorrectID');
 6756: 		return(1,$currentphase);
 6757: 	    }
 6758: 	}
 6759:     }
 6760: 
 6761:     return (0,$currentphase+1);
 6762: }
 6763: 
 6764: 
 6765: sub scantron_get_correction {
 6766:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
 6767: #FIXME in the case of a duplicated ID the previous line, probably need
 6768: #to show both the current line and the previous one and allow skipping
 6769: #the previous one or the current one
 6770: 
 6771:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 6772: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6773: 			    " for PaperID <tt>[_1]</tt>",
 6774: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
 6775:     } else {
 6776: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6777: 			    " in scanline [_1] <pre>[_2]</pre>",
 6778: 			    $i,$line)."</p> \n");
 6779:     }
 6780:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
 6781: 			  "The name on the paper is [_2],[_3]",
 6782: 			  $$scan_record{'scantron.ID'},
 6783: 			  $$scan_record{'scantron.LastName'},
 6784: 			  $$scan_record{'scantron.FirstName'})."</p>";
 6785: 
 6786:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 6787:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 6788:                            # Array populated for doublebubble or
 6789:     my @lines_to_correct;  # missingbubble errors to build javascript
 6790:                            # to validate radio button checking   
 6791: 
 6792:     if ($error =~ /ID$/) {
 6793: 	if ($error eq 'incorrectID') {
 6794: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
 6795: 		      "</p>\n");
 6796: 	} elsif ($error eq 'duplicateID') {
 6797: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 6798: 	}
 6799: 	$r->print($message);
 6800: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6801: 	$r->print("\n<ul><li> ");
 6802: 	#FIXME it would be nice if this sent back the user ID and
 6803: 	#could do partial userID matches
 6804: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 6805: 				       'scantron_username','scantron_domain'));
 6806: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 6807: 	$r->print("\n@".
 6808: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 6809: 
 6810: 	$r->print('</li>');
 6811:     } elsif ($error =~ /CODE$/) {
 6812: 	if ($error eq 'incorrectCODE') {
 6813: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 6814: 	} elsif ($error eq 'duplicateCODE') {
 6815: 	    $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");
 6816: 	}
 6817: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
 6818: 			    $$scan_record{'scantron.CODE'})."<br />\n");
 6819: 	$r->print($message);
 6820: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6821: 	$r->print("\n<br /> ");
 6822: 	my $i=0;
 6823: 	if ($error eq 'incorrectCODE' 
 6824: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 6825: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 6826: 	    if ($closest > 0) {
 6827: 		foreach my $testcode (@{$closest}) {
 6828: 		    my $checked='';
 6829: 		    if (!$i) { $checked=' checked="checked"'; }
 6830: 		    $r->print("
 6831:    <label>
 6832:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 6833:        ".&mt("Use the similar CODE [_1] instead.",
 6834: 	    "<b><tt>".$testcode."</tt></b>")."
 6835:     </label>
 6836:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 6837: 		    $r->print("\n<br />");
 6838: 		    $i++;
 6839: 		}
 6840: 	    }
 6841: 	}
 6842: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 6843: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 6844: 	    $r->print("
 6845:     <label>
 6846:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 6847:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
 6848: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 6849:     </label>");
 6850: 	    $r->print("\n<br />");
 6851: 	}
 6852: 
 6853: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
 6854: function change_radio(field) {
 6855:     var slct=document.scantronupload.scantron_CODE_resolution;
 6856:     var i;
 6857:     for (i=0;i<slct.length;i++) {
 6858:         if (slct[i].value==field) { slct[i].checked=true; }
 6859:     }
 6860: }
 6861: ENDSCRIPT
 6862: 	my $href="/adm/pickcode?".
 6863: 	   "form=".&escape("scantronupload").
 6864: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 6865: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 6866: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 6867: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 6868: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 6869: 	    $r->print("
 6870:     <label>
 6871:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 6872:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 6873: 	     "<a target='_blank' href='$href'>","</a>")."
 6874:     </label> 
 6875:     ".&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\')" />'));
 6876: 	    $r->print("\n<br />");
 6877: 	}
 6878: 	$r->print("
 6879:     <label>
 6880:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 6881:        ".&mt("Use [_1] as the CODE.",
 6882: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 6883: 	$r->print("\n<br /><br />");
 6884:     } elsif ($error eq 'doublebubble') {
 6885: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 6886: 
 6887: 	# The form field scantron_questions is acutally a list of line numbers.
 6888: 	# represented by this form so:
 6889: 
 6890: 	my $line_list = &questions_to_line_list($arg);
 6891: 
 6892: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6893: 		  $line_list.'" />');
 6894: 	$r->print($message);
 6895: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 6896: 	foreach my $question (@{$arg}) {
 6897: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6898:                                                    $scan_record, $error);
 6899:             push(@lines_to_correct,@linenums);
 6900: 	}
 6901:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6902:     } elsif ($error eq 'missingbubble') {
 6903: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
 6904: 	$r->print($message);
 6905: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 6906: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 6907: 
 6908: 	# The form field scantron_questions is actually a list of line numbers not
 6909: 	# a list of question numbers. Therefore:
 6910: 	#
 6911: 	
 6912: 	my $line_list = &questions_to_line_list($arg);
 6913: 
 6914: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6915: 		  $line_list.'" />');
 6916: 	foreach my $question (@{$arg}) {
 6917: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6918:                                                    $scan_record, $error);
 6919:             push(@lines_to_correct,@linenums);
 6920: 	}
 6921:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6922:     } else {
 6923: 	$r->print("\n<ul>");
 6924:     }
 6925:     $r->print("\n</li></ul>");
 6926: }
 6927: 
 6928: sub verify_bubbles_checked {
 6929:     my (@ansnums) = @_;
 6930:     my $ansnumstr = join('","',@ansnums);
 6931:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 6932:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
 6933: function verify_bubble_radio(form) {
 6934:     var ansnumArray = new Array ("$ansnumstr");
 6935:     var need_bubble_count = 0;
 6936:     for (var i=0; i<ansnumArray.length; i++) {
 6937:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 6938:             var bubble_picked = 0; 
 6939:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 6940:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 6941:                     bubble_picked = 1;
 6942:                 }
 6943:             }
 6944:             if (bubble_picked == 0) {
 6945:                 need_bubble_count ++;
 6946:             }
 6947:         }
 6948:     }
 6949:     if (need_bubble_count) {
 6950:         alert("$warning");
 6951:         return;
 6952:     }
 6953:     form.submit(); 
 6954: }
 6955: ENDSCRIPT
 6956:     return $output;
 6957: }
 6958: 
 6959: =pod
 6960: 
 6961: =item  questions_to_line_list
 6962: 
 6963: Converts a list of questions into a string of comma separated
 6964: line numbers in the answer sheet used by the questions.  This is
 6965: used to fill in the scantron_questions form field.
 6966: 
 6967:   Arguments:
 6968:      questions    - Reference to an array of questions.
 6969: 
 6970: =cut
 6971: 
 6972: 
 6973: sub questions_to_line_list {
 6974:     my ($questions) = @_;
 6975:     my @lines;
 6976: 
 6977:     foreach my $item (@{$questions}) {
 6978:         my $question = $item;
 6979:         my ($first,$count,$last);
 6980:         if ($item =~ /^(\d+)\.(\d+)$/) {
 6981:             $question = $1;
 6982:             my $subquestion = $2;
 6983:             $first = $first_bubble_line{$question-1} + 1;
 6984:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 6985:             my $subcount = 1;
 6986:             while ($subcount<$subquestion) {
 6987:                 $first += $subans[$subcount-1];
 6988:                 $subcount ++;
 6989:             }
 6990:             $count = $subans[$subquestion-1];
 6991:         } else {
 6992: 	    $first   = $first_bubble_line{$question-1} + 1;
 6993: 	    $count   = $bubble_lines_per_response{$question-1};
 6994:         }
 6995:         $last = $first+$count-1;
 6996:         push(@lines, ($first..$last));
 6997:     }
 6998:     return join(',', @lines);
 6999: }
 7000: 
 7001: =pod 
 7002: 
 7003: =item prompt_for_corrections
 7004: 
 7005: Prompts for a potentially multiline correction to the
 7006: user's bubbling (factors out common code from scantron_get_correction
 7007: for multi and missing bubble cases).
 7008: 
 7009:  Arguments:
 7010:    $r           - Apache request object.
 7011:    $question    - The question number to prompt for.
 7012:    $scan_config - The scantron file configuration hash.
 7013:    $scan_record - Reference to the hash that has the the parsed scanlines.
 7014:    $error       - Type of error
 7015: 
 7016:  Implicit inputs:
 7017:    %bubble_lines_per_response   - Starting line numbers for each question.
 7018:                                   Numbered from 0 (but question numbers are from
 7019:                                   1.
 7020:    %first_bubble_line           - Starting bubble line for each question.
 7021:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 7022:                                   type problems render as separate sub-questions, 
 7023:                                   in exam mode. This hash contains a 
 7024:                                   comma-separated list of the lines per 
 7025:                                   sub-question.
 7026:    %responsetype_per_response   - essayresponse, formularesponse,
 7027:                                   stringresponse, imageresponse, reactionresponse,
 7028:                                   and organicresponse type problem parts can have
 7029:                                   multiple lines per response if the weight
 7030:                                   assigned exceeds 10.  In this case, only
 7031:                                   one bubble per line is permitted, but more 
 7032:                                   than one line might contain bubbles, e.g.
 7033:                                   bubbling of: line 1 - J, line 2 - J, 
 7034:                                   line 3 - B would assign 22 points.  
 7035: 
 7036: =cut
 7037: 
 7038: sub prompt_for_corrections {
 7039:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
 7040:     my ($current_line,$lines);
 7041:     my @linenums;
 7042:     my $questionnum = $question;
 7043:     if ($question =~ /^(\d+)\.(\d+)$/) {
 7044:         $question = $1;
 7045:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7046:         my $subquestion = $2;
 7047:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7048:         my $subcount = 1;
 7049:         while ($subcount<$subquestion) {
 7050:             $current_line += $subans[$subcount-1];
 7051:             $subcount ++;
 7052:         }
 7053:         $lines = $subans[$subquestion-1];
 7054:     } else {
 7055:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7056:         $lines        = $bubble_lines_per_response{$question-1};
 7057:     }
 7058:     if ($lines > 1) {
 7059:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7060:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
 7061:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
 7062:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
 7063:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
 7064:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
 7065:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
 7066:             $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 />');
 7067:         } else {
 7068:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7069:         }
 7070:     }
 7071:     for (my $i =0; $i < $lines; $i++) {
 7072:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7073: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
 7074: 	        		  $questionnum,$error,split('', $selected));
 7075:         push(@linenums,$current_line);
 7076: 	$current_line++;
 7077:     }
 7078:     if ($lines > 1) {
 7079: 	$r->print("<hr /><br />");
 7080:     }
 7081:     return @linenums;
 7082: }
 7083: 
 7084: =pod
 7085: 
 7086: =item scantron_bubble_selector
 7087:   
 7088:    Generates the html radiobuttons to correct a single bubble line
 7089:    possibly showing the existing the selected bubbles if known
 7090: 
 7091:  Arguments:
 7092:     $r           - Apache request object
 7093:     $scan_config - hash from &get_scantron_config()
 7094:     $line        - Number of the line being displayed.
 7095:     $questionnum - Question number (may include subquestion)
 7096:     $error       - Type of error.
 7097:     @selected    - Array of bubbles picked on this line.
 7098: 
 7099: =cut
 7100: 
 7101: sub scantron_bubble_selector {
 7102:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7103:     my $max=$$scan_config{'Qlength'};
 7104: 
 7105:     my $scmode=$$scan_config{'Qon'};
 7106:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
 7107: 
 7108:     my @alphabet=('A'..'Z');
 7109:     $r->print(&Apache::loncommon::start_data_table().
 7110:               &Apache::loncommon::start_data_table_row());
 7111:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7112:     for (my $i=0;$i<$max+1;$i++) {
 7113: 	$r->print("\n".'<td align="center">');
 7114: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7115: 	else { $r->print('&nbsp;'); }
 7116: 	$r->print('</td>');
 7117:     }
 7118:     $r->print(&Apache::loncommon::end_data_table_row().
 7119:               &Apache::loncommon::start_data_table_row());
 7120:     for (my $i=0;$i<$max;$i++) {
 7121: 	$r->print("\n".
 7122: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7123: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7124:     }
 7125:     my $nobub_checked = ' ';
 7126:     if ($error eq 'missingbubble') {
 7127:         $nobub_checked = ' checked = "checked" ';
 7128:     }
 7129:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7130: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7131:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7132:               $line.'" value="'.$questionnum.'" /></td>');
 7133:     $r->print(&Apache::loncommon::end_data_table_row().
 7134:               &Apache::loncommon::end_data_table());
 7135: }
 7136: 
 7137: =pod
 7138: 
 7139: =item num_matches
 7140: 
 7141:    Counts the number of characters that are the same between the two arguments.
 7142: 
 7143:  Arguments:
 7144:    $orig - CODE from the scanline
 7145:    $code - CODE to match against
 7146: 
 7147:  Returns:
 7148:    $count - integer count of the number of same characters between the
 7149:             two arguments
 7150: 
 7151: =cut
 7152: 
 7153: sub num_matches {
 7154:     my ($orig,$code) = @_;
 7155:     my @code=split(//,$code);
 7156:     my @orig=split(//,$orig);
 7157:     my $same=0;
 7158:     for (my $i=0;$i<scalar(@code);$i++) {
 7159: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7160:     }
 7161:     return $same;
 7162: }
 7163: 
 7164: =pod
 7165: 
 7166: =item scantron_get_closely_matching_CODEs
 7167: 
 7168:    Cycles through all CODEs and finds the set that has the greatest
 7169:    number of same characters as the provided CODE
 7170: 
 7171:  Arguments:
 7172:    $allcodes - hash ref returned by &get_codes()
 7173:    $CODE     - CODE from the current scanline
 7174: 
 7175:  Returns:
 7176:    2 element list
 7177:     - first elements is number of how closely matching the best fit is 
 7178:       (5 means best set has 5 matching characters)
 7179:     - second element is an arrary ref containing the set of valid CODEs
 7180:       that best fit the passed in CODE
 7181: 
 7182: =cut
 7183: 
 7184: sub scantron_get_closely_matching_CODEs {
 7185:     my ($allcodes,$CODE)=@_;
 7186:     my @CODEs;
 7187:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7188: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7189:     }
 7190: 
 7191:     return ($#CODEs,$CODEs[-1]);
 7192: }
 7193: 
 7194: =pod
 7195: 
 7196: =item get_codes
 7197: 
 7198:    Builds a hash which has keys of all of the valid CODEs from the selected
 7199:    set of remembered CODEs.
 7200: 
 7201:  Arguments:
 7202:   $old_name - name of the set of remembered CODEs
 7203:   $cdom     - domain of the course
 7204:   $cnum     - internal course name
 7205: 
 7206:  Returns:
 7207:   %allcodes - keys are the valid CODEs, values are all 1
 7208: 
 7209: =cut
 7210: 
 7211: sub get_codes {
 7212:     my ($old_name, $cdom, $cnum) = @_;
 7213:     if (!$old_name) {
 7214: 	$old_name=$env{'form.scantron_CODElist'};
 7215:     }
 7216:     if (!$cdom) {
 7217: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7218:     }
 7219:     if (!$cnum) {
 7220: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7221:     }
 7222:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7223: 				    $cdom,$cnum);
 7224:     my %allcodes;
 7225:     if ($result{"type\0$old_name"} eq 'number') {
 7226: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7227:     } else {
 7228: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7229:     }
 7230:     return %allcodes;
 7231: }
 7232: 
 7233: =pod
 7234: 
 7235: =item scantron_validate_CODE
 7236: 
 7237:    Validates all scanlines in the selected file to not have any
 7238:    invalid or underspecified CODEs and that none of the codes are
 7239:    duplicated if this was requested.
 7240: 
 7241: =cut
 7242: 
 7243: sub scantron_validate_CODE {
 7244:     my ($r,$currentphase) = @_;
 7245:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7246:     if ($scantron_config{'CODElocation'} &&
 7247: 	$scantron_config{'CODEstart'} &&
 7248: 	$scantron_config{'CODElength'}) {
 7249: 	if (!defined($env{'form.scantron_CODElist'})) {
 7250: 	    &FIXME_blow_up()
 7251: 	}
 7252:     } else {
 7253: 	return (0,$currentphase+1);
 7254:     }
 7255:     
 7256:     my %usedCODEs;
 7257: 
 7258:     my %allcodes=&get_codes();
 7259: 
 7260:     my $nav_error;
 7261:     &scantron_get_maxbubble(\$nav_error); # parse needs the lines per response array.
 7262:     if ($nav_error) {
 7263:         $r->print(&navmap_errormsg());
 7264:         return(1,$currentphase);
 7265:     }
 7266: 
 7267:     my ($scanlines,$scan_data)=&scantron_getfile();
 7268:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7269: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7270: 	if ($line=~/^[\s\cz]*$/) { next; }
 7271: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7272: 						 $scan_data);
 7273: 	my $CODE=$$scan_record{'scantron.CODE'};
 7274: 	my $error=0;
 7275: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7276: 	    &scantron_get_correction($r,$i,$scan_record,
 7277: 				     \%scantron_config,
 7278: 				     $line,'incorrectCODE',\%allcodes);
 7279: 	    return(1,$currentphase);
 7280: 	}
 7281: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7282: 	    && !$$scan_record{'scantron.useCODE'}) {
 7283: 	    &scantron_get_correction($r,$i,$scan_record,
 7284: 				     \%scantron_config,
 7285: 				     $line,'incorrectCODE',\%allcodes);
 7286: 	    return(1,$currentphase);
 7287: 	}
 7288: 	if (exists($usedCODEs{$CODE}) 
 7289: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 7290: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 7291: 	    &scantron_get_correction($r,$i,$scan_record,
 7292: 				     \%scantron_config,
 7293: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 7294: 	    return(1,$currentphase);
 7295: 	}
 7296: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 7297:     }
 7298:     return (0,$currentphase+1);
 7299: }
 7300: 
 7301: =pod
 7302: 
 7303: =item scantron_validate_doublebubble
 7304: 
 7305:    Validates all scanlines in the selected file to not have any
 7306:    bubble lines with multiple bubbles marked.
 7307: 
 7308: =cut
 7309: 
 7310: sub scantron_validate_doublebubble {
 7311:     my ($r,$currentphase) = @_;
 7312:     #get student info
 7313:     my $classlist=&Apache::loncoursedata::get_classlist();
 7314:     my %idmap=&username_to_idmap($classlist);
 7315: 
 7316:     #get scantron line setup
 7317:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7318:     my ($scanlines,$scan_data)=&scantron_getfile();
 7319:     my $nav_error;
 7320:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble line array.
 7321:     if ($nav_error) {
 7322:         $r->print(&navmap_errormsg());
 7323:         return(1,$currentphase);
 7324:     }
 7325: 
 7326:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7327: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7328: 	if ($line=~/^[\s\cz]*$/) { next; }
 7329: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7330: 						 $scan_data);
 7331: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 7332: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 7333: 				 'doublebubble',
 7334: 				 $$scan_record{'scantron.doubleerror'});
 7335:     	return (1,$currentphase);
 7336:     }
 7337:     return (0,$currentphase+1);
 7338: }
 7339: 
 7340: 
 7341: sub scantron_get_maxbubble {
 7342:     my ($nav_error) = @_;
 7343:     if (defined($env{'form.scantron_maxbubble'}) &&
 7344: 	$env{'form.scantron_maxbubble'}) {
 7345: 	&restore_bubble_lines();
 7346: 	return $env{'form.scantron_maxbubble'};
 7347:     }
 7348: 
 7349:     my (undef, undef, $sequence) =
 7350: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7351: 
 7352:     my $navmap=Apache::lonnavmaps::navmap->new();
 7353:     unless (ref($navmap)) {
 7354:         if (ref($nav_error)) {
 7355:             $$nav_error = 1;
 7356:         }
 7357:         return;
 7358:     }
 7359:     my $map=$navmap->getResourceByUrl($sequence);
 7360:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7361: 
 7362:     &Apache::lonxml::clear_problem_counter();
 7363: 
 7364:     my $uname       = $env{'user.name'};
 7365:     my $udom        = $env{'user.domain'};
 7366:     my $cid         = $env{'request.course.id'};
 7367:     my $total_lines = 0;
 7368:     %bubble_lines_per_response = ();
 7369:     %first_bubble_line         = ();
 7370:     %subdivided_bubble_lines   = ();
 7371:     %responsetype_per_response = ();
 7372: 
 7373:     my $response_number = 0;
 7374:     my $bubble_line     = 0;
 7375:     foreach my $resource (@resources) {
 7376:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
 7377:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 7378: 	    foreach my $part_id (@{$parts}) {
 7379:                 my $lines;
 7380: 
 7381: 	        # TODO - make this a persistent hash not an array.
 7382: 
 7383:                 # optionresponse, matchresponse and rankresponse type items 
 7384:                 # render as separate sub-questions in exam mode.
 7385:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 7386:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 7387:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 7388:                     my ($numbub,$numshown);
 7389:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 7390:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 7391:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 7392:                         }
 7393:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 7394:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 7395:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 7396:                         }
 7397:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 7398:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 7399:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 7400:                         }
 7401:                     }
 7402:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 7403:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 7404:                     }
 7405:                     my $bubbles_per_line = 10;
 7406:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
 7407:                     if (($numbub % $bubbles_per_line) != 0) {
 7408:                         $inner_bubble_lines++;
 7409:                     }
 7410:                     for (my $i=0; $i<$numshown; $i++) {
 7411:                         $subdivided_bubble_lines{$response_number} .= 
 7412:                             $inner_bubble_lines.',';
 7413:                     }
 7414:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 7415:                     $lines = $numshown * $inner_bubble_lines;
 7416:                 } else {
 7417:                     $lines = $analysis->{"$part_id.bubble_lines"};
 7418:                 } 
 7419: 
 7420:                 $first_bubble_line{$response_number} = $bubble_line;
 7421: 	        $bubble_lines_per_response{$response_number} = $lines;
 7422:                 $responsetype_per_response{$response_number} = 
 7423:                     $analysis->{$part_id.'.type'};
 7424: 	        $response_number++;
 7425: 
 7426: 	        $bubble_line +=  $lines;
 7427: 	        $total_lines +=  $lines;
 7428: 	    }
 7429:         }
 7430:     }
 7431:     &Apache::lonnet::delenv('scantron.');
 7432: 
 7433:     &save_bubble_lines();
 7434:     $env{'form.scantron_maxbubble'} =
 7435: 	$total_lines;
 7436:     return $env{'form.scantron_maxbubble'};
 7437: }
 7438: 
 7439: sub scantron_validate_missingbubbles {
 7440:     my ($r,$currentphase) = @_;
 7441:     #get student info
 7442:     my $classlist=&Apache::loncoursedata::get_classlist();
 7443:     my %idmap=&username_to_idmap($classlist);
 7444: 
 7445:     #get scantron line setup
 7446:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7447:     my ($scanlines,$scan_data)=&scantron_getfile();
 7448:     my $nav_error;
 7449:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
 7450:     if ($nav_error) {
 7451:         return(1,$currentphase);
 7452:     }
 7453:     if (!$max_bubble) { $max_bubble=2**31; }
 7454:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7455: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7456: 	if ($line=~/^[\s\cz]*$/) { next; }
 7457: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7458: 						 $scan_data);
 7459: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 7460: 	my @to_correct;
 7461: 	
 7462: 	# Probably here's where the error is...
 7463: 
 7464: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 7465:             my $lastbubble;
 7466:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 7467:                my $question = $1;
 7468:                my $subquestion = $2;
 7469:                if (!defined($first_bubble_line{$question -1})) { next; }
 7470:                my $first = $first_bubble_line{$question-1};
 7471:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7472:                my $subcount = 1;
 7473:                while ($subcount<$subquestion) {
 7474:                    $first += $subans[$subcount-1];
 7475:                    $subcount ++;
 7476:                }
 7477:                my $count = $subans[$subquestion-1];
 7478:                $lastbubble = $first + $count;
 7479:             } else {
 7480:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
 7481:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
 7482:             }
 7483:             if ($lastbubble > $max_bubble) { next; }
 7484: 	    push(@to_correct,$missing);
 7485: 	}
 7486: 	if (@to_correct) {
 7487: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7488: 				     $line,'missingbubble',\@to_correct);
 7489: 	    return (1,$currentphase);
 7490: 	}
 7491: 
 7492:     }
 7493:     return (0,$currentphase+1);
 7494: }
 7495: 
 7496: 
 7497: sub scantron_process_students {
 7498:     my ($r,$symb) = @_;
 7499: 
 7500:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7501:     if (!$symb) {
 7502: 	return '';
 7503:     }
 7504:     my $default_form_data=&defaultFormData($symb);
 7505: 
 7506:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7507:     my ($scanlines,$scan_data)=&scantron_getfile();
 7508:     my $classlist=&Apache::loncoursedata::get_classlist();
 7509:     my %idmap=&username_to_idmap($classlist);
 7510:     my $navmap=Apache::lonnavmaps::navmap->new();
 7511:     unless (ref($navmap)) {
 7512:         $r->print(&navmap_errormsg());
 7513:         return '';
 7514:     }  
 7515:     my $map=$navmap->getResourceByUrl($sequence);
 7516:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7517:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 7518:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 7519:                             \%grader_randomlists_by_symb);
 7520:     my $resource_error;
 7521:     foreach my $resource (@resources) {
 7522:         my $ressymb;
 7523:         if (ref($resource)) {
 7524:             $ressymb = $resource->symb();
 7525:         } else {
 7526:             $resource_error = 1;
 7527:             last;
 7528:         }
 7529:         my ($analysis,$parts) =
 7530:             &scantron_partids_tograde($resource,$env{'request.course.id'},
 7531:                                       $env{'user.name'},$env{'user.domain'},1);
 7532:         $grader_partids_by_symb{$ressymb} = $parts;
 7533:         if (ref($analysis) eq 'HASH') {
 7534:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7535:                 $grader_randomlists_by_symb{$ressymb} = 
 7536:                     $analysis->{'parts_withrandomlist'};
 7537:             }
 7538:         }
 7539:     }
 7540:     if ($resource_error) {
 7541:         $r->print(&navmap_errormsg());
 7542:         return '';
 7543:     }
 7544: 
 7545:     my ($uname,$udom);
 7546:     my $result= <<SCANTRONFORM;
 7547: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7548:   <input type="hidden" name="command" value="scantron_configphase" />
 7549:   $default_form_data
 7550: SCANTRONFORM
 7551:     $r->print($result);
 7552: 
 7553:     my @delayqueue;
 7554:     my (%completedstudents,%scandata);
 7555:     
 7556:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 7557:     my $count=&get_todo_count($scanlines,$scan_data);
 7558:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
 7559:  				    'Bubblesheet Progress',$count,
 7560: 				    'inline',undef,'scantronupload');
 7561:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 7562: 					  'Processing first student');
 7563:     $r->print('<br />');
 7564:     my $start=&Time::HiRes::time();
 7565:     my $i=-1;
 7566:     my $started;
 7567: 
 7568:     my $nav_error;
 7569:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
 7570:     if ($nav_error) {
 7571:         $r->print(&navmap_errormsg());
 7572:         return '';
 7573:     }
 7574: 
 7575:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 7576:     # the user and return.
 7577: 
 7578:     if ($ssi_error) {
 7579: 	$r->print("</form>");
 7580: 	&ssi_print_error($r);
 7581:         &Apache::lonnet::remove_lock($lock);
 7582: 	return '';		# Dunno why the other returns return '' rather than just returning.
 7583:     }
 7584: 
 7585:     my %lettdig = &letter_to_digits();
 7586:     my $numletts = scalar(keys(%lettdig));
 7587: 
 7588:     while ($i<$scanlines->{'count'}) {
 7589:  	($uname,$udom)=('','');
 7590:  	$i++;
 7591:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7592:  	if ($line=~/^[\s\cz]*$/) { next; }
 7593: 	if ($started) {
 7594: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 7595: 						     'last student');
 7596: 	}
 7597: 	$started=1;
 7598:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7599:  						 $scan_data);
 7600:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 7601:  					      \%idmap,$i)) {
 7602:   	    &scantron_add_delay(\@delayqueue,$line,
 7603:  				'Unable to find a student that matches',1);
 7604:  	    next;
 7605:   	}
 7606:  	if (exists $completedstudents{$uname}) {
 7607:  	    &scantron_add_delay(\@delayqueue,$line,
 7608:  				'Student '.$uname.' has multiple sheets',2);
 7609:  	    next;
 7610:  	}
 7611:   	($uname,$udom)=split(/:/,$uname);
 7612: 
 7613:         my (%partids_by_symb,$res_error);
 7614:         foreach my $resource (@resources) {
 7615:             my $ressymb;
 7616:             if (ref($resource)) {
 7617:                 $ressymb = $resource->symb();
 7618:             } else {
 7619:                 $res_error = 1;
 7620:                 last;
 7621:             }
 7622:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 7623:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 7624:                 my ($analysis,$parts) =
 7625:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
 7626:                 $partids_by_symb{$ressymb} = $parts;
 7627:             } else {
 7628:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 7629:             }
 7630:         }
 7631: 
 7632:         if ($res_error) {
 7633:             &scantron_add_delay(\@delayqueue,$line,
 7634:                                 'An error occurred while grading student '.$uname,2);
 7635:             next;
 7636:         }
 7637: 
 7638: 	&Apache::lonxml::clear_problem_counter();
 7639:   	&Apache::lonnet::appenv($scan_record);
 7640: 
 7641: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 7642: 	    &scantron_putfile($scanlines,$scan_data);
 7643: 	}
 7644: 	
 7645:         my $scancode;
 7646:         if ((exists($scan_record->{'scantron.CODE'})) &&
 7647:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 7648:             $scancode = $scan_record->{'scantron.CODE'};
 7649:         } else {
 7650:             $scancode = '';
 7651:         }
 7652: 
 7653:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7654:                                    \@resources,\%partids_by_symb) eq 'ssi_error') {
 7655:             $ssi_error = 0; # So end of handler error message does not trigger.
 7656:             $r->print("</form>");
 7657:             &ssi_print_error($r);
 7658:             &Apache::lonnet::remove_lock($lock);
 7659:             return '';      # Why return ''?  Beats me.
 7660:         }
 7661: 
 7662: 	$completedstudents{$uname}={'line'=>$line};
 7663:         if ($env{'form.verifyrecord'}) {
 7664:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 7665:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 7666:             chomp($studentdata);
 7667:             $studentdata =~ s/\r$//;
 7668:             my $studentrecord = '';
 7669:             my $counter = -1;
 7670:             foreach my $resource (@resources) {
 7671:                 my $ressymb = $resource->symb();
 7672:                 ($counter,my $recording) =
 7673:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7674:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 7675:                                              \%scantron_config,\%lettdig,$numletts);
 7676:                 $studentrecord .= $recording;
 7677:             }
 7678:             if ($studentrecord ne $studentdata) {
 7679:                 &Apache::lonxml::clear_problem_counter();
 7680:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7681:                                            \@resources,\%partids_by_symb) eq 'ssi_error') {
 7682:                     $ssi_error = 0; # So end of handler error message does not trigger.
 7683:                     $r->print("</form>");
 7684:                     &ssi_print_error($r);
 7685:                     &Apache::lonnet::remove_lock($lock);
 7686:                     delete($completedstudents{$uname});
 7687:                     return '';
 7688:                 }
 7689:                 $counter = -1;
 7690:                 $studentrecord = '';
 7691:                 foreach my $resource (@resources) {
 7692:                     my $ressymb = $resource->symb();
 7693:                     ($counter,my $recording) =
 7694:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7695:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 7696:                                                  \%scantron_config,\%lettdig,$numletts);
 7697:                     $studentrecord .= $recording;
 7698:                 }
 7699:                 if ($studentrecord ne $studentdata) {
 7700:                     $r->print('<p><span class="LC_error">');
 7701:                     if ($scancode eq '') {
 7702:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
 7703:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 7704:                     } else {
 7705:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
 7706:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 7707:                     }
 7708:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 7709:                               &Apache::loncommon::start_data_table_header_row()."\n".
 7710:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 7711:                               &Apache::loncommon::end_data_table_header_row()."\n".
 7712:                               &Apache::loncommon::start_data_table_row().
 7713:                               '<td>'.&mt('Bubble Sheet').'</td>'.
 7714:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
 7715:                               &Apache::loncommon::end_data_table_row().
 7716:                               &Apache::loncommon::start_data_table_row().
 7717:                               '<td>Stored submissions</td>'.
 7718:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
 7719:                               &Apache::loncommon::end_data_table_row().
 7720:                               &Apache::loncommon::end_data_table().'</p>');
 7721:                 } else {
 7722:                     $r->print('<br /><span class="LC_warning">'.
 7723:                              &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 />'.
 7724:                              &mt("As a consequence, this user's submission history records two tries.").
 7725:                                  '</span><br />');
 7726:                 }
 7727:             }
 7728:         }
 7729:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 7730:     } continue {
 7731: 	&Apache::lonxml::clear_problem_counter();
 7732: 	&Apache::lonnet::delenv('scantron.');
 7733:     }
 7734:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 7735:     &Apache::lonnet::remove_lock($lock);
 7736: #    my $lasttime = &Time::HiRes::time()-$start;
 7737: #    $r->print("<p>took $lasttime</p>");
 7738: 
 7739:     $r->print("</form>");
 7740:     return '';
 7741: }
 7742: 
 7743: sub graders_resources_pass {
 7744:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
 7745:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 7746:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 7747:         foreach my $resource (@{$resources}) {
 7748:             my $ressymb = $resource->symb();
 7749:             my ($analysis,$parts) =
 7750:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 7751:                                           $env{'user.name'},$env{'user.domain'},1);
 7752:             $grader_partids_by_symb->{$ressymb} = $parts;
 7753:             if (ref($analysis) eq 'HASH') {
 7754:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7755:                     $grader_randomlists_by_symb->{$ressymb} =
 7756:                         $analysis->{'parts_withrandomlist'};
 7757:                 }
 7758:             }
 7759:         }
 7760:     }
 7761:     return;
 7762: }
 7763: 
 7764: sub grade_student_bubbles {
 7765:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
 7766:     if (ref($resources) eq 'ARRAY') {
 7767:         my $count = 0;
 7768:         foreach my $resource (@{$resources}) {
 7769:             my $ressymb = $resource->symb();
 7770:             my %form = ('submitted'      => 'scantron',
 7771:                         'grade_target'   => 'grade',
 7772:                         'grade_username' => $uname,
 7773:                         'grade_domain'   => $udom,
 7774:                         'grade_courseid' => $env{'request.course.id'},
 7775:                         'grade_symb'     => $ressymb,
 7776:                         'CODE'           => $scancode
 7777:                        );
 7778:             if (ref($parts) eq 'HASH') {
 7779:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 7780:                     foreach my $part (@{$parts->{$ressymb}}) {
 7781:                         $form{'scantron_questnum_start.'.$part} =
 7782:                             1+$env{'form.scantron.first_bubble_line.'.$count};
 7783:                         $count++;
 7784:                     }
 7785:                 }
 7786:             }
 7787:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 7788:             return 'ssi_error' if ($ssi_error);
 7789:             last if (&Apache::loncommon::connection_aborted($r));
 7790:         }
 7791:     }
 7792:     return;
 7793: }
 7794: 
 7795: sub scantron_upload_scantron_data {
 7796:     my ($r,$symb)=@_;
 7797:     my $dom = $env{'request.role.domain'};
 7798:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 7799:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 7800:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 7801: 							  'domainid',
 7802: 							  'coursename',$dom);
 7803:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 7804:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
 7805:     my $default_form_data=&defaultFormData($symb);
 7806:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 7807:     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.");
 7808:     $r->print(&Apache::lonhtmlcommon::scripttag('
 7809:     function checkUpload(formname) {
 7810: 	if (formname.upfile.value == "") {
 7811: 	    alert("'.$nofile_alert.'");
 7812: 	    return false;
 7813: 	}
 7814:         if (formname.courseid.value == "") {
 7815:             alert("'.$nocourseid_alert.'");
 7816:             return false;
 7817:         }
 7818: 	formname.submit();
 7819:     }
 7820: 
 7821:     function ToSyllabus() {
 7822:         var cdom = '."'$dom'".';
 7823:         var cnum = document.rules.courseid.value;
 7824:         if (cdom == "" || cdom == null) {
 7825:             return;
 7826:         }
 7827:         if (cnum == "" || cnum == null) {
 7828:            return;
 7829:         }
 7830:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 7831:                             "height=350,width=350,scrollbars=yes,menubar=no");
 7832:         return;
 7833:     }
 7834: 
 7835: '));
 7836:     $r->print('
 7837: <h3>'.&mt('Send scanned bubblesheet data to a course').'</h3>
 7838: 
 7839: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 7840: '.$default_form_data.
 7841:   &Apache::lonhtmlcommon::start_pick_box().
 7842:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 7843:   '<input name="courseid" type="text" size="30" />'.$select_link.
 7844:   &Apache::lonhtmlcommon::row_closure().
 7845:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 7846:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 7847:   &Apache::lonhtmlcommon::row_closure().
 7848:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 7849:   '<input name="domainid" type="hidden" />'.$domdesc.
 7850:   &Apache::lonhtmlcommon::row_closure().
 7851:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 7852:   '<input type="file" name="upfile" size="50" />'.
 7853:   &Apache::lonhtmlcommon::row_closure(1).
 7854:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 7855: 
 7856: <input name="command" value="scantronupload_save" type="hidden" />
 7857: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 7858: </form>
 7859: ');
 7860:     return '';
 7861: }
 7862: 
 7863: 
 7864: sub scantron_upload_scantron_data_save {
 7865:     my($r,$symb)=@_;
 7866:     my $doanotherupload=
 7867: 	'<br /><form action="/adm/grades" method="post">'."\n".
 7868: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 7869: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 7870: 	'</form>'."\n";
 7871:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 7872: 	!&Apache::lonnet::allowed('usc',
 7873: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 7874: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 7875: 	unless ($symb) {
 7876: 	    $r->print($doanotherupload);
 7877: 	}
 7878: 	return '';
 7879:     }
 7880:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 7881:     my $uploadedfile;
 7882:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
 7883:     if (length($env{'form.upfile'}) < 2) {
 7884:         $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>'));
 7885:     } else {
 7886:         my $result = 
 7887:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
 7888:                                             $env{'form.courseid'},$env{'form.domainid'});
 7889: 	if ($result =~ m{^/uploaded/}) {
 7890: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
 7891:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
 7892: 			  '<span class="LC_filename">'.$result.'</span>'));
 7893:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 7894:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 7895:                                                        $env{'form.courseid'},$uploadedfile));
 7896: 	} else {
 7897: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
 7898:                           '<span class="LC_error">','</span>',$result,
 7899: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 7900: 	}
 7901:     }
 7902:     if ($symb) {
 7903: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
 7904:     } else {
 7905: 	$r->print($doanotherupload);
 7906:     }
 7907:     return '';
 7908: }
 7909: 
 7910: sub validate_uploaded_scantron_file {
 7911:     my ($cdom,$cname,$fname) = @_;
 7912:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 7913:     my @lines;
 7914:     if ($scanlines ne '-1') {
 7915:         @lines=split("\n",$scanlines,-1);
 7916:     }
 7917:     my $output;
 7918:     if (@lines) {
 7919:         my (%counts,$max_match_format);
 7920:         my ($max_match_count,$max_match_pct) = (0,0);
 7921:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 7922:         my %idmap = &username_to_idmap($classlist);
 7923:         foreach my $key (keys(%idmap)) {
 7924:             my $lckey = lc($key);
 7925:             $idmap{$lckey} = $idmap{$key};
 7926:         }
 7927:         my %unique_formats;
 7928:         my @formatlines = &get_scantronformat_file();
 7929:         foreach my $line (@formatlines) {
 7930:             chomp($line);
 7931:             my @config = split(/:/,$line);
 7932:             my $idstart = $config[5];
 7933:             my $idlength = $config[6];
 7934:             if (($idstart ne '') && ($idlength > 0)) {
 7935:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 7936:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 7937:                 } else {
 7938:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 7939:                 }
 7940:             }
 7941:         }
 7942:         foreach my $key (keys(%unique_formats)) {
 7943:             my ($idstart,$idlength) = split(':',$key);
 7944:             %{$counts{$key}} = (
 7945:                                'found'   => 0,
 7946:                                'total'   => 0,
 7947:                               );
 7948:             foreach my $line (@lines) {
 7949:                 next if ($line =~ /^#/);
 7950:                 next if ($line =~ /^[\s\cz]*$/);
 7951:                 my $id = substr($line,$idstart-1,$idlength);
 7952:                 $id = lc($id);
 7953:                 if (exists($idmap{$id})) {
 7954:                     $counts{$key}{'found'} ++;
 7955:                 }
 7956:                 $counts{$key}{'total'} ++;
 7957:             }
 7958:             if ($counts{$key}{'total'}) {
 7959:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 7960:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 7961:                     $max_match_pct = $percent_match;
 7962:                     $max_match_format = $key;
 7963:                     $max_match_count = $counts{$key}{'total'};
 7964:                 }
 7965:             }
 7966:         }
 7967:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 7968:             my $format_descs;
 7969:             my $numwithformat = @{$unique_formats{$max_match_format}};
 7970:             for (my $i=0; $i<$numwithformat; $i++) {
 7971:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 7972:                 if ($i<$numwithformat-2) {
 7973:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 7974:                 } elsif ($i==$numwithformat-2) {
 7975:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 7976:                 } elsif ($i==$numwithformat-1) {
 7977:                     $format_descs .= '"<i>'.$desc.'</i>"';
 7978:                 }
 7979:             }
 7980:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 7981:             $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).
 7982:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
 7983:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
 7984:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
 7985:                                   '<i>'.$cdom.'</i>').'</li>'.
 7986:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 7987:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
 7988:                        '</ul>';
 7989:         }
 7990:     } else {
 7991:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
 7992:     }
 7993:     return $output;
 7994: }
 7995: 
 7996: sub valid_file {
 7997:     my ($requested_file)=@_;
 7998:     foreach my $filename (sort(&scantron_filenames())) {
 7999: 	if ($requested_file eq $filename) { return 1; }
 8000:     }
 8001:     return 0;
 8002: }
 8003: 
 8004: sub scantron_download_scantron_data {
 8005:     my ($r,$symb)=@_;
 8006:     my $default_form_data=&defaultFormData($symb);
 8007:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8008:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8009:     my $file=$env{'form.scantron_selectfile'};
 8010:     if (! &valid_file($file)) {
 8011: 	$r->print('
 8012: 	<p>
 8013: 	    '.&mt('The requested file name was invalid.').'
 8014:         </p>
 8015: ');
 8016: 	return;
 8017:     }
 8018:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 8019:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 8020:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 8021:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 8022:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 8023:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 8024:     $r->print('
 8025:     <p>
 8026: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
 8027: 	      '<a href="'.$orig.'">','</a>').'
 8028:     </p>
 8029:     <p>
 8030: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 8031: 	      '<a href="'.$corrected.'">','</a>').'
 8032:     </p>
 8033:     <p>
 8034: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 8035: 	      '<a href="'.$skipped.'">','</a>').'
 8036:     </p>
 8037: ');
 8038:     return '';
 8039: }
 8040: 
 8041: sub checkscantron_results {
 8042:     my ($r,$symb) = @_;
 8043:     if (!$symb) {return '';}
 8044:     my $cid = $env{'request.course.id'};
 8045:     my %lettdig = &letter_to_digits();
 8046:     my $numletts = scalar(keys(%lettdig));
 8047:     my $cnum = $env{'course.'.$cid.'.num'};
 8048:     my $cdom = $env{'course.'.$cid.'.domain'};
 8049:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8050:     my %record;
 8051:     my %scantron_config =
 8052:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 8053:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 8054:     my $classlist=&Apache::loncoursedata::get_classlist();
 8055:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 8056:     my $navmap=Apache::lonnavmaps::navmap->new();
 8057:     unless (ref($navmap)) {
 8058:         $r->print(&navmap_errormsg());
 8059:         return '';
 8060:     }
 8061:     my $map=$navmap->getResourceByUrl($sequence);
 8062:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8063:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 8064:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
 8065: 
 8066:     my ($uname,$udom);
 8067:     my (%scandata,%lastname,%bylast);
 8068:     $r->print('
 8069: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 8070: 
 8071:     my @delayqueue;
 8072:     my %completedstudents;
 8073: 
 8074:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
 8075:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
 8076:                                     'Progress of Bubblesheet Data/Submission Records Comparison',$count,
 8077:                                     'inline',undef,'checkscantron');
 8078:     my ($username,$domain,$started);
 8079:     my $nav_error;
 8080:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
 8081:     if ($nav_error) {
 8082:         $r->print(&navmap_errormsg());
 8083:         return '';
 8084:     }
 8085: 
 8086:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 8087:                                           'Processing first student');
 8088:     my $start=&Time::HiRes::time();
 8089:     my $i=-1;
 8090: 
 8091:     while ($i<$scanlines->{'count'}) {
 8092:         ($username,$domain,$uname)=('','','');
 8093:         $i++;
 8094:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 8095:         if ($line=~/^[\s\cz]*$/) { next; }
 8096:         if ($started) {
 8097:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 8098:                                                      'last student');
 8099:         }
 8100:         $started=1;
 8101:         my $scan_record=
 8102:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 8103:                                                      $scan_data);
 8104:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
 8105:                                                               \%idmap,$i)) {
 8106:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8107:                                 'Unable to find a student that matches',1);
 8108:             next;
 8109:         }
 8110:         if (exists $completedstudents{$uname}) {
 8111:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8112:                                 'Student '.$uname.' has multiple sheets',2);
 8113:             next;
 8114:         }
 8115:         my $pid = $scan_record->{'scantron.ID'};
 8116:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 8117:         push(@{$bylast{$lastname{$pid}}},$pid);
 8118:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8119:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8120:         chomp($scandata{$pid});
 8121:         $scandata{$pid} =~ s/\r$//;
 8122:         ($username,$domain)=split(/:/,$uname);
 8123:         my $counter = -1;
 8124:         foreach my $resource (@resources) {
 8125:             my $parts;
 8126:             my $ressymb = $resource->symb();
 8127:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8128:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8129:                 (my $analysis,$parts) =
 8130:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
 8131:             } else {
 8132:                 $parts = $grader_partids_by_symb{$ressymb};
 8133:             }
 8134:             ($counter,my $recording) =
 8135:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 8136:                                          $scandata{$pid},$parts,
 8137:                                          \%scantron_config,\%lettdig,$numletts);
 8138:             $record{$pid} .= $recording;
 8139:         }
 8140:     }
 8141:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8142:     $r->print('<br />');
 8143:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 8144:     $passed = 0;
 8145:     $failed = 0;
 8146:     $numstudents = 0;
 8147:     foreach my $last (sort(keys(%bylast))) {
 8148:         if (ref($bylast{$last}) eq 'ARRAY') {
 8149:             foreach my $pid (sort(@{$bylast{$last}})) {
 8150:                 my $showscandata = $scandata{$pid};
 8151:                 my $showrecord = $record{$pid};
 8152:                 $showscandata =~ s/\s/&nbsp;/g;
 8153:                 $showrecord =~ s/\s/&nbsp;/g;
 8154:                 if ($scandata{$pid} eq $record{$pid}) {
 8155:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 8156:                     $okstudents .= '<tr class="'.$css_class.'">'.
 8157: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 8158: '</tr>'."\n".
 8159: '<tr class="'.$css_class.'">'."\n".
 8160: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
 8161:                     $passed ++;
 8162:                 } else {
 8163:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 8164:                     $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".
 8165: '</tr>'."\n".
 8166: '<tr class="'.$css_class.'">'."\n".
 8167: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 8168: '</tr>'."\n";
 8169:                     $failed ++;
 8170:                 }
 8171:                 $numstudents ++;
 8172:             }
 8173:         }
 8174:     }
 8175:     $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>');
 8176:     $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>');
 8177:     if ($passed) {
 8178:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 8179:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8180:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8181:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8182:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8183:                  $okstudents."\n".
 8184:                  &Apache::loncommon::end_data_table().'<br />');
 8185:     }
 8186:     if ($failed) {
 8187:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 8188:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8189:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8190:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8191:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8192:                  $badstudents."\n".
 8193:                  &Apache::loncommon::end_data_table()).'<br />'.
 8194:                  &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.');  
 8195:     }
 8196:     $r->print('</form><br />');
 8197:     return;
 8198: }
 8199: 
 8200: sub verify_scantron_grading {
 8201:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 8202:         $scantron_config,$lettdig,$numletts) = @_;
 8203:     my ($record,%expected,%startpos);
 8204:     return ($counter,$record) if (!ref($resource));
 8205:     return ($counter,$record) if (!$resource->is_problem());
 8206:     my $symb = $resource->symb();
 8207:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 8208:     foreach my $part_id (@{$partids}) {
 8209:         $counter ++;
 8210:         $expected{$part_id} = 0;
 8211:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
 8212:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
 8213:             foreach my $item (@sub_lines) {
 8214:                 $expected{$part_id} += $item;
 8215:             }
 8216:         } else {
 8217:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
 8218:         }
 8219:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 8220:     }
 8221:     if ($symb) {
 8222:         my %recorded;
 8223:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 8224:         if ($returnhash{'version'}) {
 8225:             my %lasthash=();
 8226:             my $version;
 8227:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 8228:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 8229:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 8230:                 }
 8231:             }
 8232:             foreach my $key (keys(%lasthash)) {
 8233:                 if ($key =~ /\.scantron$/) {
 8234:                     my $value = &unescape($lasthash{$key});
 8235:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 8236:                     if ($value eq '') {
 8237:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 8238:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 8239:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8240:                             }
 8241:                         }
 8242:                     } else {
 8243:                         my @tocheck;
 8244:                         my @items = split(//,$value);
 8245:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 8246:                             ($scantron_config->{'Qon'} eq 'number')) {
 8247:                             if (@items < $expected{$part_id}) {
 8248:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 8249:                                 my @singles = split(//,$fragment);
 8250:                                 foreach my $pos (@singles) {
 8251:                                     if ($pos eq ' ') {
 8252:                                         push(@tocheck,$pos);
 8253:                                     } else {
 8254:                                         my $next = shift(@items);
 8255:                                         push(@tocheck,$next);
 8256:                                     }
 8257:                                 }
 8258:                             } else {
 8259:                                 @tocheck = @items;
 8260:                             }
 8261:                             foreach my $letter (@tocheck) {
 8262:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 8263:                                     if ($letter !~ /^[A-J]$/) {
 8264:                                         $letter = $scantron_config->{'Qoff'};
 8265:                                     }
 8266:                                     $recorded{$part_id} .= $letter;
 8267:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 8268:                                     my $digit;
 8269:                                     if ($letter !~ /^[A-J]$/) {
 8270:                                         $digit = $scantron_config->{'Qoff'};
 8271:                                     } else {
 8272:                                         $digit = $lettdig->{$letter};
 8273:                                     }
 8274:                                     $recorded{$part_id} .= $digit;
 8275:                                 }
 8276:                             }
 8277:                         } else {
 8278:                             @tocheck = @items;
 8279:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 8280:                                 my $curr_sub = shift(@tocheck);
 8281:                                 my $digit;
 8282:                                 if ($curr_sub =~ /^[A-J]$/) {
 8283:                                     $digit = $lettdig->{$curr_sub}-1;
 8284:                                 }
 8285:                                 if ($curr_sub eq 'J') {
 8286:                                     $digit += scalar($numletts);
 8287:                                 }
 8288:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8289:                                     if ($j == $digit) {
 8290:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 8291:                                     } else {
 8292:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8293:                                     }
 8294:                                 }
 8295:                             }
 8296:                         }
 8297:                     }
 8298:                 }
 8299:             }
 8300:         }
 8301:         foreach my $part_id (@{$partids}) {
 8302:             if ($recorded{$part_id} eq '') {
 8303:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 8304:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8305:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8306:                     }
 8307:                 }
 8308:             }
 8309:             $record .= $recorded{$part_id};
 8310:         }
 8311:     }
 8312:     return ($counter,$record);
 8313: }
 8314: 
 8315: sub letter_to_digits { 
 8316:     my %lettdig = (
 8317:                     A => 1,
 8318:                     B => 2,
 8319:                     C => 3,
 8320:                     D => 4,
 8321:                     E => 5,
 8322:                     F => 6,
 8323:                     G => 7,
 8324:                     H => 8,
 8325:                     I => 9,
 8326:                     J => 0,
 8327:                   );
 8328:     return %lettdig;
 8329: }
 8330: 
 8331: 
 8332: #-------- end of section for handling grading scantron forms -------
 8333: #
 8334: #-------------------------------------------------------------------
 8335: 
 8336: #-------------------------- Menu interface -------------------------
 8337: #
 8338: #--- Href with symb and command ---
 8339: 
 8340: sub href_symb_cmd {
 8341:     my ($symb,$cmd)=@_;
 8342:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&command='.$cmd;
 8343: }
 8344: 
 8345: sub grading_menu {
 8346:     my ($request,$symb) = @_;
 8347:     if (!$symb) {return '';}
 8348: 
 8349:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 8350:                   'command'=>'individual');
 8351:     
 8352:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8353: 
 8354:     $fields{'command'}='ungraded';
 8355:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8356: 
 8357:     $fields{'command'}='table';
 8358:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8359: 
 8360:     $fields{'command'}='all_for_one';
 8361:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8362: 
 8363:     $fields{'command'}='downloadfilesselect';
 8364:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8365: 
 8366:     $fields{'command'} = 'csvform';
 8367:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8368:     
 8369:     $fields{'command'} = 'processclicker';
 8370:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8371:     
 8372:     $fields{'command'} = 'scantron_selectphase';
 8373:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8374: 
 8375:     $fields{'command'} = 'initialverifyreceipt';
 8376:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8377:     
 8378:     my @menu = ({	categorytitle=>'Hand Grading',
 8379:             items =>[
 8380:                         {	linktext => 'Select individual students to grade',
 8381:                     		url => $url1a,
 8382:                     		permission => 'F',
 8383:                     		icon => 'grade_students.png',
 8384:                     		linktitle => 'Grade current resource for a selection of students.'
 8385:                         }, 
 8386:                         {       linktext => 'Grade ungraded submissions.',
 8387:                                 url => $url1b,
 8388:                                 permission => 'F',
 8389:                                 icon => 'ungrade_sub.png',
 8390:                                 linktitle => 'Grade all submissions that have not been graded yet.'
 8391:                         },
 8392: 
 8393:                         {       linktext => 'Grading table',
 8394:                                 url => $url1c,
 8395:                                 permission => 'F',
 8396:                                 icon => 'grading_table.png',
 8397:                                 linktitle => 'Grade current resource for all students.'
 8398:                         },
 8399:                         {       linktext => 'Grade page/folder for one student',
 8400:                                 url => $url1d,
 8401:                                 permission => 'F',
 8402:                                 icon => 'grade_PageFolder.png',
 8403:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
 8404:                         },
 8405:                         {       linktext => 'Download submissions',
 8406:                                 url => $url1e,
 8407:                                 permission => 'F',
 8408:                                 icon => 'download_sub.png',
 8409:                                 linktitle => 'Download all students submissions.'
 8410:                         }]},
 8411:                          { categorytitle=>'Automated Grading',
 8412:                items =>[
 8413: 
 8414:                 	    {	linktext => 'Upload Scores',
 8415:                     		url => $url2,
 8416:                     		permission => 'F',
 8417:                     		icon => 'uploadscores.png',
 8418:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 8419:                 	    },
 8420:                 	    {	linktext => 'Process Clicker',
 8421:                     		url => $url3,
 8422:                     		permission => 'F',
 8423:                     		icon => 'addClickerInfoFile.png',
 8424:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 8425:                 	    },
 8426:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
 8427:                     		url => $url4,
 8428:                     		permission => 'F',
 8429:                     		icon => 'bubblesheet.png',
 8430:                     		linktitle => 'Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.'
 8431:                 	    },
 8432:                             {   linktext => 'Verify Receipt Number',
 8433:                                 url => $url5,
 8434:                                 permission => 'F',
 8435:                                 icon => 'receipt_number.png',
 8436:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
 8437:                             }
 8438: 
 8439:                     ]
 8440:             });
 8441: 
 8442:     # Create the menu
 8443:     my $Str;
 8444:     $Str .= '<form method="post" action="" name="gradingMenu">';
 8445:     $Str .= '<input type="hidden" name="command" value="" />'.
 8446:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8447: 
 8448:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
 8449:     return $Str;    
 8450: }
 8451: 
 8452: 
 8453: sub ungraded {
 8454:     my ($request)=@_;
 8455:     &submit_options($request);
 8456: }
 8457: 
 8458: sub submit_options_sequence {
 8459:     my ($request,$symb) = @_;
 8460:     if (!$symb) {return '';}
 8461:     &commonJSfunctions($request);
 8462:     my $result;
 8463: 
 8464:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8465:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8466:     $result.=&selectfield(0).
 8467:             '<input type="hidden" name="command" value="pickStudentPage" />
 8468:             <div>
 8469:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 8470:             </div>
 8471:         </div>
 8472:   </form>';
 8473:     return $result;
 8474: }
 8475: 
 8476: sub submit_options_table {
 8477:     my ($request,$symb) = @_;
 8478:     if (!$symb) {return '';}
 8479:     &commonJSfunctions($request);
 8480:     my $result;
 8481: 
 8482:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8483:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8484: 
 8485:     $result.=&selectfield(0).
 8486:             '<input type="hidden" name="command" value="viewgrades" />
 8487:             <div>
 8488:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 8489:             </div>
 8490:         </div>
 8491:   </form>';
 8492:     return $result;
 8493: }
 8494: 
 8495: sub submit_options_download {
 8496:     my ($request,$symb) = @_;
 8497:     if (!$symb) {return '';}
 8498: 
 8499:     &commonJSfunctions($request);
 8500: 
 8501:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8502:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8503:     $result.='
 8504: <h2>
 8505:   '.&mt('Select Students for Which to Download Submissions').'
 8506: </h2>'.&selectfield(1).'
 8507:                 <input type="hidden" name="command" value="downloadfileslink" /> 
 8508:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 8509:             </div>
 8510:           </div>
 8511: 
 8512: 
 8513:   </form>';
 8514:     return $result;
 8515: }
 8516: 
 8517: #--- Displays the submissions first page -------
 8518: sub submit_options {
 8519:     my ($request,$symb) = @_;
 8520:     if (!$symb) {return '';}
 8521: 
 8522:     &commonJSfunctions($request);
 8523:     my $result;
 8524: 
 8525:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8526: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8527:     $result.=&selectfield(1).'
 8528:                 <input type="hidden" name="command" value="submission" /> 
 8529: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
 8530:             </div>
 8531:           </div>
 8532: 
 8533: 
 8534:   </form>';
 8535:     return $result;
 8536: }
 8537: 
 8538: sub selectfield {
 8539:    my ($full)=@_;
 8540:    my %options = 
 8541:           (&Apache::lonlocal::texthash(
 8542:              'yes'       => 'with submissions',
 8543:              'queued'    => 'in grading queue',
 8544:              'graded'    => 'with ungraded submissions',
 8545:              'incorrect' => 'with incorrect submissions',
 8546:              'all'       => 'with any status'),
 8547:              'select_form_order' => ['yes','queued','graded','incorrect','all']);
 8548:    my $result='<div class="LC_columnSection">
 8549:   
 8550:     <fieldset>
 8551:       <legend>
 8552:        '.&mt('Sections').'
 8553:       </legend>
 8554:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
 8555:     </fieldset>
 8556:   
 8557:     <fieldset>
 8558:       <legend>
 8559:         '.&mt('Groups').'
 8560:       </legend>
 8561:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 8562:     </fieldset>
 8563:   
 8564:     <fieldset>
 8565:       <legend>
 8566:         '.&mt('Access Status').'
 8567:       </legend>
 8568:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
 8569:     </fieldset>';
 8570:     if ($full) {
 8571:        $result.='
 8572:     <fieldset>
 8573:       <legend>
 8574:         '.&mt('Submission Status').'
 8575:       </legend>'.
 8576:        &Apache::loncommon::select_form('all','submitonly',\%options).
 8577:    '</fieldset>';
 8578:     }
 8579:     $result.='</div><br />';
 8580:     return $result;
 8581: }
 8582: 
 8583: sub reset_perm {
 8584:     undef(%perm);
 8585: }
 8586: 
 8587: sub init_perm {
 8588:     &reset_perm();
 8589:     foreach my $test_perm ('vgr','mgr','opa') {
 8590: 
 8591: 	my $scope = $env{'request.course.id'};
 8592: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 8593: 
 8594: 	    $scope .= '/'.$env{'request.course.sec'};
 8595: 	    if ( $perm{$test_perm}=
 8596: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 8597: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 8598: 	    } else {
 8599: 		delete($perm{$test_perm});
 8600: 	    }
 8601: 	}
 8602:     }
 8603: }
 8604: 
 8605: sub gather_clicker_ids {
 8606:     my %clicker_ids;
 8607: 
 8608:     my $classlist = &Apache::loncoursedata::get_classlist();
 8609: 
 8610:     # Set up a couple variables.
 8611:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 8612:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 8613:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 8614: 
 8615:     foreach my $student (keys(%$classlist)) {
 8616:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 8617:         my $username = $classlist->{$student}->[$username_idx];
 8618:         my $domain   = $classlist->{$student}->[$domain_idx];
 8619:         my $clickers =
 8620: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 8621:         foreach my $id (split(/\,/,$clickers)) {
 8622:             $id=~s/^[\#0]+//;
 8623:             $id=~s/[\-\:]//g;
 8624:             if (exists($clicker_ids{$id})) {
 8625: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 8626:             } else {
 8627: 		$clicker_ids{$id}=$username.':'.$domain;
 8628:             }
 8629:         }
 8630:     }
 8631:     return %clicker_ids;
 8632: }
 8633: 
 8634: sub gather_adv_clicker_ids {
 8635:     my %clicker_ids;
 8636:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 8637:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8638:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 8639:     foreach my $element (sort(keys(%coursepersonnel))) {
 8640:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 8641:             my ($puname,$pudom)=split(/\:/,$person);
 8642:             my $clickers =
 8643: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 8644:             foreach my $id (split(/\,/,$clickers)) {
 8645: 		$id=~s/^[\#0]+//;
 8646:                 $id=~s/[\-\:]//g;
 8647: 		if (exists($clicker_ids{$id})) {
 8648: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 8649: 		} else {
 8650: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 8651: 		}
 8652:             }
 8653:         }
 8654:     }
 8655:     return %clicker_ids;
 8656: }
 8657: 
 8658: sub clicker_grading_parameters {
 8659:     return ('gradingmechanism' => 'scalar',
 8660:             'upfiletype' => 'scalar',
 8661:             'specificid' => 'scalar',
 8662:             'pcorrect' => 'scalar',
 8663:             'pincorrect' => 'scalar');
 8664: }
 8665: 
 8666: sub process_clicker {
 8667:     my ($r,$symb)=@_;
 8668:     if (!$symb) {return '';}
 8669:     my $result=&checkforfile_js();
 8670:     $result.=&Apache::loncommon::start_data_table().
 8671:              &Apache::loncommon::start_data_table_header_row().
 8672:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
 8673:              &Apache::loncommon::end_data_table_header_row().
 8674:              &Apache::loncommon::start_data_table_row()."<td>\n";
 8675: # Attempt to restore parameters from last session, set defaults if not present
 8676:     my %Saveable_Parameters=&clicker_grading_parameters();
 8677:     &Apache::loncommon::restore_course_settings('grades_clicker',
 8678:                                                  \%Saveable_Parameters);
 8679:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 8680:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 8681:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 8682:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 8683: 
 8684:     my %checked;
 8685:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 8686:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 8687:           $checked{$gradingmechanism}=' checked="checked"';
 8688:        }
 8689:     }
 8690: 
 8691:     my $upload=&mt("Evaluate File");
 8692:     my $type=&mt("Type");
 8693:     my $attendance=&mt("Award points just for participation");
 8694:     my $personnel=&mt("Correctness determined from response by course personnel");
 8695:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 8696:     my $given=&mt("Correctness determined from given list of answers").' '.
 8697:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 8698:     my $pcorrect=&mt("Percentage points for correct solution");
 8699:     my $pincorrect=&mt("Percentage points for incorrect solution");
 8700:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 8701: 						   {'iclicker' => 'i>clicker',
 8702:                                                     'interwrite' => 'interwrite PRS'});
 8703:     $symb = &Apache::lonenc::check_encrypt($symb);
 8704:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
 8705: function sanitycheck() {
 8706: // Accept only integer percentages
 8707:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 8708:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 8709: // Find out grading choice
 8710:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8711:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 8712:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 8713:       }
 8714:    }
 8715: // By default, new choice equals user selection
 8716:    newgradingchoice=gradingchoice;
 8717: // Not good to give more points for false answers than correct ones
 8718:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 8719:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 8720:    }
 8721: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 8722:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 8723:       document.forms.gradesupload.pcorrect.value=100;
 8724:       document.forms.gradesupload.pincorrect.value=100;
 8725:    }
 8726: // If the values are different, cannot be attendance only
 8727:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 8728:        (gradingchoice=='attendance')) {
 8729:        newgradingchoice='personnel';
 8730:    }
 8731: // Change grading choice to new one
 8732:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8733:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 8734:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 8735:       } else {
 8736:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 8737:       }
 8738:    }
 8739: // Remember the old state
 8740:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 8741: }
 8742: ENDUPFORM
 8743:     $result.= <<ENDUPFORM;
 8744: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 8745: <input type="hidden" name="symb" value="$symb" />
 8746: <input type="hidden" name="command" value="processclickerfile" />
 8747: <input type="file" name="upfile" size="50" />
 8748: <br /><label>$type: $selectform</label>
 8749: ENDUPFORM
 8750:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
 8751:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
 8752:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
 8753: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
 8754: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
 8755: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 8756: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
 8757: <br />&nbsp;&nbsp;&nbsp;
 8758: <input type="text" name="givenanswer" size="50" />
 8759: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 8760: ENDGRADINGFORM
 8761:          $result.='</td>'.&Apache::loncommon::end_data_table_row().
 8762:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
 8763:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
 8764: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
 8765: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 8766: </form>'
 8767: ENDPERCFORM
 8768:     $result.='</td>'.
 8769:              &Apache::loncommon::end_data_table_row().
 8770:              &Apache::loncommon::end_data_table();
 8771:     return $result;
 8772: }
 8773: 
 8774: sub process_clicker_file {
 8775:     my ($r,$symb)=@_;
 8776:     if (!$symb) {return '';}
 8777: 
 8778:     my %Saveable_Parameters=&clicker_grading_parameters();
 8779:     &Apache::loncommon::store_course_settings('grades_clicker',
 8780:                                               \%Saveable_Parameters);
 8781:     my $result='';
 8782:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 8783: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 8784: 	return $result;
 8785:     }
 8786:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 8787:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 8788:         return $result;
 8789:     }
 8790:     my $foundgiven=0;
 8791:     if ($env{'form.gradingmechanism'} eq 'given') {
 8792:         $env{'form.givenanswer'}=~s/^\s*//gs;
 8793:         $env{'form.givenanswer'}=~s/\s*$//gs;
 8794:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
 8795:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 8796:         my @answers=split(/\,/,$env{'form.givenanswer'});
 8797:         $foundgiven=$#answers+1;
 8798:     }
 8799:     my %clicker_ids=&gather_clicker_ids();
 8800:     my %correct_ids;
 8801:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 8802: 	%correct_ids=&gather_adv_clicker_ids();
 8803:     }
 8804:     if ($env{'form.gradingmechanism'} eq 'specific') {
 8805: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 8806: 	   $correct_id=~tr/a-z/A-Z/;
 8807: 	   $correct_id=~s/\s//gs;
 8808: 	   $correct_id=~s/^[\#0]+//;
 8809:            $correct_id=~s/[\-\:]//g;
 8810:            if ($correct_id) {
 8811: 	      $correct_ids{$correct_id}='specified';
 8812:            }
 8813:         }
 8814:     }
 8815:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 8816: 	$result.=&mt('Score based on attendance only');
 8817:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
 8818:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
 8819:     } else {
 8820: 	my $number=0;
 8821: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 8822: 	foreach my $id (sort(keys(%correct_ids))) {
 8823: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 8824: 	    if ($correct_ids{$id} eq 'specified') {
 8825: 		$result.=&mt('specified');
 8826: 	    } else {
 8827: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 8828: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 8829: 	    }
 8830: 	    $number++;
 8831: 	}
 8832:         $result.="</p>\n";
 8833: 	if ($number==0) {
 8834: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
 8835: 	    return $result;
 8836: 	}
 8837:     }
 8838:     if (length($env{'form.upfile'}) < 2) {
 8839:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
 8840: 		     '<span class="LC_error">',
 8841: 		     '</span>',
 8842: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
 8843:         return $result;
 8844:     }
 8845: 
 8846: # Were able to get all the info needed, now analyze the file
 8847: 
 8848:     $result.=&Apache::loncommon::studentbrowser_javascript();
 8849:     $symb = &Apache::lonenc::check_encrypt($symb);
 8850:     $result.=&Apache::loncommon::start_data_table().
 8851:              &Apache::loncommon::start_data_table_header_row().
 8852:              '<th>'.&mt('Evaluate clicker file').'</th>'.
 8853:              &Apache::loncommon::end_data_table_header_row().
 8854:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
 8855: <td>
 8856: <form method="post" action="/adm/grades" name="clickeranalysis">
 8857: <input type="hidden" name="symb" value="$symb" />
 8858: <input type="hidden" name="command" value="assignclickergrades" />
 8859: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 8860: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 8861: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 8862: ENDHEADER
 8863:     if ($env{'form.gradingmechanism'} eq 'given') {
 8864:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
 8865:     } 
 8866:     my %responses;
 8867:     my @questiontitles;
 8868:     my $errormsg='';
 8869:     my $number=0;
 8870:     if ($env{'form.upfiletype'} eq 'iclicker') {
 8871: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 8872:     }
 8873:     if ($env{'form.upfiletype'} eq 'interwrite') {
 8874:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 8875:     }
 8876:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 8877:              '<input type="hidden" name="number" value="'.$number.'" />'.
 8878:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 8879:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 8880:              '<br />';
 8881:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
 8882:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
 8883:        return $result;
 8884:     } 
 8885: # Remember Question Titles
 8886: # FIXME: Possibly need delimiter other than ":"
 8887:     for (my $i=0;$i<$number;$i++) {
 8888:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 8889:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 8890:     }
 8891:     my $correct_count=0;
 8892:     my $student_count=0;
 8893:     my $unknown_count=0;
 8894: # Match answers with usernames
 8895: # FIXME: Possibly need delimiter other than ":"
 8896:     foreach my $id (keys(%responses)) {
 8897:        if ($correct_ids{$id}) {
 8898:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 8899:           $correct_count++;
 8900:        } elsif ($clicker_ids{$id}) {
 8901:           if ($clicker_ids{$id}=~/\,/) {
 8902: # More than one user with the same clicker!
 8903:              $result.="</td>".&Apache::loncommon::end_data_table_row().
 8904:                            &Apache::loncommon::start_data_table_row()."<td>".
 8905:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 8906:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 8907:                            "<select name='multi".$id."'>";
 8908:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 8909:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 8910:              }
 8911:              $result.='</select>';
 8912:              $unknown_count++;
 8913:           } else {
 8914: # Good: found one and only one user with the right clicker
 8915:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 8916:              $student_count++;
 8917:           }
 8918:        } else {
 8919:           $result.="</td>".&Apache::loncommon::end_data_table_row().
 8920:                            &Apache::loncommon::start_data_table_row()."<td>".
 8921:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 8922:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 8923:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 8924:                    "\n".&mt("Domain").": ".
 8925:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 8926:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
 8927:           $unknown_count++;
 8928:        }
 8929:     }
 8930:     $result.='<hr />'.
 8931:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 8932:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
 8933:        if ($correct_count==0) {
 8934:           $errormsg.="Found no correct answers answers for grading!";
 8935:        } elsif ($correct_count>1) {
 8936:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 8937:        }
 8938:     }
 8939:     if ($number<1) {
 8940:        $errormsg.="Found no questions.";
 8941:     }
 8942:     if ($errormsg) {
 8943:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 8944:     } else {
 8945:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 8946:     }
 8947:     $result.='</form></td>'.
 8948:              &Apache::loncommon::end_data_table_row().
 8949:              &Apache::loncommon::end_data_table();
 8950:     return $result;
 8951: }
 8952: 
 8953: sub iclicker_eval {
 8954:     my ($questiontitles,$responses)=@_;
 8955:     my $number=0;
 8956:     my $errormsg='';
 8957:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 8958:         my %components=&Apache::loncommon::record_sep($line);
 8959:         my @entries=map {$components{$_}} (sort(keys(%components)));
 8960: 	if ($entries[0] eq 'Question') {
 8961: 	    for (my $i=3;$i<$#entries;$i+=6) {
 8962: 		$$questiontitles[$number]=$entries[$i];
 8963: 		$number++;
 8964: 	    }
 8965: 	}
 8966: 	if ($entries[0]=~/^\#/) {
 8967: 	    my $id=$entries[0];
 8968: 	    my @idresponses;
 8969: 	    $id=~s/^[\#0]+//;
 8970: 	    for (my $i=0;$i<$number;$i++) {
 8971: 		my $idx=3+$i*6;
 8972: 		push(@idresponses,$entries[$idx]);
 8973: 	    }
 8974: 	    $$responses{$id}=join(',',@idresponses);
 8975: 	}
 8976:     }
 8977:     return ($errormsg,$number);
 8978: }
 8979: 
 8980: sub interwrite_eval {
 8981:     my ($questiontitles,$responses)=@_;
 8982:     my $number=0;
 8983:     my $errormsg='';
 8984:     my $skipline=1;
 8985:     my $questionnumber=0;
 8986:     my %idresponses=();
 8987:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 8988:         my %components=&Apache::loncommon::record_sep($line);
 8989:         my @entries=map {$components{$_}} (sort(keys(%components)));
 8990:         if ($entries[1] eq 'Time') { $skipline=0; next; }
 8991:         if ($entries[1] eq 'Response') { $skipline=1; }
 8992:         next if $skipline;
 8993:         if ($entries[0]!=$questionnumber) {
 8994:            $questionnumber=$entries[0];
 8995:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
 8996:            $number++;
 8997:         }
 8998:         my $id=$entries[4];
 8999:         $id=~s/^[\#0]+//;
 9000:         $id=~s/^v\d*\://i;
 9001:         $id=~s/[\-\:]//g;
 9002:         $idresponses{$id}[$number]=$entries[6];
 9003:     }
 9004:     foreach my $id (keys(%idresponses)) {
 9005:        $$responses{$id}=join(',',@{$idresponses{$id}});
 9006:        $$responses{$id}=~s/^\s*\,//;
 9007:     }
 9008:     return ($errormsg,$number);
 9009: }
 9010: 
 9011: sub assign_clicker_grades {
 9012:     my ($r,$symb)=@_;
 9013:     if (!$symb) {return '';}
 9014: # See which part we are saving to
 9015:     my $res_error;
 9016:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 9017:     if ($res_error) {
 9018:         return &navmap_errormsg();
 9019:     }
 9020: # FIXME: This should probably look for the first handgradeable part
 9021:     my $part=$$partlist[0];
 9022: # Start screen output
 9023:     my $result=&Apache::loncommon::start_data_table().
 9024:              &Apache::loncommon::start_data_table_header_row().
 9025:              '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
 9026:              &Apache::loncommon::end_data_table_header_row().
 9027:              &Apache::loncommon::start_data_table_row().'<td>';
 9028: # Get correct result
 9029: # FIXME: Possibly need delimiter other than ":"
 9030:     my @correct=();
 9031:     my $gradingmechanism=$env{'form.gradingmechanism'};
 9032:     my $number=$env{'form.number'};
 9033:     if ($gradingmechanism ne 'attendance') {
 9034:        foreach my $key (keys(%env)) {
 9035:           if ($key=~/^form\.correct\:/) {
 9036:              my @input=split(/\,/,$env{$key});
 9037:              for (my $i=0;$i<=$#input;$i++) {
 9038:                  if (($correct[$i]) && ($input[$i]) &&
 9039:                      ($correct[$i] ne $input[$i])) {
 9040:                     $result.='<br /><span class="LC_warning">'.
 9041:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
 9042:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
 9043:                  } elsif ($input[$i]) {
 9044:                     $correct[$i]=$input[$i];
 9045:                  }
 9046:              }
 9047:           }
 9048:        }
 9049:        for (my $i=0;$i<$number;$i++) {
 9050:           if (!$correct[$i]) {
 9051:              $result.='<br /><span class="LC_error">'.
 9052:                       &mt('No correct result given for question "[_1]"!',
 9053:                           $env{'form.question:'.$i}).'</span>';
 9054:           }
 9055:        }
 9056:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
 9057:     }
 9058: # Start grading
 9059:     my $pcorrect=$env{'form.pcorrect'};
 9060:     my $pincorrect=$env{'form.pincorrect'};
 9061:     my $storecount=0;
 9062:     my %users=();
 9063:     foreach my $key (keys(%env)) {
 9064:        my $user='';
 9065:        if ($key=~/^form\.student\:(.*)$/) {
 9066:           $user=$1;
 9067:        }
 9068:        if ($key=~/^form\.unknown\:(.*)$/) {
 9069:           my $id=$1;
 9070:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
 9071:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
 9072:           } elsif ($env{'form.multi'.$id}) {
 9073:              $user=$env{'form.multi'.$id};
 9074:           }
 9075:        }
 9076:        if ($user) {
 9077:           if ($users{$user}) {
 9078:              $result.='<br /><span class="LC_warning">'.
 9079:                       &mt("More than one entry found for <tt>[_1]</tt>!",$user).
 9080:                       '</span><br />';
 9081:           }
 9082:           $users{$user}=1; 
 9083:           my @answer=split(/\,/,$env{$key});
 9084:           my $sum=0;
 9085:           my $realnumber=$number;
 9086:           for (my $i=0;$i<$number;$i++) {
 9087:              if  ($correct[$i] eq '-') {
 9088:                 $realnumber--;
 9089:              } elsif ($answer[$i]) {
 9090:                 if ($gradingmechanism eq 'attendance') {
 9091:                    $sum+=$pcorrect;
 9092:                 } elsif ($correct[$i] eq '*') {
 9093:                    $sum+=$pcorrect;
 9094:                 } else {
 9095:                    if ($answer[$i] eq $correct[$i]) {
 9096:                       $sum+=$pcorrect;
 9097:                    } else {
 9098:                       $sum+=$pincorrect;
 9099:                    }
 9100:                 }
 9101:              }
 9102:           }
 9103:           my $ave=$sum/(100*$realnumber);
 9104: # Store
 9105:           my ($username,$domain)=split(/\:/,$user);
 9106:           my %grades=();
 9107:           $grades{"resource.$part.solved"}='correct_by_override';
 9108:           $grades{"resource.$part.awarded"}=$ave;
 9109:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 9110:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
 9111:                                                  $env{'request.course.id'},
 9112:                                                  $domain,$username);
 9113:           if ($returncode ne 'ok') {
 9114:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
 9115:           } else {
 9116:              $storecount++;
 9117:           }
 9118:        }
 9119:     }
 9120: # We are done
 9121:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
 9122:              '</td>'.
 9123:              &Apache::loncommon::end_data_table_row().
 9124:              &Apache::loncommon::end_data_table();
 9125:     return $result;
 9126: }
 9127: 
 9128: sub navmap_errormsg {
 9129:     return '<div class="LC_error">'.
 9130:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
 9131:            &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>').
 9132:            '</div>';
 9133: }
 9134: 
 9135: sub startpage {
 9136:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag) = @_;
 9137:     unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
 9138:     $r->print(&Apache::loncommon::start_page('Grading',undef,
 9139:                                           {'bread_crumbs' => $crumbs}));
 9140:     $r->print('<h3>'.$$crumbs[-1]{'text'}.'</h3>');
 9141:     unless ($nodisplayflag) {
 9142:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag));
 9143:     }
 9144: }
 9145: 
 9146: sub select_problem {
 9147:     my ($r)=@_;
 9148:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
 9149:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1));
 9150:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
 9151:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
 9152: }
 9153: 
 9154: sub handler {
 9155:     my $request=$_[0];
 9156:     &reset_caches();
 9157:     if ($env{'browser.mathml'}) {
 9158: 	&Apache::loncommon::content_type($request,'text/xml');
 9159:     } else {
 9160: 	&Apache::loncommon::content_type($request,'text/html');
 9161:     }
 9162:     $request->send_http_header;
 9163:     return '' if $request->header_only;
 9164:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
 9165: 
 9166: # see what command we need to execute
 9167: 
 9168:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
 9169:     my $command=$commands[0];
 9170: 
 9171:     if ($#commands > 0) {
 9172: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
 9173:     }
 9174: 
 9175: # see what the symb is
 9176: 
 9177:     my $symb=$env{'form.symb'};
 9178:     unless ($symb) {
 9179:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
 9180:        $symb=&Apache::lonnet::symbread($url);
 9181:     }
 9182:     &Apache::lonenc::check_decrypt(\$symb);                             
 9183: 
 9184:     $ssi_error = 0;
 9185:     if ($symb eq '' || $command eq '') {
 9186: #
 9187: # Not called from a resource
 9188: #    
 9189:         &startpage($request,undef,[],1,1);
 9190:         &select_problem($request);
 9191:     } else {
 9192: 	&init_perm();
 9193: 	if ($command eq 'submission' && $perm{'vgr'}) {
 9194:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}]);
 9195: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
 9196: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
 9197:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
 9198:                                        {href=>'',text=>'Select student'}],1,1);
 9199: 	    &pickStudentPage($request,$symb);
 9200: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
 9201:             &startpage($request,$symb,
 9202:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
 9203:                                        {href=>'',text=>'Select student'},
 9204:                                        {href=>'',text=>'Grade student'}],1,1);
 9205: 	    &displayPage($request,$symb);
 9206: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
 9207:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
 9208:                                        {href=>'',text=>'Select student'},
 9209:                                        {href=>'',text=>'Grade student'},
 9210:                                        {href=>'',text=>'Store grades'}],1,1);
 9211: 	    &updateGradeByPage($request,$symb);
 9212: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
 9213:             &startpage($request,$symb,[{href=>'',text=>'...'},
 9214:                                        {href=>'',text=>'Modify grades'}]);
 9215: 	    &processGroup($request,$symb);
 9216: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
 9217:             &startpage($request,$symb);
 9218: 	    $request->print(&grading_menu($request,$symb));
 9219: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
 9220:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
 9221: 	    $request->print(&submit_options($request,$symb));
 9222:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
 9223:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
 9224:             $request->print(&listStudents($request,$symb,'graded'));
 9225:         } elsif ($command eq 'table' && $perm{'vgr'}) {
 9226:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
 9227:             $request->print(&submit_options_table($request,$symb));
 9228:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
 9229:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
 9230:             $request->print(&submit_options_sequence($request,$symb));
 9231: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
 9232:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
 9233: 	    $request->print(&viewgrades($request,$symb));
 9234: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
 9235:             &startpage($request,$symb,[{href=>'',text=>'...'},
 9236:                                        {href=>'',text=>'Store grades'}]);
 9237: 	    $request->print(&processHandGrade($request,$symb));
 9238: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
 9239:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
 9240:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
 9241:                                                                              text=>"Modify grades"},
 9242:                                        {href=>'', text=>"Store grades"}]);
 9243: 	    $request->print(&editgrades($request,$symb));
 9244:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
 9245:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
 9246:             $request->print(&initialverifyreceipt($request,$symb));
 9247: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
 9248:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
 9249:                                        {href=>'',text=>'Verification Result'}]);
 9250: 	    $request->print(&verifyreceipt($request,$symb));
 9251:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
 9252:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
 9253:             $request->print(&process_clicker($request,$symb));
 9254:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
 9255:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
 9256:                                        {href=>'', text=>'Process clicker file'}]);
 9257:             $request->print(&process_clicker_file($request,$symb));
 9258:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
 9259:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
 9260:                                        {href=>'', text=>'Process clicker file'},
 9261:                                        {href=>'', text=>'Store grades'}]);
 9262:             $request->print(&assign_clicker_grades($request,$symb));
 9263: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
 9264:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
 9265: 	    $request->print(&upcsvScores_form($request,$symb));
 9266: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
 9267:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
 9268: 	    $request->print(&csvupload($request,$symb));
 9269: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
 9270:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
 9271: 	    $request->print(&csvuploadmap($request,$symb));
 9272: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
 9273: 	    if ($env{'form.associate'} ne 'Reverse Association') {
 9274:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
 9275: 		$request->print(&csvuploadoptions($request,$symb));
 9276: 	    } else {
 9277: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
 9278: 		    $env{'form.upfile_associate'} = 'reverse';
 9279: 		} else {
 9280: 		    $env{'form.upfile_associate'} = 'forward';
 9281: 		}
 9282:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
 9283: 		$request->print(&csvuploadmap($request,$symb));
 9284: 	    }
 9285: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
 9286:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
 9287: 	    $request->print(&csvuploadassign($request,$symb));
 9288: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
 9289:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9290: 	    $request->print(&scantron_selectphase($request,undef,$symb));
 9291:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
 9292:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9293:  	    $request->print(&scantron_do_warning($request,$symb));
 9294: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
 9295:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9296: 	    $request->print(&scantron_validate_file($request,$symb));
 9297: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
 9298:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9299: 	    $request->print(&scantron_process_students($request,$symb));
 9300:  	} elsif ($command eq 'scantronupload' && 
 9301:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9302: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9303:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9304:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
 9305:  	} elsif ($command eq 'scantronupload_save' &&
 9306:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9307: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9308:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9309:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
 9310:  	} elsif ($command eq 'scantron_download' &&
 9311: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 9312:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9313:  	    $request->print(&scantron_download_scantron_data($request,$symb));
 9314:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
 9315:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9316:             $request->print(&checkscantron_results($request,$symb));
 9317:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
 9318:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
 9319:             $request->print(&submit_options_download($request,$symb));
 9320:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
 9321:             &startpage($request,$symb,
 9322:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
 9323:     {href=>'', text=>'Download submissions'}]);
 9324:             &submit_download_link($request,$symb);
 9325: 	} elsif ($command) {
 9326:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
 9327: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
 9328: 	}
 9329:     }
 9330:     if ($ssi_error) {
 9331: 	&ssi_print_error($request);
 9332:     }
 9333:     $request->print(&Apache::loncommon::end_page());
 9334:     &reset_caches();
 9335:     return '';
 9336: }
 9337: 
 9338: 1;
 9339: 
 9340: __END__;
 9341: 
 9342: 
 9343: =head1 NAME
 9344: 
 9345: Apache::grades
 9346: 
 9347: =head1 SYNOPSIS
 9348: 
 9349: Handles the viewing of grades.
 9350: 
 9351: This is part of the LearningOnline Network with CAPA project
 9352: described at http://www.lon-capa.org.
 9353: 
 9354: =head1 OVERVIEW
 9355: 
 9356: Do an ssi with retries:
 9357: While I'd love to factor out this with the vesrion in lonprintout,
 9358: 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
 9359: I'm not quite ready to invent (e.g. an ssi_with_retry object).
 9360: 
 9361: At least the logic that drives this has been pulled out into loncommon.
 9362: 
 9363: 
 9364: 
 9365: ssi_with_retries - Does the server side include of a resource.
 9366:                      if the ssi call returns an error we'll retry it up to
 9367:                      the number of times requested by the caller.
 9368:                      If we still have a proble, no text is appended to the
 9369:                      output and we set some global variables.
 9370:                      to indicate to the caller an SSI error occurred.  
 9371:                      All of this is supposed to deal with the issues described
 9372:                      in LonCAPA BZ 5631 see:
 9373:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
 9374:                      by informing the user that this happened.
 9375: 
 9376: Parameters:
 9377:   resource   - The resource to include.  This is passed directly, without
 9378:                interpretation to lonnet::ssi.
 9379:   form       - The form hash parameters that guide the interpretation of the resource
 9380:                
 9381:   retries    - Number of retries allowed before giving up completely.
 9382: Returns:
 9383:   On success, returns the rendered resource identified by the resource parameter.
 9384: Side Effects:
 9385:   The following global variables can be set:
 9386:    ssi_error                - If an unrecoverable error occurred this becomes true.
 9387:                               It is up to the caller to initialize this to false
 9388:                               if desired.
 9389:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
 9390:                               of the resource that could not be rendered by the ssi
 9391:                               call.
 9392:    ssi_error_message   - The error string fetched from the ssi response
 9393:                               in the event of an error.
 9394: 
 9395: 
 9396: =head1 HANDLER SUBROUTINE
 9397: 
 9398: ssi_with_retries()
 9399: 
 9400: =head1 SUBROUTINES
 9401: 
 9402: =over
 9403: 
 9404: =item scantron_get_correction() : 
 9405: 
 9406:    Builds the interface screen to interact with the operator to fix a
 9407:    specific error condition in a specific scanline
 9408: 
 9409:  Arguments:
 9410:     $r           - Apache request object
 9411:     $i           - number of the current scanline
 9412:     $scan_record - hash ref as returned from &scantron_parse_scanline()
 9413:     $scan_config - hash ref as returned from &get_scantron_config()
 9414:     $line        - full contents of the current scanline
 9415:     $error       - error condition, valid values are
 9416:                    'incorrectCODE', 'duplicateCODE',
 9417:                    'doublebubble', 'missingbubble',
 9418:                    'duplicateID', 'incorrectID'
 9419:     $arg         - extra information needed
 9420:        For errors:
 9421:          - duplicateID   - paper number that this studentID was seen before on
 9422:          - duplicateCODE - array ref of the paper numbers this CODE was
 9423:                            seen on before
 9424:          - incorrectCODE - current incorrect CODE 
 9425:          - doublebubble  - array ref of the bubble lines that have double
 9426:                            bubble errors
 9427:          - missingbubble - array ref of the bubble lines that have missing
 9428:                            bubble errors
 9429: 
 9430: =item  scantron_get_maxbubble() : 
 9431: 
 9432:    Arguments:
 9433:        $nav_error  - Reference to scalar which is a flag to indicate a
 9434:                       failure to retrieve a navmap object.
 9435:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
 9436:        calling routine should trap the error condition and display the warning
 9437:        found in &navmap_errormsg().
 9438: 
 9439:    Returns the maximum number of bubble lines that are expected to
 9440:    occur. Does this by walking the selected sequence rendering the
 9441:    resource and then checking &Apache::lonxml::get_problem_counter()
 9442:    for what the current value of the problem counter is.
 9443: 
 9444:    Caches the results to $env{'form.scantron_maxbubble'},
 9445:    $env{'form.scantron.bubble_lines.n'}, 
 9446:    $env{'form.scantron.first_bubble_line.n'} and
 9447:    $env{"form.scantron.sub_bubblelines.n"}
 9448:    which are the total number of bubble, lines, the number of bubble
 9449:    lines for response n and number of the first bubble line for response n,
 9450:    and a comma separated list of numbers of bubble lines for sub-questions
 9451:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
 9452: 
 9453: 
 9454: =item  scantron_validate_missingbubbles() : 
 9455: 
 9456:    Validates all scanlines in the selected file to not have any
 9457:     answers that don't have bubbles that have not been verified
 9458:     to be bubble free.
 9459: 
 9460: =item  scantron_process_students() : 
 9461: 
 9462:    Routine that does the actual grading of the bubble sheet information.
 9463: 
 9464:    The parsed scanline hash is added to %env 
 9465: 
 9466:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
 9467:    foreach resource , with the form data of
 9468: 
 9469: 	'submitted'     =>'scantron' 
 9470: 	'grade_target'  =>'grade',
 9471: 	'grade_username'=> username of student
 9472: 	'grade_domain'  => domain of student
 9473: 	'grade_courseid'=> of course
 9474: 	'grade_symb'    => symb of resource to grade
 9475: 
 9476:     This triggers a grading pass. The problem grading code takes care
 9477:     of converting the bubbled letter information (now in %env) into a
 9478:     valid submission.
 9479: 
 9480: =item  scantron_upload_scantron_data() :
 9481: 
 9482:     Creates the screen for adding a new bubble sheet data file to a course.
 9483: 
 9484: =item  scantron_upload_scantron_data_save() : 
 9485: 
 9486:    Adds a provided bubble information data file to the course if user
 9487:    has the correct privileges to do so. 
 9488: 
 9489: =item  valid_file() :
 9490: 
 9491:    Validates that the requested bubble data file exists in the course.
 9492: 
 9493: =item  scantron_download_scantron_data() : 
 9494: 
 9495:    Shows a list of the three internal files (original, corrected,
 9496:    skipped) for a specific bubble sheet data file that exists in the
 9497:    course.
 9498: 
 9499: =item  scantron_validate_ID() : 
 9500: 
 9501:    Validates all scanlines in the selected file to not have any
 9502:    invalid or underspecified student/employee IDs
 9503: 
 9504: =item navmap_errormsg() :
 9505: 
 9506:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
 9507:    Should be called whenever the request to instantiate a navmap object fails.  
 9508: 
 9509: =back
 9510: 
 9511: =cut

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