File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.632: download - view: text, annotated - select for diffs
Tue Apr 27 00:06:34 2010 UTC (14 years, 1 month ago) by www
Branches: MAIN
CVS tags: HEAD
Standard tables
Standardize page headers
Internationalization
Detect double data on clickers (after assignment of unknown clickers)

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.632 2010/04/27 00:06:34 www Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: 
   30: 
   31: package Apache::grades;
   32: use strict;
   33: use Apache::style;
   34: use Apache::lonxml;
   35: use Apache::lonnet;
   36: use Apache::loncommon;
   37: use Apache::lonhtmlcommon;
   38: use Apache::lonnavmaps;
   39: use Apache::lonhomework;
   40: use Apache::lonpickcode;
   41: use Apache::loncoursedata;
   42: use Apache::lonmsg();
   43: use Apache::Constants qw(:common);
   44: use Apache::lonlocal;
   45: use Apache::lonenc;
   46: use 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: 	if (val == "Grade Student") {
 1271: 	    if (formname.Status.value == "") {
 1272: 		formname.Status.value = "Active";
 1273: 	    }
 1274: 	    formname.studentNo.value = total;
 1275: 	}
 1276: 	formname.submit();
 1277:     }
 1278: 
 1279: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1280:     function checkSubmitPage(formname,total) {
 1281: 	noscore = new Array(100);
 1282: 	var ptr = 0;
 1283: 	for (i=1;i<total;i++) {
 1284: 	    var partid = formname["q_"+i].value;
 1285: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1286: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1287: 		var status = formname["solved"+i+"_"+partid].value;
 1288: 		if (points == "" && status != "correct_by_student") {
 1289: 		    noscore[ptr] = i;
 1290: 		    ptr++;
 1291: 		}
 1292: 	    }
 1293: 	}
 1294: 	if (ptr != 0) {
 1295: 	    var sense = ptr == 1 ? ": " : "s: ";
 1296: 	    var prolist = "";
 1297: 	    if (ptr == 1) {
 1298: 		prolist = noscore[0];
 1299: 	    } else {
 1300: 		var i = 0;
 1301: 		while (i < ptr-1) {
 1302: 		    prolist += noscore[i]+", ";
 1303: 		    i++;
 1304: 		}
 1305: 		prolist += "and "+noscore[i];
 1306: 	    }
 1307: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1308: 	    if (resp == false) {
 1309: 		return false;
 1310: 	    }
 1311: 	}
 1312: 
 1313: 	formname.submit();
 1314:     }
 1315: SUBJAVASCRIPT
 1316: }
 1317: 
 1318: #--- javascript for essay type problem --
 1319: sub sub_page_kw_js {
 1320:     my $request = shift;
 1321:     my $iconpath = $request->dir_config('lonIconsURL');
 1322:     &commonJSfunctions($request);
 1323: 
 1324:     my $inner_js_msg_central= (<<INNERJS);
 1325: <script type="text/javascript">
 1326:     function checkInput() {
 1327:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1328:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1329:       var usrctr = document.msgcenter.usrctr.value;
 1330:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1331:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1332: 
 1333:       var msgchk = "";
 1334:       if (document.msgcenter.subchk.checked) {
 1335:          msgchk = "msgsub,";
 1336:       }
 1337:       var includemsg = 0;
 1338:       for (var i=1; i<=nmsg; i++) {
 1339:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1340:           var frmmsg = document.msgcenter["msg"+i];
 1341:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1342:           var showflg = opener.document.SCORE["shownOnce"+i];
 1343:           showflg.value = "1";
 1344:           var chkbox = document.msgcenter["msgn"+i];
 1345:           if (chkbox.checked) {
 1346:              msgchk += "savemsg"+i+",";
 1347:              includemsg = 1;
 1348:           }
 1349:       }
 1350:       if (document.msgcenter.newmsgchk.checked) {
 1351:          msgchk += "newmsg"+usrctr;
 1352:          includemsg = 1;
 1353:       }
 1354:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1355:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1356:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1357:       includemsg.value = msgchk;
 1358: 
 1359:       self.close()
 1360: 
 1361:     }
 1362: </script>
 1363: INNERJS
 1364: 
 1365:     my $inner_js_highlight_central= (<<INNERJS);
 1366: <script type="text/javascript">
 1367:     function updateChoice(flag) {
 1368:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1369:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1370:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1371:       opener.document.SCORE.refresh.value = "on";
 1372:       if (opener.document.SCORE.keywords.value!=""){
 1373:          opener.document.SCORE.submit();
 1374:       }
 1375:       self.close()
 1376:     }
 1377: </script>
 1378: INNERJS
 1379: 
 1380:     my $start_page_msg_central = 
 1381:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1382: 				       {'js_ready'  => 1,
 1383: 					'only_body' => 1,
 1384: 					'bgcolor'   =>'#FFFFFF',});
 1385:     my $end_page_msg_central = 
 1386: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1387: 
 1388: 
 1389:     my $start_page_highlight_central = 
 1390:         &Apache::loncommon::start_page('Highlight Central',
 1391: 				       $inner_js_highlight_central,
 1392: 				       {'js_ready'  => 1,
 1393: 					'only_body' => 1,
 1394: 					'bgcolor'   =>'#FFFFFF',});
 1395:     my $end_page_highlight_central = 
 1396: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1397: 
 1398:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1399:     $docopen=~s/^document\.//;
 1400:     my $alertmsg = &mt('Please select a word or group of words from document and then click this link.');
 1401:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1402: 
 1403: //===================== Show list of keywords ====================
 1404:   function keywords(formname) {
 1405:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
 1406:     if (nret==null) return;
 1407:     formname.keywords.value = nret;
 1408: 
 1409:     if (formname.keywords.value != "") {
 1410: 	formname.refresh.value = "on";
 1411: 	formname.submit();
 1412:     }
 1413:     return;
 1414:   }
 1415: 
 1416: //===================== Script to view submitted by ==================
 1417:   function viewSubmitter(submitter) {
 1418:     document.SCORE.refresh.value = "on";
 1419:     document.SCORE.NCT.value = "1";
 1420:     document.SCORE.unamedom0.value = submitter;
 1421:     document.SCORE.submit();
 1422:     return;
 1423:   }
 1424: 
 1425: //===================== Script to add keyword(s) ==================
 1426:   function getSel() {
 1427:     if (document.getSelection) txt = document.getSelection();
 1428:     else if (document.selection) txt = document.selection.createRange().text;
 1429:     else return;
 1430:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1431:     if (cleantxt=="") {
 1432: 	alert("$alertmsg");
 1433: 	return;
 1434:     }
 1435:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
 1436:     if (nret==null) return;
 1437:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1438:     if (document.SCORE.keywords.value != "") {
 1439: 	document.SCORE.refresh.value = "on";
 1440: 	document.SCORE.submit();
 1441:     }
 1442:     return;
 1443:   }
 1444: 
 1445: //====================== Script for composing message ==============
 1446:    // preload images
 1447:    img1 = new Image();
 1448:    img1.src = "$iconpath/mailbkgrd.gif";
 1449:    img2 = new Image();
 1450:    img2.src = "$iconpath/mailto.gif";
 1451: 
 1452:   function msgCenter(msgform,usrctr,fullname) {
 1453:     var Nmsg  = msgform.savemsgN.value;
 1454:     savedMsgHeader(Nmsg,usrctr,fullname);
 1455:     var subject = msgform.msgsub.value;
 1456:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1457:     re = /msgsub/;
 1458:     var shwsel = "";
 1459:     if (re.test(msgchk)) { shwsel = "checked" }
 1460:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1461:     displaySubject(checkEntities(subject),shwsel);
 1462:     for (var i=1; i<=Nmsg; i++) {
 1463: 	var testmsg = "savemsg"+i+",";
 1464: 	re = new RegExp(testmsg,"g");
 1465: 	shwsel = "";
 1466: 	if (re.test(msgchk)) { shwsel = "checked" }
 1467: 	var message = document.SCORE["savemsg"+i].value;
 1468: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1469: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1470: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1471:     }
 1472:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1473:     shwsel = "";
 1474:     re = /newmsg/;
 1475:     if (re.test(msgchk)) { shwsel = "checked" }
 1476:     newMsg(newmsg,shwsel);
 1477:     msgTail(); 
 1478:     return;
 1479:   }
 1480: 
 1481:   function checkEntities(strx) {
 1482:     if (strx.length == 0) return strx;
 1483:     var orgStr = ["&", "<", ">", '"']; 
 1484:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1485:     var counter = 0;
 1486:     while (counter < 4) {
 1487: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1488: 	counter++;
 1489:     }
 1490:     return strx;
 1491:   }
 1492: 
 1493:   function strReplace(strx, orgStr, newStr) {
 1494:     return strx.split(orgStr).join(newStr);
 1495:   }
 1496: 
 1497:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1498:     var height = 70*Nmsg+250;
 1499:     var scrollbar = "no";
 1500:     if (height > 600) {
 1501: 	height = 600;
 1502: 	scrollbar = "yes";
 1503:     }
 1504:     var xpos = (screen.width-600)/2;
 1505:     xpos = (xpos < 0) ? '0' : xpos;
 1506:     var ypos = (screen.height-height)/2-30;
 1507:     ypos = (ypos < 0) ? '0' : ypos;
 1508: 
 1509:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
 1510:     pWin.focus();
 1511:     pDoc = pWin.document;
 1512:     pDoc.$docopen;
 1513:     pDoc.write('$start_page_msg_central');
 1514: 
 1515:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1516:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1517:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
 1518: 
 1519:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1520:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1521:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
 1522: }
 1523:     function displaySubject(msg,shwsel) {
 1524:     pDoc = pWin.document;
 1525:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1526:     pDoc.write("<td>Subject<\\/td>");
 1527:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1528:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1529: }
 1530: 
 1531:   function displaySavedMsg(ctr,msg,shwsel) {
 1532:     pDoc = pWin.document;
 1533:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1534:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1535:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1536:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1537: }
 1538: 
 1539:   function newMsg(newmsg,shwsel) {
 1540:     pDoc = pWin.document;
 1541:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1542:     pDoc.write("<td align=\\"center\\">New<\\/td>");
 1543:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1544:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1545: }
 1546: 
 1547:   function msgTail() {
 1548:     pDoc = pWin.document;
 1549:     pDoc.write("<\\/table>");
 1550:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1551:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1552:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
 1553:     pDoc.write("<\\/form>");
 1554:     pDoc.write('$end_page_msg_central');
 1555:     pDoc.close();
 1556: }
 1557: 
 1558: //====================== Script for keyword highlight options ==============
 1559:   function kwhighlight() {
 1560:     var kwclr    = document.SCORE.kwclr.value;
 1561:     var kwsize   = document.SCORE.kwsize.value;
 1562:     var kwstyle  = document.SCORE.kwstyle.value;
 1563:     var redsel = "";
 1564:     var grnsel = "";
 1565:     var blusel = "";
 1566:     if (kwclr=="red")   {var redsel="checked"};
 1567:     if (kwclr=="green") {var grnsel="checked"};
 1568:     if (kwclr=="blue")  {var blusel="checked"};
 1569:     var sznsel = "";
 1570:     var sz1sel = "";
 1571:     var sz2sel = "";
 1572:     if (kwsize=="0")  {var sznsel="checked"};
 1573:     if (kwsize=="+1") {var sz1sel="checked"};
 1574:     if (kwsize=="+2") {var sz2sel="checked"};
 1575:     var synsel = "";
 1576:     var syisel = "";
 1577:     var sybsel = "";
 1578:     if (kwstyle=="")    {var synsel="checked"};
 1579:     if (kwstyle=="<i>") {var syisel="checked"};
 1580:     if (kwstyle=="<b>") {var sybsel="checked"};
 1581:     highlightCentral();
 1582:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
 1583:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
 1584:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
 1585:     highlightend();
 1586:     return;
 1587:   }
 1588: 
 1589:   function highlightCentral() {
 1590: //    if (window.hwdWin) window.hwdWin.close();
 1591:     var xpos = (screen.width-400)/2;
 1592:     xpos = (xpos < 0) ? '0' : xpos;
 1593:     var ypos = (screen.height-330)/2-30;
 1594:     ypos = (ypos < 0) ? '0' : ypos;
 1595: 
 1596:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1597:     hwdWin.focus();
 1598:     var hDoc = hwdWin.document;
 1599:     hDoc.$docopen;
 1600:     hDoc.write('$start_page_highlight_central');
 1601:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1602:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
 1603: 
 1604:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1605:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1606:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
 1607:   }
 1608: 
 1609:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1610:     var hDoc = hwdWin.document;
 1611:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1612:     hDoc.write("<td align=\\"left\\">");
 1613:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
 1614:     hDoc.write("<td align=\\"left\\">");
 1615:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
 1616:     hDoc.write("<td align=\\"left\\">");
 1617:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
 1618:     hDoc.write("<\\/tr>");
 1619:   }
 1620: 
 1621:   function highlightend() { 
 1622:     var hDoc = hwdWin.document;
 1623:     hDoc.write("<\\/table>");
 1624:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1625:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
 1626:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
 1627:     hDoc.write("<\\/form>");
 1628:     hDoc.write('$end_page_highlight_central');
 1629:     hDoc.close();
 1630:   }
 1631: 
 1632: SUBJAVASCRIPT
 1633: }
 1634: 
 1635: sub get_increment {
 1636:     my $increment = $env{'form.increment'};
 1637:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1638:         $increment != .1) {
 1639:         $increment = 1;
 1640:     }
 1641:     return $increment;
 1642: }
 1643: 
 1644: sub gradeBox_start {
 1645:     return (
 1646:         &Apache::loncommon::start_data_table()
 1647:        .&Apache::loncommon::start_data_table_header_row()
 1648:        .'<th>'.&mt('Part').'</th>'
 1649:        .'<th>'.&mt('Points').'</th>'
 1650:        .'<th>&nbsp;</th>'
 1651:        .'<th>'.&mt('Assign Grade').'</th>'
 1652:        .'<th>'.&mt('Weight').'</th>'
 1653:        .'<th>'.&mt('Grade Status').'</th>'
 1654:        .&Apache::loncommon::end_data_table_header_row()
 1655:     );
 1656: }
 1657: 
 1658: sub gradeBox_end {
 1659:     return (
 1660:         &Apache::loncommon::end_data_table()
 1661:     );
 1662: }
 1663: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1664: sub gradeBox {
 1665:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1666:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1667: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1668:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1669:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1670:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1671:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1672:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1673: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1674:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1675:     my $display_part= &get_display_part($partid,$symb);
 1676:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1677: 				       [$partid]);
 1678:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1679:     if ($last_resets{$partid}) {
 1680:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1681:     }
 1682:     $result.=&Apache::loncommon::start_data_table_row();
 1683:     my $ctr = 0;
 1684:     my $thisweight = 0;
 1685:     my $increment = &get_increment();
 1686: 
 1687:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1688:     while ($thisweight<=$wgt) {
 1689: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1690:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1691: 	    $thisweight.')" value="'.$thisweight.'" '.
 1692: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1693: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1694:         $thisweight += $increment;
 1695: 	$ctr++;
 1696:     }
 1697:     $radio.='</tr></table>';
 1698: 
 1699:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1700: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1701: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1702: 	$wgt.')" /></td>'."\n";
 1703:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1704: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1705: 	' </td>'."\n";
 1706:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1707: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1708:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1709: 	$line.='<option></option>'.
 1710: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1711:     } else {
 1712: 	$line.='<option selected="selected"></option>'.
 1713: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1714:     }
 1715:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1716: 
 1717: 
 1718:     $result .= 
 1719: 	    '<td>'.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 1720:     $result.=&Apache::loncommon::end_data_table_row();
 1721:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1722: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1723: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1724: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1725:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1726:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1727:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1728:         $aggtries.'" />'."\n";
 1729:     my $res_error;
 1730:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 1731:     if ($res_error) {
 1732:         return &navmap_errormsg();
 1733:     }
 1734:     return $result;
 1735: }
 1736: 
 1737: sub handback_box {
 1738:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
 1739:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
 1740:     my (@respids);
 1741:      my @part_response_id = &flatten_responseType($responseType);
 1742:     foreach my $part_response_id (@part_response_id) {
 1743:     	my ($part,$resp) = @{ $part_response_id };
 1744:         if ($part eq $partid) {
 1745:             push(@respids,$resp);
 1746:         }
 1747:     }
 1748:     my $result;
 1749:     foreach my $respid (@respids) {
 1750: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1751: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1752: 	next if (!@$files);
 1753: 	my $file_counter = 1;
 1754: 	foreach my $file (@$files) {
 1755: 	    if ($file =~ /\/portfolio\//) {
 1756:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1757:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1758:     	        $file_disp = "$name.$ext";
 1759:     	        $file = $file_path.$file_disp;
 1760:     	        $result.=&mt('Return commented version of [_1] to student.',
 1761:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1762:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1763:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
 1764:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
 1765:     	        $file_counter++;
 1766: 	    }
 1767: 	}
 1768:     }
 1769:     return $result;    
 1770: }
 1771: 
 1772: sub show_problem {
 1773:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1774:     my $rendered;
 1775:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1776:     &Apache::lonxml::remember_problem_counter();
 1777:     if ($mode eq 'both' or $mode eq 'text') {
 1778: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1779: 						       $env{'request.course.id'},
 1780: 						       undef,\%form);
 1781:     }
 1782:     if ($removeform) {
 1783: 	$rendered=~s|<form(.*?)>||g;
 1784: 	$rendered=~s|</form>||g;
 1785: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1786:     }
 1787:     my $companswer;
 1788:     if ($mode eq 'both' or $mode eq 'answer') {
 1789: 	&Apache::lonxml::restore_problem_counter();
 1790: 	$companswer=
 1791: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1792: 						    $env{'request.course.id'},
 1793: 						    %form);
 1794:     }
 1795:     if ($removeform) {
 1796: 	$companswer=~s|<form(.*?)>||g;
 1797: 	$companswer=~s|</form>||g;
 1798: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1799:     }
 1800:     $rendered=
 1801:         '<div class="LC_Box">'
 1802:        .'<h3 class="LC_hcell">'.&mt('View of the problem').'</h3>'
 1803:        .$rendered
 1804:        .'</div>';
 1805:     $companswer=
 1806:         '<div class="LC_Box">'
 1807:        .'<h3 class="LC_hcell">'.&mt('Correct answer').'</h3>'
 1808:        .$companswer
 1809:        .'</div>';
 1810:     my $result;
 1811:     if ($mode eq 'both') {
 1812:         $result=$rendered.$companswer;
 1813:     } elsif ($mode eq 'text') {
 1814:         $result=$rendered;
 1815:     } elsif ($mode eq 'answer') {
 1816:         $result=$companswer;
 1817:     }
 1818:     return $result;
 1819: }
 1820: 
 1821: sub files_exist {
 1822:     my ($r, $symb) = @_;
 1823:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1824: 
 1825:     foreach my $student (@students) {
 1826:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1827:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1828: 					      $udom,$uname);
 1829:         my ($string,$timestamp)= &get_last_submission(\%record);
 1830:         foreach my $submission (@$string) {
 1831:             my ($partid,$respid) =
 1832: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1833:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1834: 					   \%record);
 1835:             return 1 if (@$files);
 1836:         }
 1837:     }
 1838:     return 0;
 1839: }
 1840: 
 1841: sub download_all_link {
 1842:     my ($r,$symb) = @_;
 1843:     unless (&files_exist($r, $symb)) {
 1844:        $r->print(&mt('There are currently no submitted documents.'));
 1845:        return;
 1846:     }
 1847: 
 1848:     my $all_students = 
 1849: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1850: 
 1851:     my $parts =
 1852: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1853: 
 1854:     my $identifier = &Apache::loncommon::get_cgi_id();
 1855:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 1856:                              'cgi.'.$identifier.'.symb' => $symb,
 1857:                              'cgi.'.$identifier.'.parts' => $parts,});
 1858:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1859: 	      &mt('Download All Submitted Documents').'</a>');
 1860:     return;
 1861: }
 1862: 
 1863: sub submit_download_link {
 1864:     my ($request,$symb) = @_;
 1865:     if (!$symb) { return ''; }
 1866: #FIXME: Figure out which type of problem this is and provide appropriate download
 1867:     &download_all_link($request,$symb);
 1868: }
 1869: 
 1870: sub build_section_inputs {
 1871:     my $section_inputs;
 1872:     if ($env{'form.section'} eq '') {
 1873:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 1874:     } else {
 1875:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 1876:         foreach my $section (@sections) {
 1877:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 1878:         }
 1879:     }
 1880:     return $section_inputs;
 1881: }
 1882: 
 1883: # --------------------------- show submissions of a student, option to grade 
 1884: sub submission {
 1885:     my ($request,$counter,$total,$symb) = @_;
 1886:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 1887:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 1888:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 1889:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 1890: 
 1891:     my $probtitle=&Apache::lonnet::gettitle($symb); 
 1892:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 1893: 
 1894:     if (!&canview($usec)) {
 1895: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
 1896: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
 1897: 			$env{'request.course.id'}.')</span>');
 1898: 	return;
 1899:     }
 1900: 
 1901:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 1902:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 1903:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 1904:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 1905:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1906: 	'" src="'.$request->dir_config('lonIconsURL').
 1907: 	'/check.gif" height="16" border="0" />';
 1908: 
 1909:     my %old_essays;
 1910:     # header info
 1911:     if ($counter == 0) {
 1912: 	&sub_page_js($request);
 1913: 	&sub_page_kw_js($request);
 1914: 
 1915: 	# option to display problem, only once else it cause problems 
 1916:         # with the form later since the problem has a form.
 1917: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 1918: 	    my $mode;
 1919: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 1920: 		$mode='both';
 1921: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 1922: 		$mode='text';
 1923: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 1924: 		$mode='answer';
 1925: 	    }
 1926: 	    &Apache::lonxml::clear_problem_counter();
 1927: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 1928: 	}
 1929: 
 1930: 	# kwclr is the only variable that is guaranteed to be non blank 
 1931:         # if this subroutine has been called once.
 1932: 	my %keyhash = ();
 1933: #	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 1934:         if (1) {
 1935: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 1936: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 1937: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 1938: 
 1939: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 1940: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 1941: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 1942: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 1943: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 1944: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 1945: 		$keyhash{$symb.'_subject'} : $probtitle;
 1946: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 1947: 	}
 1948: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 1949: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 1950: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 1951: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 1952: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 1953: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 1954: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 1955: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 1956: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 1957: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1958: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 1959: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 1960: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 1961: 			&build_section_inputs().
 1962: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 1963: 			'<input type="hidden" name="NCT"'.
 1964: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 1965: #	if ($env{'form.handgrade'} eq 'yes') {
 1966:         if (1) {
 1967: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 1968: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 1969: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 1970: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 1971: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 1972: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 1973: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 1974: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 1975: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 1976: 	    }
 1977: 	}
 1978: 	
 1979: 	my ($cts,$prnmsg) = (1,'');
 1980: 	while ($cts <= $env{'form.savemsgN'}) {
 1981: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 1982: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 1983: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 1984: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 1985: 		'" />'."\n".
 1986: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 1987: 	    $cts++;
 1988: 	}
 1989: 	$request->print($prnmsg);
 1990: 
 1991: #	if ($env{'form.handgrade'} eq 'yes') {
 1992:         if (1) {
 1993: #
 1994: # Print out the keyword options line
 1995: #
 1996: 	    $request->print(<<KEYWORDS);
 1997: &nbsp;<b>Keyword Options:</b>&nbsp;
 1998: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
 1999: <a href="#" onmousedown="javascript:getSel(); return false"
 2000:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
 2001: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
 2002: KEYWORDS
 2003: #
 2004: # Load the other essays for similarity check
 2005: #
 2006:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2007: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2008: 	    $apath=&escape($apath);
 2009: 	    $apath=~s/\W/\_/gs;
 2010: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 2011:         }
 2012:     }
 2013: 
 2014: # This is where output for one specific student would start
 2015:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2016:     $request->print(
 2017:         "\n\n"
 2018:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2019:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2020:        ."\n"
 2021:     );
 2022: 
 2023:     # Show additional functions if allowed
 2024:     if ($perm{'vgr'}) {
 2025:         $request->print(
 2026:             &Apache::loncommon::track_student_link(
 2027:                 &mt('View recent activity'),
 2028:                 $uname,$udom,'check')
 2029:            .' '
 2030:         );
 2031:     }
 2032:     if ($perm{'opa'}) {
 2033:         $request->print(
 2034:             &Apache::loncommon::pprmlink(
 2035:                 &mt('Set/Change parameters'),
 2036:                 $uname,$udom,$symb,'check'));
 2037:     }
 2038: 
 2039:     # Show Problem
 2040:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2041: 	my $mode;
 2042: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2043: 	    $mode='both';
 2044: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2045: 	    $mode='text';
 2046: 	} elsif ($env{'form.vAns'} eq 'all') {
 2047: 	    $mode='answer';
 2048: 	}
 2049: 	&Apache::lonxml::clear_problem_counter();
 2050: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2051:     }
 2052: 
 2053:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2054:     my $res_error;
 2055:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2056:     if ($res_error) {
 2057:         $request->print(&navmap_errormsg());
 2058:         return;
 2059:     }
 2060: 
 2061:     # Display student info
 2062:     $request->print(($counter == 0 ? '' : '<br />'));
 2063: 
 2064:     my $result='<div class="LC_Box">'
 2065:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
 2066:     $result.='<input type="hidden" name="name'.$counter.
 2067:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2068: #    if ($env{'form.handgrade'} eq 'no') {
 2069:     if (1) {
 2070:         $result.='<p class="LC_info">'
 2071:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2072:                 ."</p>\n";
 2073:     }
 2074: 
 2075:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2076:     my $fullname;
 2077:     my $col_fullnames = [];
 2078: #    if ($env{'form.handgrade'} eq 'yes') {
 2079:     if (1) {
 2080: 	(my $sub_result,$fullname,$col_fullnames)=
 2081: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2082: 				 $counter);
 2083: 	$result.=$sub_result;
 2084:     }
 2085:     $request->print($result."\n");
 2086: 
 2087:     # print student answer/submission
 2088:     # Options are (1) Handgraded submission only
 2089:     #             (2) Last submission, includes submission that is not handgraded 
 2090:     #                  (for multi-response type part)
 2091:     #             (3) Last submission plus the parts info
 2092:     #             (4) The whole record for this student
 2093:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
 2094: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2095: 	
 2096: 	my $lastsubonly;
 2097: 
 2098:         if ($$timestamp eq '') {
 2099:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2100:         } else {
 2101:             $lastsubonly =
 2102:                 '<div class="LC_grade_submissions_body">'
 2103:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
 2104: 
 2105: 	    my %seenparts;
 2106: 	    my @part_response_id = &flatten_responseType($responseType);
 2107: 	    foreach my $part (@part_response_id) {
 2108: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2109: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2110: 
 2111: 		my ($partid,$respid) = @{ $part };
 2112: 		my $display_part=&get_display_part($partid,$symb);
 2113: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2114: 		    if (exists($seenparts{$partid})) { next; }
 2115: 		    $seenparts{$partid}=1;
 2116: 		    my $submitby='<b>Part:</b> '.$display_part.
 2117: 			' <b>Collaborative submission by:</b> '.
 2118: 			'<a href="javascript:viewSubmitter(\''.
 2119: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
 2120: 			'\');" target="_self">'.
 2121: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
 2122: 		    $request->print($submitby);
 2123: 		    next;
 2124: 		}
 2125: 		my $responsetype = $responseType->{$partid}->{$respid};
 2126: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2127:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2128:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2129:                         ' <span class="LC_internal_info">'.
 2130:                         '('.&mt('Response ID: [_1]',$respid).')'.
 2131:                         '</span>&nbsp; &nbsp;'.
 2132: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2133: 		    next;
 2134: 		}
 2135: 		foreach my $submission (@$string) {
 2136: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2137: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2138: 		    my ($ressub,$hide,$subval) = split(/:/,$submission,3);
 2139: 		    # Similarity check
 2140: 		    my $similar='';
 2141: 		    if($env{'form.checkPlag'}){
 2142: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2143: 			    &most_similar($uname,$udom,$subval,\%old_essays);
 2144: 			if ($osim) {
 2145: 			    $osim=int($osim*100.0);
 2146: 			    my %old_course_desc = 
 2147: 				&Apache::lonnet::coursedescription($ocrsid,
 2148: 								   {'one_time' => 1});
 2149: 
 2150:                             if ($hide) {
 2151:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2152:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2153:                             } else {
 2154: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
 2155: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2156: 				        $osim,
 2157: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2158: 				        $old_course_desc{'description'},
 2159: 				        $old_course_desc{'num'},
 2160: 				        $old_course_desc{'domain'}).
 2161: 				    '</span></h3><blockquote><i>'.
 2162: 				    &keywords_highlight($oessay).
 2163: 				    '</i></blockquote><hr />';
 2164:                             }
 2165: 			}
 2166: 		    }
 2167: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
 2168: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
 2169: 			($env{'form.lastSub'} eq 'hdgrade' && 
 2170: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2171: 			my $display_part=&get_display_part($partid,$symb);
 2172:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
 2173:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2174:                             ' <span class="LC_internal_info">'.
 2175:                             '('.&mt('Response ID: [_1]',$respid).')'.
 2176:                             '</span>&nbsp; &nbsp;';
 2177: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2178: 			if (@$files) {
 2179:                             if ($hide) {
 2180:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2181:                             } else {
 2182:                                 $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
 2183:                                 foreach my $file (@$files) {
 2184:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2185:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
 2186:                                 }
 2187:                             }
 2188: 			    $lastsubonly.='<br />';
 2189: 			}
 2190:                         if ($hide) {
 2191:                             $lastsubonly.='<b>'.&mt('Anonymous Survey').'</b>'; 
 2192:                         } else {
 2193: 			    $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
 2194: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
 2195: 					     $respid,\%record,$order,undef,$uname,$udom);
 2196:                         }
 2197: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2198: 			$lastsubonly.='</div>';
 2199: 		    }
 2200: 		}
 2201: 	    }
 2202: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2203: 	}
 2204: 	$request->print($lastsubonly);
 2205:    } elsif ($env{'form.lastSub'} eq 'datesub') {
 2206:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2207: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2208:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2209: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2210: 								 $env{'request.course.id'},
 2211: 								 $last,'.submission',
 2212: 								 'Apache::grades::keywords_highlight'));
 2213:     }
 2214:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2215: 	.$udom.'" />'."\n");
 2216:     # return if view submission with no grading option
 2217: # FIXME: the logic seems off here. Why show the grade button if you cannot grade?
 2218:     if (!&canmodify($usec)) {
 2219: 	my $toGrade.='<input type="button" value="Grade Student" '.
 2220: 	    'onclick="javascript:checksubmit(this.form,\'Grade Student\',\''
 2221: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
 2222: 	$toGrade.='</div>'."\n";
 2223: 	$request->print($toGrade);
 2224: 	return;
 2225:     } else {
 2226: 	$request->print('</div>'."\n");
 2227:     }
 2228: 
 2229:     # essay grading message center
 2230: #    if ($env{'form.handgrade'} eq 'yes') {
 2231:     if (1) {
 2232: 	my $result='<div class="LC_grade_message_center">';
 2233:     
 2234: 	$result.='<div class="LC_grade_message_center_header">'.
 2235: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2236: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2237: 	my $msgfor = $givenn.' '.$lastname;
 2238: 	if (scalar(@$col_fullnames) > 0) {
 2239: 	    my $lastone = pop(@$col_fullnames);
 2240: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2241: 	}
 2242: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2243: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2244: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2245: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2246: 	    ',\''.$msgfor.'\');" target="_self">'.
 2247: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
 2248: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2249: 	    '<img src="'.$request->dir_config('lonIconsURL').
 2250: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2251: 	    '<br />&nbsp;('.
 2252: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2253: 	$result.='</div></div>';
 2254: 	$request->print($result);
 2255:     }
 2256: 
 2257:     my %seen = ();
 2258:     my @partlist;
 2259:     my @gradePartRespid;
 2260:     my @part_response_id = &flatten_responseType($responseType);
 2261:     $request->print(
 2262:         '<div class="LC_Box">'
 2263:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2264:     );
 2265:     $request->print(&gradeBox_start());
 2266:     foreach my $part_response_id (@part_response_id) {
 2267:     	my ($partid,$respid) = @{ $part_response_id };
 2268: 	my $part_resp = join('_',@{ $part_response_id });
 2269: 	next if ($seen{$partid} > 0);
 2270: 	$seen{$partid}++;
 2271: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2272: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2273: 	push(@partlist,$partid);
 2274: 	push(@gradePartRespid,$partid.'.'.$respid);
 2275: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2276:     }
 2277:     $request->print(&gradeBox_end()); # </div>
 2278:     $request->print('</div>');
 2279: 
 2280:     $request->print('<div class="LC_grade_info_links">');
 2281:     $request->print('</div>');
 2282: 
 2283:     $result='<input type="hidden" name="partlist'.$counter.
 2284: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2285:     $result.='<input type="hidden" name="gradePartRespid'.
 2286: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2287:     my $ctr = 0;
 2288:     while ($ctr < scalar(@partlist)) {
 2289: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2290: 	    $partlist[$ctr].'" />'."\n";
 2291: 	$ctr++;
 2292:     }
 2293:     $request->print($result.''."\n");
 2294: 
 2295: # Done with printing info for one student
 2296: 
 2297:     $request->print('</div>');#LC_grade_show_user
 2298: 
 2299: 
 2300:     # print end of form
 2301:     if ($counter == $total) {
 2302:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2303: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2304: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2305: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2306: 	my $ntstu ='<select name="NTSTU">'.
 2307: 	    '<option>1</option><option>2</option>'.
 2308: 	    '<option>3</option><option>5</option>'.
 2309: 	    '<option>7</option><option>10</option></select>'."\n";
 2310: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2311: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2312:         $endform.=&mt('[_1]student(s)',$ntstu);
 2313: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2314: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2315: 	    '<input type="button" value="'.&mt('Next').'" '.
 2316: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2317:         $endform.='<span class="LC_warning">'.
 2318:                   &mt('(Next and Previous (student) do not save the scores.)').
 2319:                   '</span>'."\n" ;
 2320:         $endform.="<input type='hidden' value='".&get_increment().
 2321:             "' name='increment' />";
 2322: 	$endform.='</td></tr></table></form>';
 2323: 	$request->print($endform);
 2324:     }
 2325:     return '';
 2326: }
 2327: 
 2328: sub check_collaborators {
 2329:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2330:     my ($result,@col_fullnames);
 2331:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2332:     foreach my $part (keys(%$handgrade)) {
 2333: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2334: 					'.maxcollaborators',
 2335: 					$symb,$udom,$uname);
 2336: 	next if ($ncol <= 0);
 2337: 	$part =~ s/\_/\./g;
 2338: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2339: 	my (@good_collaborators, @bad_collaborators);
 2340: 	foreach my $possible_collaborator
 2341: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2342: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2343: 	    next if ($possible_collaborator eq '');
 2344: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
 2345: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2346: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2347: 	    # Doing this grep allows 'fuzzy' specification
 2348: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2349: 			       keys(%$classlist));
 2350: 	    if (! scalar(@matches)) {
 2351: 		push(@bad_collaborators, $possible_collaborator);
 2352: 	    } else {
 2353: 		push(@good_collaborators, @matches);
 2354: 	    }
 2355: 	}
 2356: 	if (scalar(@good_collaborators) != 0) {
 2357: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
 2358: 	    foreach my $name (@good_collaborators) {
 2359: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2360: 		push(@col_fullnames, $givenn.' '.$lastname);
 2361: 		$result.='<li>'.$fullname->{$name}.'</li>';
 2362: 	    }
 2363: 	    $result.='</ol><br />'."\n";
 2364: 	    my ($part)=split(/\./,$part);
 2365: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2366: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2367: 		"\n";
 2368: 	}
 2369: 	if (scalar(@bad_collaborators) > 0) {
 2370: 	    $result.='<div class="LC_warning">';
 2371: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2372: 	    $result .= '</div>';
 2373: 	}         
 2374: 	if (scalar(@bad_collaborators > $ncol)) {
 2375: 	    $result .= '<div class="LC_warning">';
 2376: 	    $result .= &mt('This student has submitted too many '.
 2377: 		'collaborators.  Maximum is [_1].',$ncol);
 2378: 	    $result .= '</div>';
 2379: 	}
 2380:     }
 2381:     return ($result,$fullname,\@col_fullnames);
 2382: }
 2383: 
 2384: #--- Retrieve the last submission for all the parts
 2385: sub get_last_submission {
 2386:     my ($returnhash)=@_;
 2387:     my (@string,$timestamp,%lasthidden);
 2388:     if ($$returnhash{'version'}) {
 2389: 	my %lasthash=();
 2390: 	my ($version);
 2391: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2392: 	    foreach my $key (sort(split(/\:/,
 2393: 					$$returnhash{$version.':keys'}))) {
 2394: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2395: 		$timestamp = 
 2396: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2397: 	    }
 2398: 	}
 2399:         my %typeparts;
 2400:         my $showsurv = 
 2401:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2402:         foreach my $key (sort(keys(%lasthash))) {
 2403:             if ($key =~ /\.type$/) {
 2404:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2405:                     ($lasthash{$key} eq 'anonsurveycred')) {
 2406:                     my ($ign,@parts) = split(/\./,$key);
 2407:                     pop(@parts);
 2408:                     unless ($showsurv) {
 2409:                         my $id = join(',',@parts);
 2410:                         $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2411:                     }
 2412:                     delete($lasthash{$key});
 2413:                 }
 2414:             }
 2415:         }
 2416:         my @hidden = keys(%typeparts);
 2417: 	foreach my $key (keys(%lasthash)) {
 2418: 	    next if ($key !~ /\.submission$/);
 2419:             my $hide;
 2420:             if (@hidden) {
 2421:                 foreach my $id (@hidden) {
 2422:                     if ($key =~ /^\Q$id\E/) {
 2423:                         $hide = 1;
 2424:                         last;
 2425:                     }
 2426:                 }
 2427:             }
 2428: 	    my ($partid,$foo) = split(/submission$/,$key);
 2429: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 2430: 		'<span class="LC_warning">Draft Copy</span> ' : '';
 2431: 	    push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
 2432: 	}
 2433:     }
 2434:     if (!@string) {
 2435: 	$string[0] =
 2436: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2437:     }
 2438:     return (\@string,\$timestamp);
 2439: }
 2440: 
 2441: #--- High light keywords, with style choosen by user.
 2442: sub keywords_highlight {
 2443:     my $string    = shift;
 2444:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2445:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2446:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2447:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2448:     foreach my $keyword (@keylist) {
 2449: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2450:     }
 2451:     return $string;
 2452: }
 2453: 
 2454: #--- Called from submission routine
 2455: sub processHandGrade {
 2456:     my ($request,$symb) = @_;
 2457:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2458:     my $button = $env{'form.gradeOpt'};
 2459:     my $ngrade = $env{'form.NCT'};
 2460:     my $ntstu  = $env{'form.NTSTU'};
 2461:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2462:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2463: 
 2464:     if ($button eq 'Save & Next') {
 2465: 	my $ctr = 0;
 2466: 	while ($ctr < $ngrade) {
 2467: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2468: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2469: 	    if ($errorflag eq 'no_score') {
 2470: 		$ctr++;
 2471: 		next;
 2472: 	    }
 2473: 	    if ($errorflag eq 'not_allowed') {
 2474: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
 2475: 		$ctr++;
 2476: 		next;
 2477: 	    }
 2478: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2479: 	    my ($subject,$message,$msgstatus) = ('','','');
 2480: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2481:             my ($feedurl,$showsymb) =
 2482: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2483: 	    my $messagetail;
 2484: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2485: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2486: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2487: 		$subject.=' ['.$restitle.']';
 2488: 		my (@msgnum) = split(/,/,$includemsg);
 2489: 		foreach (@msgnum) {
 2490: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2491: 		}
 2492: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2493: 		if ($env{'form.withgrades'.$ctr}) {
 2494: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2495: 		    $messagetail = " for <a href=\"".
 2496: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
 2497: 		}
 2498: 		$msgstatus = 
 2499:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2500: 						     $message.$messagetail,
 2501:                                                      undef,$feedurl,undef,
 2502:                                                      undef,undef,$showsymb,
 2503:                                                      $restitle);
 2504: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 2505: 				$msgstatus);
 2506: 	    }
 2507: 	    if ($env{'form.collaborator'.$ctr}) {
 2508: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2509: 		foreach my $collabstr (@collabstrs) {
 2510: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2511: 		    foreach my $collaborator (@collaborators) {
 2512: 			my ($errorflag,$pts,$wgt) = 
 2513: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2514: 					   $env{'form.unamedom'.$ctr},$part);
 2515: 			if ($errorflag eq 'not_allowed') {
 2516: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2517: 			    next;
 2518: 			} elsif ($message ne '') {
 2519: 			    my ($baseurl,$showsymb) = 
 2520: 				&get_feedurl_and_symb($symb,$collaborator,
 2521: 						      $udom);
 2522: 			    if ($env{'form.withgrades'.$ctr}) {
 2523: 				$messagetail = " for <a href=\"".
 2524:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
 2525: 			    }
 2526: 			    $msgstatus = 
 2527: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2528: 			}
 2529: 		    }
 2530: 		}
 2531: 	    }
 2532: 	    $ctr++;
 2533: 	}
 2534:     }
 2535: 
 2536: #    if ($env{'form.handgrade'} eq 'yes') {
 2537:     if (1) {
 2538: 	# Keywords sorted in alphabatical order
 2539: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2540: 	my %keyhash = ();
 2541: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2542: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2543: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2544: 	$env{'form.keywords'} = join(' ',@keywords);
 2545: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2546: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2547: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2548: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2549: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2550: 
 2551: 	# message center - Order of message gets changed. Blank line is eliminated.
 2552: 	# New messages are saved in env for the next student.
 2553: 	# All messages are saved in nohist_handgrade.db
 2554: 	my ($ctr,$idx) = (1,1);
 2555: 	while ($ctr <= $env{'form.savemsgN'}) {
 2556: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2557: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2558: 		$idx++;
 2559: 	    }
 2560: 	    $ctr++;
 2561: 	}
 2562: 	$ctr = 0;
 2563: 	while ($ctr < $ngrade) {
 2564: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2565: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2566: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2567: 		$idx++;
 2568: 	    }
 2569: 	    $ctr++;
 2570: 	}
 2571: 	$env{'form.savemsgN'} = --$idx;
 2572: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2573: 	my $putresult = &Apache::lonnet::put
 2574: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2575:     }
 2576:     # Called by Save & Refresh from Highlight Attribute Window
 2577:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2578:     if ($env{'form.refresh'} eq 'on') {
 2579: 	my ($ctr,$total) = (0,0);
 2580: 	while ($ctr < $ngrade) {
 2581: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2582: 	    $ctr++;
 2583: 	}
 2584: 	$env{'form.NTSTU'}=$ngrade;
 2585: 	$ctr = 0;
 2586: 	while ($ctr < $total) {
 2587: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2588: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2589: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2590: 	    &submission($request,$ctr,$total-1,$symb);
 2591: 	    $ctr++;
 2592: 	}
 2593: 	return '';
 2594:     }
 2595: 
 2596: # Go directly to grade student - from submission or link from chart page
 2597: # FIXME: looks like reading off the button label!
 2598:     if ($button eq 'Grade Student') {
 2599: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
 2600: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2601: 	$env{'form.fullname'} = $$fullname{$processUser};
 2602: 	&submission($request,0,0,$symb);
 2603: 	return '';
 2604:     }
 2605: 
 2606:     # Get the next/previous one or group of students
 2607:     my $firststu = $env{'form.unamedom0'};
 2608:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2609:     my $ctr = 2;
 2610:     while ($laststu eq '') {
 2611: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2612: 	$ctr++;
 2613: 	$laststu = $firststu if ($ctr > $ngrade);
 2614:     }
 2615: 
 2616:     my (@parsedlist,@nextlist);
 2617:     my ($nextflg) = 0;
 2618:     foreach my $item (sort 
 2619: 	     {
 2620: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2621: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2622: 		 }
 2623: 		 return $a cmp $b;
 2624: 	     } (keys(%$fullname))) {
 2625: # FIXME: this is fishy, looks like the button label
 2626: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2627: 	    push(@parsedlist,$item);
 2628: 	}
 2629: 	$nextflg = 1 if ($item eq $laststu);
 2630: 	if ($button eq 'Previous') {
 2631: 	    last if ($item eq $firststu);
 2632: 	    push(@parsedlist,$item);
 2633: 	}
 2634:     }
 2635:     $ctr = 0;
 2636: # FIXME: this is fishy, looks like the button label
 2637:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2638:     my $res_error;
 2639:     my ($partlist) = &response_type($symb,\$res_error);
 2640:     if ($res_error) {
 2641:         $request->print(&navmap_errormsg());
 2642:         return;
 2643:     }
 2644:     foreach my $student (@parsedlist) {
 2645: 	my $submitonly=$env{'form.submitonly'};
 2646: 	my ($uname,$udom) = split(/:/,$student);
 2647: 	
 2648: 	if ($submitonly eq 'queued') {
 2649: 	    my %queue_status = 
 2650: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2651: 							$udom,$uname);
 2652: 	    next if (!defined($queue_status{'gradingqueue'}));
 2653: 	}
 2654: 
 2655: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2656: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2657: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2658: 	    my $submitted = 0;
 2659: 	    my $ungraded = 0;
 2660: 	    my $incorrect = 0;
 2661: 	    foreach my $item (keys(%status)) {
 2662: 		$submitted = 1 if ($status{$item} ne 'nothing');
 2663: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 2664: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 2665: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 2666: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2667: 		    $submitted = 0;
 2668: 		}
 2669: 	    }
 2670: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2671: 				     $submitonly eq 'incorrect' ||
 2672: 				     $submitonly eq 'graded'));
 2673: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2674: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2675: 	}
 2676: 	push(@nextlist,$student) if ($ctr < $ntstu);
 2677: 	last if ($ctr == $ntstu);
 2678: 	$ctr++;
 2679:     }
 2680: 
 2681:     $ctr = 0;
 2682:     my $total = scalar(@nextlist)-1;
 2683: 
 2684:     foreach (sort(@nextlist)) {
 2685: 	my ($uname,$udom,$submitter) = split(/:/);
 2686: 	$env{'form.student'}  = $uname;
 2687: 	$env{'form.userdom'}  = $udom;
 2688: 	$env{'form.fullname'} = $$fullname{$_};
 2689: 	&submission($request,$ctr,$total,$symb);
 2690: 	$ctr++;
 2691:     }
 2692:     if ($total < 0) {
 2693: 	my $the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
 2694: 	$request->print($the_end);
 2695:     }
 2696:     return '';
 2697: }
 2698: 
 2699: #---- Save the score and award for each student, if changed
 2700: sub saveHandGrade {
 2701:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 2702:     my @version_parts;
 2703:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 2704: 					   $env{'request.course.id'});
 2705:     if (!&canmodify($usec)) { return('not_allowed'); }
 2706:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 2707:     my @parts_graded;
 2708:     my %newrecord  = ();
 2709:     my ($pts,$wgt) = ('','');
 2710:     my %aggregate = ();
 2711:     my $aggregateflag = 0;
 2712:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 2713:     foreach my $new_part (@parts) {
 2714: 	#collaborator ($submi may vary for different parts
 2715: 	if ($submitter && $new_part ne $part) { next; }
 2716: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 2717: 	if ($dropMenu eq 'excused') {
 2718: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 2719: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 2720: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 2721: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 2722: 		}
 2723: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 2724: 	    }
 2725: 	} elsif ($dropMenu eq 'reset status'
 2726: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 2727: 	    foreach my $key (keys(%record)) {
 2728: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 2729: 	    }
 2730: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2731: 		"$env{'user.name'}:$env{'user.domain'}";
 2732:             my $totaltries = $record{'resource.'.$part.'.tries'};
 2733: 
 2734:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2735: 					       [$new_part]);
 2736:             my $aggtries =$totaltries;
 2737:             if ($last_resets{$new_part}) {
 2738:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 2739: 					   $new_part);
 2740:             }
 2741: 
 2742:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 2743:             if ($aggtries > 0) {
 2744:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 2745:                 $aggregateflag = 1;
 2746:             }
 2747: 	} elsif ($dropMenu eq '') {
 2748: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 2749: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 2750: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 2751: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 2752: 		next;
 2753: 	    }
 2754: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 2755: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 2756: 	    my $partial= $pts/$wgt;
 2757: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 2758: 		#do not update score for part if not changed.
 2759:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 2760: 		next;
 2761: 	    } else {
 2762: 	        push(@parts_graded,$new_part);
 2763: 	    }
 2764: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 2765: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 2766: 	    }
 2767: 	    my $reckey = 'resource.'.$new_part.'.solved';
 2768: 	    if ($partial == 0) {
 2769: 		if ($record{$reckey} ne 'incorrect_by_override') {
 2770: 		    $newrecord{$reckey} = 'incorrect_by_override';
 2771: 		}
 2772: 	    } else {
 2773: 		if ($record{$reckey} ne 'correct_by_override') {
 2774: 		    $newrecord{$reckey} = 'correct_by_override';
 2775: 		}
 2776: 	    }	    
 2777: 	    if ($submitter && 
 2778: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 2779: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 2780: 	    }
 2781: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2782: 		"$env{'user.name'}:$env{'user.domain'}";
 2783: 	}
 2784: 	# unless problem has been graded, set flag to version the submitted files
 2785: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 2786: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 2787: 	        $dropMenu eq 'reset status')
 2788: 	   {
 2789: 	    push(@version_parts,$new_part);
 2790: 	}
 2791:     }
 2792:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2793:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2794: 
 2795:     if (%newrecord) {
 2796:         if (@version_parts) {
 2797:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 2798:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 2799: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 2800: 	    foreach my $new_part (@version_parts) {
 2801: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 2802: 				$new_part,\%newrecord);
 2803: 	    }
 2804:         }
 2805: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 2806: 				$env{'request.course.id'},$domain,$stuname);
 2807: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 2808: 				     $cdom,$cnum,$domain,$stuname);
 2809:     }
 2810:     if ($aggregateflag) {
 2811:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 2812: 			      $cdom,$cnum);
 2813:     }
 2814:     return ('',$pts,$wgt);
 2815: }
 2816: 
 2817: sub check_and_remove_from_queue {
 2818:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 2819:     my @ungraded_parts;
 2820:     foreach my $part (@{$parts}) {
 2821: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 2822: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 2823: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 2824: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 2825: 		) {
 2826: 	    push(@ungraded_parts, $part);
 2827: 	}
 2828:     }
 2829:     if ( !@ungraded_parts ) {
 2830: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 2831: 					       $cnum,$domain,$stuname);
 2832:     }
 2833: }
 2834: 
 2835: sub handback_files {
 2836:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 2837:     my $portfolio_root = '/userfiles/portfolio';
 2838:     my $res_error;
 2839:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2840:     if ($res_error) {
 2841:         $request->print('<br />'.&navmap_errormsg().'<br />');
 2842:         return;
 2843:     }
 2844:     my @part_response_id = &flatten_responseType($responseType);
 2845:     foreach my $part_response_id (@part_response_id) {
 2846:     	my ($part_id,$resp_id) = @{ $part_response_id };
 2847: 	my $part_resp = join('_',@{ $part_response_id });
 2848:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
 2849:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 2850:                 my $file_counter = 1;
 2851: 		my $file_msg;
 2852:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
 2853:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
 2854:                     my ($directory,$answer_file) = 
 2855:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
 2856:                     my ($answer_name,$answer_ver,$answer_ext) =
 2857: 		        &file_name_version_ext($answer_file);
 2858: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 2859:                     my $getpropath = 1;
 2860: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
 2861: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2862:                     # fix file name
 2863:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 2864:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 2865:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
 2866:             	                                $save_file_name);
 2867:                     if ($result !~ m|^/uploaded/|) {
 2868:                         $request->print('<br /><span class="LC_error">'.
 2869:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 2870:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
 2871:                                         '</span>');
 2872:                     } else {
 2873:                         # mark the file as read only
 2874:                         my @files = ($save_file_name);
 2875:                         my @what = ($symb,$env{'request.course.id'},'handback');
 2876:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
 2877: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 2878: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 2879: 			}
 2880:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 2881: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
 2882: 
 2883:                     }
 2884:                     $request->print("<br />".$fname." will be the uploaded file name");
 2885:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
 2886:                     $file_counter++;
 2887:                 }
 2888: 		my $subject = "File Handed Back by Instructor ";
 2889: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
 2890: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
 2891: 		$message .= ' The returned file(s) are named: '. $file_msg;
 2892: 		$message .= " and can be found in your portfolio space.";
 2893: 		my ($feedurl,$showsymb) = 
 2894: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
 2895:                 my $restitle = &Apache::lonnet::gettitle($symb);
 2896: 		my $msgstatus = 
 2897:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
 2898: 			 ' (File Returned) ['.$restitle.']',$message,undef,
 2899:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
 2900:             }
 2901:         }
 2902:     return;
 2903: }
 2904: 
 2905: sub get_feedurl_and_symb {
 2906:     my ($symb,$uname,$udom) = @_;
 2907:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2908:     $url = &Apache::lonnet::clutter($url);
 2909:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 2910: 					$symb,$udom,$uname);
 2911:     if ($encrypturl =~ /^yes$/i) {
 2912: 	&Apache::lonenc::encrypted(\$url,1);
 2913: 	&Apache::lonenc::encrypted(\$symb,1);
 2914:     }
 2915:     return ($url,$symb);
 2916: }
 2917: 
 2918: sub get_submitted_files {
 2919:     my ($udom,$uname,$partid,$respid,$record) = @_;
 2920:     my @files;
 2921:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 2922:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 2923:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 2924:     	    push(@files,$file_url.$file);
 2925:         }
 2926:     }
 2927:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 2928:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 2929:     }
 2930:     return (\@files);
 2931: }
 2932: 
 2933: # ----------- Provides number of tries since last reset.
 2934: sub get_num_tries {
 2935:     my ($record,$last_reset,$part) = @_;
 2936:     my $timestamp = '';
 2937:     my $num_tries = 0;
 2938:     if ($$record{'version'}) {
 2939:         for (my $version=$$record{'version'};$version>=1;$version--) {
 2940:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 2941:                 $timestamp = $$record{$version.':timestamp'};
 2942:                 if ($timestamp > $last_reset) {
 2943:                     $num_tries ++;
 2944:                 } else {
 2945:                     last;
 2946:                 }
 2947:             }
 2948:         }
 2949:     }
 2950:     return $num_tries;
 2951: }
 2952: 
 2953: # ----------- Determine decrements required in aggregate totals 
 2954: sub decrement_aggs {
 2955:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 2956:     my %decrement = (
 2957:                         attempts => 0,
 2958:                         users => 0,
 2959:                         correct => 0
 2960:                     );
 2961:     $decrement{'attempts'} = $aggtries;
 2962:     if ($solvedstatus =~ /^correct/) {
 2963:         $decrement{'correct'} = 1;
 2964:     }
 2965:     if ($aggtries == $totaltries) {
 2966:         $decrement{'users'} = 1;
 2967:     }
 2968:     foreach my $type (keys(%decrement)) {
 2969:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 2970:     }
 2971:     return;
 2972: }
 2973: 
 2974: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 2975: sub get_last_resets {
 2976:     my ($symb,$courseid,$partids) =@_;
 2977:     my %last_resets;
 2978:     my $cdom = $env{'course.'.$courseid.'.domain'};
 2979:     my $cname = $env{'course.'.$courseid.'.num'};
 2980:     my @keys;
 2981:     foreach my $part (@{$partids}) {
 2982: 	push(@keys,"$symb\0$part\0resettime");
 2983:     }
 2984:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 2985: 				     $cdom,$cname);
 2986:     foreach my $part (@{$partids}) {
 2987: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 2988:     }
 2989:     return %last_resets;
 2990: }
 2991: 
 2992: # ----------- Handles creating versions for portfolio files as answers
 2993: sub version_portfiles {
 2994:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 2995:     my $version_parts = join('|',@$v_flag);
 2996:     my @returned_keys;
 2997:     my $parts = join('|', @$parts_graded);
 2998:     my $portfolio_root = '/userfiles/portfolio';
 2999:     foreach my $key (keys(%$record)) {
 3000:         my $new_portfiles;
 3001:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3002:             my @versioned_portfiles;
 3003:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3004:             foreach my $file (@portfiles) {
 3005:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 3006:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 3007: 		my ($answer_name,$answer_ver,$answer_ext) =
 3008: 		    &file_name_version_ext($answer_file);
 3009:                 my $getpropath = 1;    
 3010:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
 3011:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 3012:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 3013:                 if ($new_answer ne 'problem getting file') {
 3014:                     push(@versioned_portfiles, $directory.$new_answer);
 3015:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 3016:                         [$directory.$new_answer],
 3017:                         [$symb,$env{'request.course.id'},'graded']);
 3018:                 }
 3019:             }
 3020:             $$record{$key} = join(',',@versioned_portfiles);
 3021:             push(@returned_keys,$key);
 3022:         }
 3023:     } 
 3024:     return (@returned_keys);   
 3025: }
 3026: 
 3027: sub get_next_version {
 3028:     my ($answer_name, $answer_ext, $dir_list) = @_;
 3029:     my $version;
 3030:     foreach my $row (@$dir_list) {
 3031:         my ($file) = split(/\&/,$row,2);
 3032:         my ($file_name,$file_version,$file_ext) =
 3033: 	    &file_name_version_ext($file);
 3034:         if (($file_name eq $answer_name) && 
 3035: 	    ($file_ext eq $answer_ext)) {
 3036:                 # gets here if filename and extension match, regardless of version
 3037:                 if ($file_version ne '') {
 3038:                 # a versioned file is found  so save it for later
 3039:                 if ($file_version > $version) {
 3040: 		    $version = $file_version;
 3041: 	        }
 3042:             }
 3043:         }
 3044:     } 
 3045:     $version ++;
 3046:     return($version);
 3047: }
 3048: 
 3049: sub version_selected_portfile {
 3050:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3051:     my ($answer_name,$answer_ver,$answer_ext) =
 3052:         &file_name_version_ext($file_name);
 3053:     my $new_answer;
 3054:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3055:     if($env{'form.copy'} eq '-1') {
 3056:         $new_answer = 'problem getting file';
 3057:     } else {
 3058:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3059:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3060:                             $stu_name,$domain,'copy',
 3061: 		        '/portfolio'.$directory.$new_answer);
 3062:     }    
 3063:     return ($new_answer);
 3064: }
 3065: 
 3066: sub file_name_version_ext {
 3067:     my ($file)=@_;
 3068:     my @file_parts = split(/\./, $file);
 3069:     my ($name,$version,$ext);
 3070:     if (@file_parts > 1) {
 3071: 	$ext=pop(@file_parts);
 3072: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3073: 	    $version=pop(@file_parts);
 3074: 	}
 3075: 	$name=join('.',@file_parts);
 3076:     } else {
 3077: 	$name=join('.',@file_parts);
 3078:     }
 3079:     return($name,$version,$ext);
 3080: }
 3081: 
 3082: #--------------------------------------------------------------------------------------
 3083: #
 3084: #-------------------------- Next few routines handles grading by section or whole class
 3085: #
 3086: #--- Javascript to handle grading by section or whole class
 3087: sub viewgrades_js {
 3088:     my ($request) = shift;
 3089: 
 3090:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3091:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
 3092:    function writePoint(partid,weight,point) {
 3093: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3094: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3095: 	if (point == "textval") {
 3096: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3097: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3098: 		alert("$alertmsg"+parseFloat(point));
 3099: 		var resetbox = false;
 3100: 		for (var i=0; i<radioButton.length; i++) {
 3101: 		    if (radioButton[i].checked) {
 3102: 			textbox.value = i;
 3103: 			resetbox = true;
 3104: 		    }
 3105: 		}
 3106: 		if (!resetbox) {
 3107: 		    textbox.value = "";
 3108: 		}
 3109: 		return;
 3110: 	    }
 3111: 	    if (parseFloat(point) > parseFloat(weight)) {
 3112: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3113: 				   ") greater than the weight for the part. Accept?");
 3114: 		if (resp == false) {
 3115: 		    textbox.value = "";
 3116: 		    return;
 3117: 		}
 3118: 	    }
 3119: 	    for (var i=0; i<radioButton.length; i++) {
 3120: 		radioButton[i].checked=false;
 3121: 		if (parseFloat(point) == i) {
 3122: 		    radioButton[i].checked=true;
 3123: 		}
 3124: 	    }
 3125: 
 3126: 	} else {
 3127: 	    textbox.value = parseFloat(point);
 3128: 	}
 3129: 	for (i=0;i<document.classgrade.total.value;i++) {
 3130: 	    var user = document.classgrade["ctr"+i].value;
 3131: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3132: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3133: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3134: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3135: 	    if (saveval != "correct") {
 3136: 		scorename.value = point;
 3137: 		if (selname[0].selected != true) {
 3138: 		    selname[0].selected = true;
 3139: 		}
 3140: 	    }
 3141: 	}
 3142: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3143:     }
 3144: 
 3145:     function writeRadText(partid,weight) {
 3146: 	var selval   = document.classgrade["SELVAL_"+partid];
 3147: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3148:         var override = document.classgrade["FORCE_"+partid].checked;
 3149: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3150: 	if (selval[1].selected || selval[2].selected) {
 3151: 	    for (var i=0; i<radioButton.length; i++) {
 3152: 		radioButton[i].checked=false;
 3153: 
 3154: 	    }
 3155: 	    textbox.value = "";
 3156: 
 3157: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3158: 		var user = document.classgrade["ctr"+i].value;
 3159: 		user = user.replace(new RegExp(':', 'g'),"_");
 3160: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3161: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3162: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3163: 		if ((saveval != "correct") || override) {
 3164: 		    scorename.value = "";
 3165: 		    if (selval[1].selected) {
 3166: 			selname[1].selected = true;
 3167: 		    } else {
 3168: 			selname[2].selected = true;
 3169: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3170: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3171: 		    }
 3172: 		}
 3173: 	    }
 3174: 	} else {
 3175: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3176: 		var user = document.classgrade["ctr"+i].value;
 3177: 		user = user.replace(new RegExp(':', 'g'),"_");
 3178: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3179: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3180: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3181: 		if ((saveval != "correct") || override) {
 3182: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3183: 		    selname[0].selected = true;
 3184: 		}
 3185: 	    }
 3186: 	}	    
 3187:     }
 3188: 
 3189:     function changeSelect(partid,user) {
 3190: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3191: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3192: 	var point  = textbox.value;
 3193: 	var weight = document.classgrade["weight_"+partid].value;
 3194: 
 3195: 	if (isNaN(point) || parseFloat(point) < 0) {
 3196: 	    alert("$alertmsg"+parseFloat(point));
 3197: 	    textbox.value = "";
 3198: 	    return;
 3199: 	}
 3200: 	if (parseFloat(point) > parseFloat(weight)) {
 3201: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3202: 			       ") greater than the weight of the part. Accept?");
 3203: 	    if (resp == false) {
 3204: 		textbox.value = "";
 3205: 		return;
 3206: 	    }
 3207: 	}
 3208: 	selval[0].selected = true;
 3209:     }
 3210: 
 3211:     function changeOneScore(partid,user) {
 3212: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3213: 	if (selval[1].selected || selval[2].selected) {
 3214: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3215: 	    if (selval[2].selected) {
 3216: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3217: 	    }
 3218:         }
 3219:     }
 3220: 
 3221:     function resetEntry(numpart) {
 3222: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3223: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3224: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3225: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3226: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3227: 	    for (var i=0; i<radioButton.length; i++) {
 3228: 		radioButton[i].checked=false;
 3229: 
 3230: 	    }
 3231: 	    textbox.value = "";
 3232: 	    selval[0].selected = true;
 3233: 
 3234: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3235: 		var user = document.classgrade["ctr"+i].value;
 3236: 		user = user.replace(new RegExp(':', 'g'),"_");
 3237: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3238: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3239: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3240: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3241: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3242: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3243: 		if (saveselval == "excused") {
 3244: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3245: 		} else {
 3246: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3247: 		}
 3248: 	    }
 3249: 	}
 3250:     }
 3251: 
 3252: VIEWJAVASCRIPT
 3253: }
 3254: 
 3255: #--- show scores for a section or whole class w/ option to change/update a score
 3256: sub viewgrades {
 3257:     my ($request,$symb) = @_;
 3258:     &viewgrades_js($request);
 3259: 
 3260:     #need to make sure we have the correct data for later EXT calls, 
 3261:     #thus invalidate the cache
 3262:     &Apache::lonnet::devalidatecourseresdata(
 3263:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3264:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3265:     &Apache::lonnet::clear_EXT_cache_status();
 3266: 
 3267:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3268: 
 3269:     #view individual student submission form - called using Javascript viewOneStudent
 3270:     $result.=&jscriptNform($symb);
 3271: 
 3272:     #beginning of class grading form
 3273:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3274:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3275: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3276: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3277: 	&build_section_inputs().
 3278: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3279: 
 3280:     my ($common_header,$specific_header);
 3281:     if ($env{'form.section'} eq 'all') {
 3282: 	$common_header = &mt('Assign Common Grade to Class');
 3283:         $specific_header = &mt('Assign Grade to Specific Students in Class');
 3284:     } elsif ($env{'form.section'} eq 'none') {
 3285:         $common_header = &mt('Assign Common Grade to Students in no Section');
 3286: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
 3287:     } else {
 3288:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3289:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3290: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3291:     }
 3292:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
 3293:     #radio buttons/text box for assigning points for a section or class.
 3294:     #handles different parts of a problem
 3295:     my $res_error;
 3296:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3297:     if ($res_error) {
 3298:         return &navmap_errormsg();
 3299:     }
 3300:     my %weight = ();
 3301:     my $ctsparts = 0;
 3302:     my %seen = ();
 3303:     my @part_response_id = &flatten_responseType($responseType);
 3304:     foreach my $part_response_id (@part_response_id) {
 3305:     	my ($partid,$respid) = @{ $part_response_id };
 3306: 	my $part_resp = join('_',@{ $part_response_id });
 3307: 	next if $seen{$partid};
 3308: 	$seen{$partid}++;
 3309: 	my $handgrade=$$handgrade{$part_resp};
 3310: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3311: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3312: 
 3313: 	my $display_part=&get_display_part($partid,$symb);
 3314: 	my $radio.='<table border="0"><tr>';  
 3315: 	my $ctr = 0;
 3316: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3317: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3318: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3319: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3320: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3321: 	    $ctr++;
 3322: 	}
 3323: 	$radio.='</tr></table>';
 3324: 	my $line = '<input type="text" name="TEXTVAL_'.
 3325: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 3326: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3327: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3328: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
 3329: 	    'onchange="javascript:writeRadText(\''.$partid.'\','.
 3330: 		$weight{$partid}.')"> '.
 3331: 	    '<option selected="selected"> </option>'.
 3332: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3333: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3334: 	    '</select></td>'.
 3335:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3336: 	$line.='<input type="hidden" name="partid_'.
 3337: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3338: 	$line.='<input type="hidden" name="weight_'.
 3339: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3340: 
 3341: 	$result.=
 3342: 	    &Apache::loncommon::start_data_table_row()."\n".
 3343: 	    '<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>'.
 3344: 	    &Apache::loncommon::end_data_table_row()."\n";
 3345: 	$ctsparts++;
 3346:     }
 3347:     $result.=&Apache::loncommon::end_data_table()."\n".
 3348: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3349:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3350: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 3351: 
 3352:     #table listing all the students in a section/class
 3353:     #header of table
 3354:     $result.= '<h3>'.$specific_header.'</h3>'.
 3355:               &Apache::loncommon::start_data_table().
 3356: 	      &Apache::loncommon::start_data_table_header_row().
 3357: 	      '<th>'.&mt('No.').'</th>'.
 3358: 	      '<th>'.&nameUserString('header')."</th>\n";
 3359:     my $partserror;
 3360:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3361:     if ($partserror) {
 3362:         return &navmap_errormsg();
 3363:     }
 3364:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3365:     my @partids = ();
 3366:     foreach my $part (@parts) {
 3367: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3368:         my $narrowtext = &mt('Tries');
 3369: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3370: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3371: 	my ($partid) = &split_part_type($part);
 3372:         push(@partids,$partid);
 3373: #
 3374: # FIXME: Looks like $display looks at English text
 3375: #
 3376: 	my $display_part=&get_display_part($partid,$symb);
 3377: 	if ($display =~ /^Partial Credit Factor/) {
 3378: 	    $result.='<th>'.
 3379: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
 3380: 		    $display_part,$weight{$partid}).'</th>'."\n";
 3381: 	    next;
 3382: 	    
 3383: 	} else {
 3384: 	    if ($display =~ /Problem Status/) {
 3385: 		my $grade_status_mt = &mt('Grade Status');
 3386: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3387: 	    }
 3388: 	    my $part_mt = &mt('Part:');
 3389: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3390: 	}
 3391: 
 3392: 	$result.='<th>'.$display.'</th>'."\n";
 3393:     }
 3394:     $result.=&Apache::loncommon::end_data_table_header_row();
 3395: 
 3396:     my %last_resets = 
 3397: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3398: 
 3399:     #get info for each student
 3400:     #list all the students - with points and grade status
 3401:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3402:     my $ctr = 0;
 3403:     foreach (sort 
 3404: 	     {
 3405: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3406: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3407: 		 }
 3408: 		 return $a cmp $b;
 3409: 	     } (keys(%$fullname))) {
 3410: 	$ctr++;
 3411: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3412: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3413:     }
 3414:     $result.=&Apache::loncommon::end_data_table();
 3415:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3416:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3417: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 3418:     if (scalar(%$fullname) eq 0) {
 3419: 	my $colspan=3+scalar(@parts);
 3420: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3421:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3422: 	$result='<span class="LC_warning">'.
 3423: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3424: 	        $section_display, $stu_status).
 3425: 	    '</span>';
 3426:     }
 3427:     return $result;
 3428: }
 3429: 
 3430: #--- call by previous routine to display each student
 3431: sub viewstudentgrade {
 3432:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3433:     my ($uname,$udom) = split(/:/,$student);
 3434:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3435:     my %aggregates = (); 
 3436:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3437: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3438: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3439: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3440: 	'\');" target="_self">'.$fullname.'</a> '.
 3441: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3442:     $student=~s/:/_/; # colon doen't work in javascript for names
 3443:     foreach my $apart (@$parts) {
 3444: 	my ($part,$type) = &split_part_type($apart);
 3445: 	my $score=$record{"resource.$part.$type"};
 3446:         $result.='<td align="center">';
 3447:         my ($aggtries,$totaltries);
 3448:         unless (exists($aggregates{$part})) {
 3449: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3450: 
 3451: 	    $aggtries = $totaltries;
 3452:             if ($$last_resets{$part}) {  
 3453:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3454: 					   $part);
 3455:             }
 3456:             $result.='<input type="hidden" name="'.
 3457:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3458:             $result.='<input type="hidden" name="'.
 3459:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3460:             $aggregates{$part} = 1;
 3461:         }
 3462: 	if ($type eq 'awarded') {
 3463: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3464: 	    $result.='<input type="hidden" name="'.
 3465: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3466: 	    $result.='<input type="text" name="'.
 3467: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3468:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3469: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3470: 	} elsif ($type eq 'solved') {
 3471: 	    my ($status,$foo)=split(/_/,$score,2);
 3472: 	    $status = 'nothing' if ($status eq '');
 3473: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3474: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3475: 	    $result.='&nbsp;<select name="'.
 3476: 		'GD_'.$student.'_'.$part.'_solved" '.
 3477:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3478: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3479: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3480: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3481: 	    $result.="</select>&nbsp;</td>\n";
 3482: 	} else {
 3483: 	    $result.='<input type="hidden" name="'.
 3484: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3485: 		    "\n";
 3486: 	    $result.='<input type="text" name="'.
 3487: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3488: 		'value="'.$score.'" size="4" /></td>'."\n";
 3489: 	}
 3490:     }
 3491:     $result.=&Apache::loncommon::end_data_table_row();
 3492:     return $result;
 3493: }
 3494: 
 3495: #--- change scores for all the students in a section/class
 3496: #    record does not get update if unchanged
 3497: sub editgrades {
 3498:     my ($request,$symb) = @_;
 3499: 
 3500:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3501:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3502:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3503: 
 3504:     my $result= &Apache::loncommon::start_data_table().
 3505: 	&Apache::loncommon::start_data_table_header_row().
 3506: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3507: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3508:     my %scoreptr = (
 3509: 		    'correct'  =>'correct_by_override',
 3510: 		    'incorrect'=>'incorrect_by_override',
 3511: 		    'excused'  =>'excused',
 3512: 		    'ungraded' =>'ungraded_attempted',
 3513:                     'credited' =>'credit_attempted',
 3514: 		    'nothing'  => '',
 3515: 		    );
 3516:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3517: 
 3518:     my (@partid);
 3519:     my %weight = ();
 3520:     my %columns = ();
 3521:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3522: 
 3523:     my $partserror;
 3524:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3525:     if ($partserror) {
 3526:         return &navmap_errormsg();
 3527:     }
 3528:     my $header;
 3529:     while ($ctr < $env{'form.totalparts'}) {
 3530: 	my $partid = $env{'form.partid_'.$ctr};
 3531: 	push(@partid,$partid);
 3532: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3533: 	$ctr++;
 3534:     }
 3535:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3536:     foreach my $partid (@partid) {
 3537: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3538: 	    '<th align="center">'.&mt('New Score').'</th>';
 3539: 	$columns{$partid}=2;
 3540: 	foreach my $stores (@parts) {
 3541: 	    my ($part,$type) = &split_part_type($stores);
 3542: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3543: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3544: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3545: 	    $display =~ s/\[Part: \Q$part\E\]//;
 3546:             my $narrowtext = &mt('Tries');
 3547: 	    $display =~ s/Number of Attempts/$narrowtext/;
 3548: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 3549: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 3550: 	    $columns{$partid}+=2;
 3551: 	}
 3552:     }
 3553:     foreach my $partid (@partid) {
 3554: 	my $display_part=&get_display_part($partid,$symb);
 3555: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3556: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3557: 	    '</th>';
 3558: 
 3559:     }
 3560:     $result .= &Apache::loncommon::end_data_table_header_row().
 3561: 	&Apache::loncommon::start_data_table_header_row().
 3562: 	$header.
 3563: 	&Apache::loncommon::end_data_table_header_row();
 3564:     my @noupdate;
 3565:     my ($updateCtr,$noupdateCtr) = (1,1);
 3566:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3567: 	my $line;
 3568: 	my $user = $env{'form.ctr'.$i};
 3569: 	my ($uname,$udom)=split(/:/,$user);
 3570: 	my %newrecord;
 3571: 	my $updateflag = 0;
 3572: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3573: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3574: 	if (!&canmodify($usec)) {
 3575: 	    my $numcols=scalar(@partid)*4+2;
 3576: 	    push(@noupdate,
 3577: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 3578: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 3579: 	    next;
 3580: 	}
 3581:         my %aggregate = ();
 3582:         my $aggregateflag = 0;
 3583: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3584: 	foreach (@partid) {
 3585: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3586: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3587: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3588: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3589: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3590: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3591: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3592: 	    my $score;
 3593: 	    if ($partial eq '') {
 3594: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3595: 	    } elsif ($partial > 0) {
 3596: 		$score = 'correct_by_override';
 3597: 	    } elsif ($partial == 0) {
 3598: 		$score = 'incorrect_by_override';
 3599: 	    }
 3600: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3601: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3602: 
 3603: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3604: 		"$env{'user.name'}:$env{'user.domain'}";
 3605: 	    if ($dropMenu eq 'reset status' &&
 3606: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3607: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3608: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3609: 		$newrecord{'resource.'.$_.'.award'} = '';
 3610: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3611: 		$updateflag = 1;
 3612:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3613:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3614:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3615:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3616:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3617:                     $aggregateflag = 1;
 3618:                 }
 3619: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3620: 		$updateflag = 1;
 3621: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3622: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3623: 		$rec_update++;
 3624: 	    }
 3625: 
 3626: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3627: 		'<td align="center">'.$awarded.
 3628: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3629: 
 3630: 
 3631: 	    my $partid=$_;
 3632: 	    foreach my $stores (@parts) {
 3633: 		my ($part,$type) = &split_part_type($stores);
 3634: 		if ($part !~ m/^\Q$partid\E/) { next;}
 3635: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 3636: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 3637: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 3638: 		if ($awarded ne '' && $awarded ne $old_aw) {
 3639: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 3640: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3641: 		    $updateflag=1;
 3642: 		}
 3643: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3644: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 3645: 	    }
 3646: 	}
 3647: 	$line.="\n";
 3648: 
 3649: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3650: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3651: 
 3652: 	if ($updateflag) {
 3653: 	    $count++;
 3654: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 3655: 				    $udom,$uname);
 3656: 
 3657: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 3658: 					      $cnum,$udom,$uname)) {
 3659: 		# need to figure out if should be in queue.
 3660: 		my %record =  
 3661: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3662: 					     $udom,$uname);
 3663: 		my $all_graded = 1;
 3664: 		my $none_graded = 1;
 3665: 		foreach my $part (@parts) {
 3666: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 3667: 			$all_graded = 0;
 3668: 		    } else {
 3669: 			$none_graded = 0;
 3670: 		    }
 3671: 		}
 3672: 
 3673: 		if ($all_graded || $none_graded) {
 3674: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 3675: 							   $symb,$cdom,$cnum,
 3676: 							   $udom,$uname);
 3677: 		}
 3678: 	    }
 3679: 
 3680: 	    $result.=&Apache::loncommon::start_data_table_row().
 3681: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 3682: 		&Apache::loncommon::end_data_table_row();
 3683: 	    $updateCtr++;
 3684: 	} else {
 3685: 	    push(@noupdate,
 3686: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 3687: 	    $noupdateCtr++;
 3688: 	}
 3689:         if ($aggregateflag) {
 3690:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3691: 				  $cdom,$cnum);
 3692:         }
 3693:     }
 3694:     if (@noupdate) {
 3695: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 3696: 	my $numcols=scalar(@partid)*4+2;
 3697: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 3698: 	    '<td align="center" colspan="'.$numcols.'">'.
 3699: 	    &mt('No Changes Occurred For the Students Below').
 3700: 	    '</td>'.
 3701: 	    &Apache::loncommon::end_data_table_row();
 3702: 	foreach my $line (@noupdate) {
 3703: 	    $result.=
 3704: 		&Apache::loncommon::start_data_table_row().
 3705: 		$line.
 3706: 		&Apache::loncommon::end_data_table_row();
 3707: 	}
 3708:     }
 3709:     $result .= &Apache::loncommon::end_data_table();
 3710:     my $msg = '<p><b>'.
 3711: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 3712: 	    $rec_update,$count).'</b><br />'.
 3713: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 3714: 	'</b></p>';
 3715:     return $title.$msg.$result;
 3716: }
 3717: 
 3718: sub split_part_type {
 3719:     my ($partstr) = @_;
 3720:     my ($temp,@allparts)=split(/_/,$partstr);
 3721:     my $type=pop(@allparts);
 3722:     my $part=join('_',@allparts);
 3723:     return ($part,$type);
 3724: }
 3725: 
 3726: #------------- end of section for handling grading by section/class ---------
 3727: #
 3728: #----------------------------------------------------------------------------
 3729: 
 3730: 
 3731: #----------------------------------------------------------------------------
 3732: #
 3733: #-------------------------- Next few routines handles grading by csv upload
 3734: #
 3735: #--- Javascript to handle csv upload
 3736: sub csvupload_javascript_reverse_associate {
 3737:     my $error1=&mt('You need to specify the username or the student/employee ID');
 3738:     my $error2=&mt('You need to specify at least one grading field');
 3739:   return(<<ENDPICK);
 3740:   function verify(vf) {
 3741:     var foundsomething=0;
 3742:     var founduname=0;
 3743:     var foundID=0;
 3744:     for (i=0;i<=vf.nfields.value;i++) {
 3745:       tw=eval('vf.f'+i+'.selectedIndex');
 3746:       if (i==0 && tw!=0) { foundID=1; }
 3747:       if (i==1 && tw!=0) { founduname=1; }
 3748:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 3749:     }
 3750:     if (founduname==0 && foundID==0) {
 3751: 	alert('$error1');
 3752: 	return;
 3753:     }
 3754:     if (foundsomething==0) {
 3755: 	alert('$error2');
 3756: 	return;
 3757:     }
 3758:     vf.submit();
 3759:   }
 3760:   function flip(vf,tf) {
 3761:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3762:     var i;
 3763:     for (i=0;i<=vf.nfields.value;i++) {
 3764:       //can not pick the same destination field for both name and domain
 3765:       if (((i ==0)||(i ==1)) && 
 3766:           ((tf==0)||(tf==1)) && 
 3767:           (i!=tf) &&
 3768:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3769:         eval('vf.f'+i+'.selectedIndex=0;')
 3770:       }
 3771:     }
 3772:   }
 3773: ENDPICK
 3774: }
 3775: 
 3776: sub csvupload_javascript_forward_associate {
 3777:     my $error1=&mt('You need to specify the username or the student/employee ID');
 3778:     my $error2=&mt('You need to specify at least one grading field');
 3779:   return(<<ENDPICK);
 3780:   function verify(vf) {
 3781:     var foundsomething=0;
 3782:     var founduname=0;
 3783:     var foundID=0;
 3784:     for (i=0;i<=vf.nfields.value;i++) {
 3785:       tw=eval('vf.f'+i+'.selectedIndex');
 3786:       if (tw==1) { foundID=1; }
 3787:       if (tw==2) { founduname=1; }
 3788:       if (tw>3) { foundsomething=1; }
 3789:     }
 3790:     if (founduname==0 && foundID==0) {
 3791: 	alert('$error1');
 3792: 	return;
 3793:     }
 3794:     if (foundsomething==0) {
 3795: 	alert('$error2');
 3796: 	return;
 3797:     }
 3798:     vf.submit();
 3799:   }
 3800:   function flip(vf,tf) {
 3801:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3802:     var i;
 3803:     //can not pick the same destination field twice
 3804:     for (i=0;i<=vf.nfields.value;i++) {
 3805:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3806:         eval('vf.f'+i+'.selectedIndex=0;')
 3807:       }
 3808:     }
 3809:   }
 3810: ENDPICK
 3811: }
 3812: 
 3813: sub csvuploadmap_header {
 3814:     my ($request,$symb,$datatoken,$distotal)= @_;
 3815:     my $javascript;
 3816:     if ($env{'form.upfile_associate'} eq 'reverse') {
 3817: 	$javascript=&csvupload_javascript_reverse_associate();
 3818:     } else {
 3819: 	$javascript=&csvupload_javascript_forward_associate();
 3820:     }
 3821: 
 3822:     $symb = &Apache::lonenc::check_encrypt($symb);
 3823:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
 3824:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
 3825:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
 3826:     my $reverse=&mt("Reverse Association");
 3827:     $request->print(<<ENDPICK);
 3828: <br />
 3829: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 3830: <input type="hidden" name="associate"  value="" />
 3831: <input type="hidden" name="phase"      value="three" />
 3832: <input type="hidden" name="datatoken"  value="$datatoken" />
 3833: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 3834: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 3835: <input type="hidden" name="upfile_associate" 
 3836:                                        value="$env{'form.upfile_associate'}" />
 3837: <input type="hidden" name="symb"       value="$symb" />
 3838: <input type="hidden" name="command"    value="csvuploadoptions" />
 3839: <hr />
 3840: ENDPICK
 3841:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
 3842:     return '';
 3843: 
 3844: }
 3845: 
 3846: sub csvupload_fields {
 3847:     my ($symb,$errorref) = @_;
 3848:     my (@parts) = &getpartlist($symb,$errorref);
 3849:     if (ref($errorref)) {
 3850:         if ($$errorref) {
 3851:             return;
 3852:         }
 3853:     }
 3854: 
 3855:     my @fields=(['ID','Student/Employee ID'],
 3856: 		['username','Student Username'],
 3857: 		['domain','Student Domain']);
 3858:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3859:     foreach my $part (sort(@parts)) {
 3860: 	my @datum;
 3861: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3862: 	my $name=$part;
 3863: 	if  (!$display) { $display = $name; }
 3864: 	@datum=($name,$display);
 3865: 	if ($name=~/^stores_(.*)_awarded/) {
 3866: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 3867: 	}
 3868: 	push(@fields,\@datum);
 3869:     }
 3870:     return (@fields);
 3871: }
 3872: 
 3873: sub csvuploadmap_footer {
 3874:     my ($request,$i,$keyfields) =@_;
 3875:     $request->print(<<ENDPICK);
 3876: </table>
 3877: <input type="hidden" name="nfields" value="$i" />
 3878: <input type="hidden" name="keyfields" value="$keyfields" />
 3879: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
 3880: </form>
 3881: ENDPICK
 3882: }
 3883: 
 3884: sub checkforfile_js {
 3885:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 3886:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
 3887:     function checkUpload(formname) {
 3888: 	if (formname.upfile.value == "") {
 3889: 	    alert("$alertmsg");
 3890: 	    return false;
 3891: 	}
 3892: 	formname.submit();
 3893:     }
 3894: CSVFORMJS
 3895:     return $result;
 3896: }
 3897: 
 3898: sub upcsvScores_form {
 3899:     my ($request,$symb) = @_;
 3900:     if (!$symb) {return '';}
 3901:     my $result=&checkforfile_js();
 3902:     $result.=&Apache::loncommon::start_data_table().
 3903:              &Apache::loncommon::start_data_table_header_row().
 3904:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
 3905:              &Apache::loncommon::end_data_table_header_row().
 3906:              &Apache::loncommon::start_data_table_row().'<td>';
 3907:     my $upload=&mt("Upload Scores");
 3908:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 3909:     my $ignore=&mt('Ignore First Line');
 3910:     $symb = &Apache::lonenc::check_encrypt($symb);
 3911:     $result.=<<ENDUPFORM;
 3912: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3913: <input type="hidden" name="symb" value="$symb" />
 3914: <input type="hidden" name="command" value="csvuploadmap" />
 3915: $upfile_select
 3916: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 3917: </form>
 3918: ENDUPFORM
 3919:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 3920:                            &mt("How do I create a CSV file from a spreadsheet")).
 3921:              '</td>'.
 3922:             &Apache::loncommon::end_data_table_row().
 3923:             &Apache::loncommon::end_data_table();
 3924:     return $result;
 3925: }
 3926: 
 3927: 
 3928: sub csvuploadmap {
 3929:     my ($request,$symb)= @_;
 3930:     if (!$symb) {return '';}
 3931: 
 3932:     my $datatoken;
 3933:     if (!$env{'form.datatoken'}) {
 3934: 	$datatoken=&Apache::loncommon::upfile_store($request);
 3935:     } else {
 3936: 	$datatoken=$env{'form.datatoken'};
 3937: 	&Apache::loncommon::load_tmp_file($request);
 3938:     }
 3939:     my @records=&Apache::loncommon::upfile_record_sep();
 3940:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 3941:     my ($i,$keyfields);
 3942:     if (@records) {
 3943:         my $fieldserror;
 3944: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 3945:         if ($fieldserror) {
 3946:             $request->print(&navmap_errormsg());
 3947:             return;
 3948:         }
 3949: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 3950: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 3951: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 3952: 							  \@fields);
 3953: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 3954: 	    chop($keyfields);
 3955: 	} else {
 3956: 	    unshift(@fields,['none','']);
 3957: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 3958: 							    \@fields);
 3959:             foreach my $rec (@records) {
 3960:                 my %temp = &Apache::loncommon::record_sep($rec);
 3961:                 if (%temp) {
 3962:                     $keyfields=join(',',sort(keys(%temp)));
 3963:                     last;
 3964:                 }
 3965:             }
 3966: 	}
 3967:     }
 3968:     &csvuploadmap_footer($request,$i,$keyfields);
 3969: 
 3970:     return '';
 3971: }
 3972: 
 3973: sub csvuploadoptions {
 3974:     my ($request,$symb)= @_;
 3975:     my $overwrite=&mt('Overwrite any existing score');
 3976:     $request->print(<<ENDPICK);
 3977: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3978: <input type="hidden" name="command"    value="csvuploadassign" />
 3979: <p>
 3980: <label>
 3981:    <input type="checkbox" name="overwite_scores" checked="checked" />
 3982:    $overwrite
 3983: </label>
 3984: </p>
 3985: ENDPICK
 3986:     my %fields=&get_fields();
 3987:     if (!defined($fields{'domain'})) {
 3988: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 3989: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
 3990:     }
 3991:     foreach my $key (sort(keys(%env))) {
 3992: 	if ($key !~ /^form\.(.*)$/) { next; }
 3993: 	my $cleankey=$1;
 3994: 	if ($cleankey eq 'command') { next; }
 3995: 	$request->print('<input type="hidden" name="'.$cleankey.
 3996: 			'"  value="'.$env{$key}.'" />'."\n");
 3997:     }
 3998:     # FIXME do a check for any duplicated user ids...
 3999:     # FIXME do a check for any invalid user ids?...
 4000:     $request->print('<input type="submit" value="Assign Grades" /><br />
 4001: <hr /></form>'."\n");
 4002:     return '';
 4003: }
 4004: 
 4005: sub get_fields {
 4006:     my %fields;
 4007:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4008:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4009: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4010: 	    if ($env{'form.f'.$i} ne 'none') {
 4011: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4012: 	    }
 4013: 	} else {
 4014: 	    if ($env{'form.f'.$i} ne 'none') {
 4015: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4016: 	    }
 4017: 	}
 4018:     }
 4019:     return %fields;
 4020: }
 4021: 
 4022: sub csvuploadassign {
 4023:     my ($request,$symb)= @_;
 4024:     if (!$symb) {return '';}
 4025:     my $error_msg = '';
 4026:     &Apache::loncommon::load_tmp_file($request);
 4027:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4028:     my %fields=&get_fields();
 4029:     my $courseid=$env{'request.course.id'};
 4030:     my ($classlist) = &getclasslist('all',0);
 4031:     my @notallowed;
 4032:     my @skipped;
 4033:     my $countdone=0;
 4034:     foreach my $grade (@gradedata) {
 4035: 	my %entries=&Apache::loncommon::record_sep($grade);
 4036: 	my $domain;
 4037: 	if ($entries{$fields{'domain'}}) {
 4038: 	    $domain=$entries{$fields{'domain'}};
 4039: 	} else {
 4040: 	    $domain=$env{'form.default_domain'};
 4041: 	}
 4042: 	$domain=~s/\s//g;
 4043: 	my $username=$entries{$fields{'username'}};
 4044: 	$username=~s/\s//g;
 4045: 	if (!$username) {
 4046: 	    my $id=$entries{$fields{'ID'}};
 4047: 	    $id=~s/\s//g;
 4048: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4049: 	    $username=$ids{$id};
 4050: 	}
 4051: 	if (!exists($$classlist{"$username:$domain"})) {
 4052: 	    my $id=$entries{$fields{'ID'}};
 4053: 	    $id=~s/\s//g;
 4054: 	    if ($id) {
 4055: 		push(@skipped,"$id:$domain");
 4056: 	    } else {
 4057: 		push(@skipped,"$username:$domain");
 4058: 	    }
 4059: 	    next;
 4060: 	}
 4061: 	my $usec=$classlist->{"$username:$domain"}[5];
 4062: 	if (!&canmodify($usec)) {
 4063: 	    push(@notallowed,"$username:$domain");
 4064: 	    next;
 4065: 	}
 4066: 	my %points;
 4067: 	my %grades;
 4068: 	foreach my $dest (keys(%fields)) {
 4069: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4070: 		$dest eq 'domain') { next; }
 4071: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4072: 	    if ($dest=~/stores_(.*)_points/) {
 4073: 		my $part=$1;
 4074: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4075: 					      $symb,$domain,$username);
 4076:                 if ($wgt) {
 4077:                     $entries{$fields{$dest}}=~s/\s//g;
 4078:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4079:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4080:                                           : 'correct_by_override';
 4081:                     $grades{"resource.$part.awarded"}=$pcr;
 4082:                     $grades{"resource.$part.solved"}=$award;
 4083:                     $points{$part}=1;
 4084:                 } else {
 4085:                     $error_msg = "<br />" .
 4086:                         &mt("Some point values were assigned"
 4087:                             ." for problems with a weight "
 4088:                             ."of zero. These values were "
 4089:                             ."ignored.");
 4090:                 }
 4091: 	    } else {
 4092: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4093: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4094: 		my $store_key=$dest;
 4095: 		$store_key=~s/^stores/resource/;
 4096: 		$store_key=~s/_/\./g;
 4097: 		$grades{$store_key}=$entries{$fields{$dest}};
 4098: 	    }
 4099: 	}
 4100: 	if (! %grades) { 
 4101:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4102:         } else {
 4103: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4104: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4105: 					   $env{'request.course.id'},
 4106: 					   $domain,$username);
 4107: 	   if ($result eq 'ok') {
 4108: # Successfully stored
 4109: 	      $request->print('.');
 4110: # Remove from grading queue
 4111:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
 4112:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
 4113:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
 4114:                                              $domain,$username);
 4115:               $countdone++;
 4116:            } else {
 4117: 	      $request->print("<p><span class=\"LC_error\">".
 4118:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4119:                                   "$username:$domain",$result)."</span></p>");
 4120: 	   }
 4121: 	   $request->rflush();
 4122:         }
 4123:     }
 4124:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 4125:     if (@skipped) {
 4126: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 4127:         $request->print(join(', ',@skipped));
 4128:     }
 4129:     if (@notallowed) {
 4130: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 4131: 	$request->print(join(', ',@notallowed));
 4132:     }
 4133:     $request->print("<br />\n");
 4134:     return $error_msg;
 4135: }
 4136: #------------- end of section for handling csv file upload ---------
 4137: #
 4138: #-------------------------------------------------------------------
 4139: #
 4140: #-------------- Next few routines handle grading by page/sequence
 4141: #
 4142: #--- Select a page/sequence and a student to grade
 4143: sub pickStudentPage {
 4144:     my ($request,$symb) = @_;
 4145: 
 4146:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4147:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
 4148: 
 4149: function checkPickOne(formname) {
 4150:     if (radioSelection(formname.student) == null) {
 4151: 	alert("$alertmsg");
 4152: 	return;
 4153:     }
 4154:     ptr = pullDownSelection(formname.selectpage);
 4155:     formname.page.value = formname["page"+ptr].value;
 4156:     formname.title.value = formname["title"+ptr].value;
 4157:     formname.submit();
 4158: }
 4159: 
 4160: LISTJAVASCRIPT
 4161:     &commonJSfunctions($request);
 4162: 
 4163:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4164:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4165:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4166: 
 4167:     my $result='<h3><span class="LC_info">&nbsp;'.
 4168: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4169: 
 4170:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4171:     my $map_error;
 4172:     my ($titles,$symbx) = &getSymbMap($map_error);
 4173:     if ($map_error) {
 4174:         $request->print(&navmap_errormsg());
 4175:         return; 
 4176:     }
 4177:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4178: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4179: #    my $type=($curpage =~ /\.(page|sequence)/);
 4180:     my $select = '<select name="selectpage">'."\n";
 4181:     my $ctr=0;
 4182:     foreach (@$titles) {
 4183: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4184: 	$select.='<option value="'.$ctr.'" '.
 4185: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4186: 	    '>'.$showtitle.'</option>'."\n";
 4187: 	$ctr++;
 4188:     }
 4189:     $select.= '</select>';
 4190:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
 4191: 
 4192:     $ctr=0;
 4193:     foreach (@$titles) {
 4194: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4195: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4196: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4197: 	$ctr++;
 4198:     }
 4199:     $result.='<input type="hidden" name="page" />'."\n".
 4200: 	'<input type="hidden" name="title" />'."\n";
 4201: 
 4202:     my $options =
 4203: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
 4204: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
 4205:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
 4206: 
 4207:     $options =
 4208: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
 4209: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
 4210: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
 4211:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
 4212:     
 4213:     $result.=&build_section_inputs();
 4214:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4215:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4216: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4217: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."<br />\n";
 4218: 
 4219:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
 4220: 
 4221:     $result.='&nbsp;<input type="button" '.
 4222:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4223: 
 4224:     $request->print($result);
 4225: 
 4226:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4227: 	&Apache::loncommon::start_data_table().
 4228: 	&Apache::loncommon::start_data_table_header_row().
 4229: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4230: 	'<th>'.&nameUserString('header').'</th>'.
 4231: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4232: 	'<th>'.&nameUserString('header').'</th>'.
 4233: 	&Apache::loncommon::end_data_table_header_row();
 4234:  
 4235:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4236:     my $ptr = 1;
 4237:     foreach my $student (sort 
 4238: 			 {
 4239: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4240: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4241: 			     }
 4242: 			     return $a cmp $b;
 4243: 			 } (keys(%$fullname))) {
 4244: 	my ($uname,$udom) = split(/:/,$student);
 4245: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4246:                                   : '</td>');
 4247: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4248: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4249: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4250: 	$studentTable.=
 4251: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4252:                          : '');
 4253: 	$ptr++;
 4254:     }
 4255:     if ($ptr%2 == 0) {
 4256: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4257: 	    &Apache::loncommon::end_data_table_row();
 4258:     }
 4259:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4260:     $studentTable.='<input type="button" '.
 4261:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4262: 
 4263:     $request->print($studentTable);
 4264: 
 4265:     return '';
 4266: }
 4267: 
 4268: sub getSymbMap {
 4269:     my ($map_error) = @_;
 4270:     my $navmap = Apache::lonnavmaps::navmap->new();
 4271:     unless (ref($navmap)) {
 4272:         if (ref($map_error)) {
 4273:             $$map_error = 'navmap';
 4274:         }
 4275:         return;
 4276:     }
 4277:     my %symbx = ();
 4278:     my @titles = ();
 4279:     my $minder = 0;
 4280: 
 4281:     # Gather every sequence that has problems.
 4282:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4283: 					       1,0,1);
 4284:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4285: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4286: 	    my $title = $minder.'.'.
 4287: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4288: 	    push(@titles, $title); # minder in case two titles are identical
 4289: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4290: 	    $minder++;
 4291: 	}
 4292:     }
 4293:     return \@titles,\%symbx;
 4294: }
 4295: 
 4296: #
 4297: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4298: sub displayPage {
 4299:     my ($request,$symb) = @_;
 4300:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4301:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4302:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4303:     my $pageTitle = $env{'form.page'};
 4304:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4305:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4306:     my $usec=$classlist->{$env{'form.student'}}[5];
 4307: 
 4308:     #need to make sure we have the correct data for later EXT calls, 
 4309:     #thus invalidate the cache
 4310:     &Apache::lonnet::devalidatecourseresdata(
 4311:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4312:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4313:     &Apache::lonnet::clear_EXT_cache_status();
 4314: 
 4315:     if (!&canview($usec)) {
 4316: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
 4317: 	return;
 4318:     }
 4319:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4320:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4321: 	'</h3>'."\n";
 4322:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4323:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4324: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4325:     } else {
 4326: 	delete($env{'form.CODE'});
 4327:     }
 4328:     &sub_page_js($request);
 4329:     $request->print($result);
 4330: 
 4331:     my $navmap = Apache::lonnavmaps::navmap->new();
 4332:     unless (ref($navmap)) {
 4333:         $request->print(&navmap_errormsg());
 4334:         return;
 4335:     }
 4336:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4337:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4338:     if (!$map) {
 4339: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4340: 	return; 
 4341:     }
 4342:     my $iterator = $navmap->getIterator($map->map_start(),
 4343: 					$map->map_finish());
 4344: 
 4345:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4346: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4347: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4348: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4349: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4350: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4351: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4352: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
 4353: 
 4354:     if (defined($env{'form.CODE'})) {
 4355: 	$studentTable.=
 4356: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4357:     }
 4358:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4359: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4360: 
 4361:     $studentTable.='&nbsp;<span class="LC_info">'.
 4362:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 4363:         '</span>'."\n".
 4364: 	&Apache::loncommon::start_data_table().
 4365: 	&Apache::loncommon::start_data_table_header_row().
 4366: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
 4367: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4368: 	&Apache::loncommon::end_data_table_header_row();
 4369: 
 4370:     &Apache::lonxml::clear_problem_counter();
 4371:     my ($depth,$question,$prob) = (1,1,1);
 4372:     $iterator->next(); # skip the first BEGIN_MAP
 4373:     my $curRes = $iterator->next(); # for "current resource"
 4374:     while ($depth > 0) {
 4375:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4376:         if($curRes == $iterator->END_MAP) { $depth--; }
 4377: 
 4378:         if (ref($curRes) && $curRes->is_problem()) {
 4379: 	    my $parts = $curRes->parts();
 4380:             my $title = $curRes->compTitle();
 4381: 	    my $symbx = $curRes->symb();
 4382: 	    $studentTable.=
 4383: 		&Apache::loncommon::start_data_table_row().
 4384: 		'<td align="center" valign="top" >'.$prob.
 4385: 		(scalar(@{$parts}) == 1 ? '' 
 4386: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
 4387: 							scalar(@{$parts}))
 4388: 		 ).
 4389: 		 '</td>';
 4390: 	    $studentTable.='<td valign="top">';
 4391: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4392: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4393: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4394: 					     undef,'both',\%form);
 4395: 	    } else {
 4396: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4397: 		$companswer =~ s|<form(.*?)>||g;
 4398: 		$companswer =~ s|</form>||g;
 4399: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4400: #		    $companswer =~ s/$1/ /ms;
 4401: #		    $request->print('match='.$1."<br />\n");
 4402: #		}
 4403: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4404: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 4405: 	    }
 4406: 
 4407: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4408: 
 4409: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4410: 		if ($record{'version'} eq '') {
 4411: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4412: 		} else {
 4413: 		    my %responseType = ();
 4414: 		    foreach my $partid (@{$parts}) {
 4415: 			my @responseIds =$curRes->responseIds($partid);
 4416: 			my @responseType =$curRes->responseType($partid);
 4417: 			my %responseIds;
 4418: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4419: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4420: 			}
 4421: 			$responseType{$partid} = \%responseIds;
 4422: 		    }
 4423: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4424: 
 4425: 		}
 4426: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4427: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4428: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4429: 									$env{'request.course.id'},
 4430: 									'','.submission');
 4431:  
 4432: 	    }
 4433: 	    if (&canmodify($usec)) {
 4434:             $studentTable.=&gradeBox_start();
 4435: 		foreach my $partid (@{$parts}) {
 4436: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4437: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4438: 		    $question++;
 4439: 		}
 4440:             $studentTable.=&gradeBox_end();
 4441: 		$prob++;
 4442: 	    }
 4443: 	    $studentTable.='</td></tr>';
 4444: 
 4445: 	}
 4446:         $curRes = $iterator->next();
 4447:     }
 4448: 
 4449:     $studentTable.=
 4450:         '</table>'."\n".
 4451:         '<input type="button" value="'.&mt('Save').'" '.
 4452:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4453:         '</form>'."\n";
 4454:     $request->print($studentTable);
 4455: 
 4456:     return '';
 4457: }
 4458: 
 4459: sub displaySubByDates {
 4460:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4461:     my $isCODE=0;
 4462:     my $isTask = ($symb =~/\.task$/);
 4463:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4464:     my $studentTable=&Apache::loncommon::start_data_table().
 4465: 	&Apache::loncommon::start_data_table_header_row().
 4466: 	'<th>'.&mt('Date/Time').'</th>'.
 4467: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4468: 	'<th>'.&mt('Submission').'</th>'.
 4469: 	'<th>'.&mt('Status').'</th>'.
 4470: 	&Apache::loncommon::end_data_table_header_row();
 4471:     my ($version);
 4472:     my %mark;
 4473:     my %orders;
 4474:     $mark{'correct_by_student'} = $checkIcon;
 4475:     if (!exists($$record{'1:timestamp'})) {
 4476: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 4477:     }
 4478: 
 4479:     my $interaction;
 4480:     my $no_increment = 1;
 4481:     for ($version=1;$version<=$$record{'version'};$version++) {
 4482: 	my $timestamp = 
 4483: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4484: 	if (exists($$record{$version.':resource.0.version'})) {
 4485: 	    $interaction = $$record{$version.':resource.0.version'};
 4486: 	}
 4487: 
 4488: 	my $where = ($isTask ? "$version:resource.$interaction"
 4489: 		             : "$version:resource");
 4490: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4491: 	    '<td>'.$timestamp.'</td>';
 4492: 	if ($isCODE) {
 4493: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4494: 	}
 4495: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4496: 	my @displaySub = ();
 4497: 	foreach my $partid (@{$parts}) {
 4498:             my $hidden;
 4499:             if (($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurvey') ||
 4500:                 ($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurveycred')) {
 4501:                 $hidden = 1;
 4502:             }
 4503: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4504: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4505: 	    
 4506: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4507: 	    my $display_part=&get_display_part($partid,$symb);
 4508: 	    foreach my $matchKey (@matchKey) {
 4509: 		if (exists($$record{$version.':'.$matchKey}) &&
 4510: 		    $$record{$version.':'.$matchKey} ne '') {
 4511:                     
 4512: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4513: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4514:                     $displaySub[0].='<span class="LC_nobreak"';
 4515:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 4516:                                    .' <span class="LC_internal_info">'
 4517:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
 4518:                                    .'</span>'
 4519:                                    .' <b>';
 4520:                     if ($hidden) {
 4521:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
 4522:                     } else {
 4523: 		        if ($$record{"$where.$partid.tries"} eq '') {
 4524: 			    $displaySub[0].=&mt('Trial not counted');
 4525: 		        } else {
 4526: 			    $displaySub[0].=&mt('Trial: [_1]',
 4527: 					    $$record{"$where.$partid.tries"});
 4528: 		        }
 4529: 		        my $responseType=($isTask ? 'Task'
 4530:                                               : $responseType->{$partid}->{$responseId});
 4531: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4532: 		        if (!exists($orders{$partid}->{$responseId})) {
 4533: 			    $orders{$partid}->{$responseId}=
 4534: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
 4535:                                            $no_increment);
 4536: 		        }
 4537: 		        $displaySub[0].='</b></span>'; # /nobreak
 4538: 		        $displaySub[0].='&nbsp; '.
 4539: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
 4540:                     }
 4541: 		}
 4542: 	    }
 4543: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4544: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 4545: 				    $$record{"$where.$partid.checkedin"},
 4546: 				    $$record{"$where.$partid.checkedin.slot"}).
 4547: 					'<br />';
 4548: 	    }
 4549: 	    if (exists $$record{"$where.$partid.award"}) {
 4550: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 4551: 		    lc($$record{"$where.$partid.award"}).' '.
 4552: 		    $mark{$$record{"$where.$partid.solved"}}.
 4553: 		    '<br />';
 4554: 	    }
 4555: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4556: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4557: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4558: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4559: 		$displaySub[2].=
 4560: 		    $$record{"$version:resource.$partid.regrader"}.
 4561: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4562: 	    }
 4563: 	}
 4564: 	# needed because old essay regrader has not parts info
 4565: 	if (exists $$record{"$version:resource.regrader"}) {
 4566: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 4567: 	}
 4568: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 4569: 	if ($displaySub[2]) {
 4570: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 4571: 	}
 4572: 	$studentTable.='&nbsp;</td>'.
 4573: 	    &Apache::loncommon::end_data_table_row();
 4574:     }
 4575:     $studentTable.=&Apache::loncommon::end_data_table();
 4576:     return $studentTable;
 4577: }
 4578: 
 4579: sub updateGradeByPage {
 4580:     my ($request,$symb) = @_;
 4581: 
 4582:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4583:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4584:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4585:     my $pageTitle = $env{'form.page'};
 4586:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4587:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4588:     my $usec=$classlist->{$env{'form.student'}}[5];
 4589:     if (!&canmodify($usec)) {
 4590: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 4591: 	return;
 4592:     }
 4593:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4594:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 4595: 	'</h3>'."\n";
 4596: 
 4597:     $request->print($result);
 4598: 
 4599: 
 4600:     my $navmap = Apache::lonnavmaps::navmap->new();
 4601:     unless (ref($navmap)) {
 4602:         $request->print(&navmap_errormsg());
 4603:         return;
 4604:     }
 4605:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 4606:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4607:     if (!$map) {
 4608: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 4609: 	return; 
 4610:     }
 4611:     my $iterator = $navmap->getIterator($map->map_start(),
 4612: 					$map->map_finish());
 4613: 
 4614:     my $studentTable=
 4615: 	&Apache::loncommon::start_data_table().
 4616: 	&Apache::loncommon::start_data_table_header_row().
 4617: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 4618: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 4619: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 4620: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 4621: 	&Apache::loncommon::end_data_table_header_row();
 4622: 
 4623:     $iterator->next(); # skip the first BEGIN_MAP
 4624:     my $curRes = $iterator->next(); # for "current resource"
 4625:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 4626:     while ($depth > 0) {
 4627:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4628:         if($curRes == $iterator->END_MAP) { $depth--; }
 4629: 
 4630:         if (ref($curRes) && $curRes->is_problem()) {
 4631: 	    my $parts = $curRes->parts();
 4632:             my $title = $curRes->compTitle();
 4633: 	    my $symbx = $curRes->symb();
 4634: 	    $studentTable.=
 4635: 		&Apache::loncommon::start_data_table_row().
 4636: 		'<td align="center" valign="top" >'.$prob.
 4637: 		(scalar(@{$parts}) == 1 ? '' 
 4638:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
 4639: 		.')').'</td>';
 4640: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 4641: 
 4642: 	    my %newrecord=();
 4643: 	    my @displayPts=();
 4644:             my %aggregate = ();
 4645:             my $aggregateflag = 0;
 4646: 	    foreach my $partid (@{$parts}) {
 4647: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 4648: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 4649: 
 4650: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 4651: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 4652: 		my $partial = $newpts/$wgt;
 4653: 		my $score;
 4654: 		if ($partial > 0) {
 4655: 		    $score = 'correct_by_override';
 4656: 		} elsif ($newpts ne '') { #empty is taken as 0
 4657: 		    $score = 'incorrect_by_override';
 4658: 		}
 4659: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 4660: 		if ($dropMenu eq 'excused') {
 4661: 		    $partial = '';
 4662: 		    $score = 'excused';
 4663: 		} elsif ($dropMenu eq 'reset status'
 4664: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 4665: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 4666: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 4667: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 4668: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 4669: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 4670: 		    $changeflag++;
 4671: 		    $newpts = '';
 4672:                     
 4673:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 4674:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 4675:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 4676:                     if ($aggtries > 0) {
 4677:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4678:                         $aggregateflag = 1;
 4679:                     }
 4680: 		}
 4681: 		my $display_part=&get_display_part($partid,$curRes->symb());
 4682: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 4683: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4684: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 4685: 		    '&nbsp;<br />';
 4686: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4687: 		     (($score eq 'excused') ? 'excused' : $newpts).
 4688: 		    '&nbsp;<br />';
 4689: 		$question++;
 4690: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 4691: 
 4692: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 4693: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 4694: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 4695: 		    if (scalar(keys(%newrecord)) > 0);
 4696: 
 4697: 		$changeflag++;
 4698: 	    }
 4699: 	    if (scalar(keys(%newrecord)) > 0) {
 4700: 		my %record = 
 4701: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 4702: 					     $udom,$uname);
 4703: 
 4704: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 4705: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 4706: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 4707: 		    $newrecord{'resource.CODE'} = '';
 4708: 		}
 4709: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 4710: 					$udom,$uname);
 4711: 		%record = &Apache::lonnet::restore($symbx,
 4712: 						   $env{'request.course.id'},
 4713: 						   $udom,$uname);
 4714: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 4715: 					     $cdom,$cnum,$udom,$uname);
 4716: 	    }
 4717: 	    
 4718:             if ($aggregateflag) {
 4719:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4720:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 4721:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 4722:             }
 4723: 
 4724: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 4725: 		'<td valign="top">'.$displayPts[1].'</td>'.
 4726: 		&Apache::loncommon::end_data_table_row();
 4727: 
 4728: 	    $prob++;
 4729: 	}
 4730:         $curRes = $iterator->next();
 4731:     }
 4732: 
 4733:     $studentTable.=&Apache::loncommon::end_data_table();
 4734:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 4735: 		  &mt('The scores were changed for [quant,_1,problem].',
 4736: 		  $changeflag));
 4737:     $request->print($grademsg.$studentTable);
 4738: 
 4739:     return '';
 4740: }
 4741: 
 4742: #-------- end of section for handling grading by page/sequence ---------
 4743: #
 4744: #-------------------------------------------------------------------
 4745: 
 4746: #-------------------- Bubblesheet (Scantron) Grading -------------------
 4747: #
 4748: #------ start of section for handling grading by page/sequence ---------
 4749: 
 4750: =pod
 4751: 
 4752: =head1 Bubble sheet grading routines
 4753: 
 4754:   For this documentation:
 4755: 
 4756:    'scanline' refers to the full line of characters
 4757:    from the file that we are parsing that represents one entire sheet
 4758: 
 4759:    'bubble line' refers to the data
 4760:    representing the line of bubbles that are on the physical bubble sheet
 4761: 
 4762: 
 4763: The overall process is that a scanned in bubble sheet data is uploaded
 4764: into a course. When a user wants to grade, they select a
 4765: sequence/folder of resources, a file of bubble sheet info, and pick
 4766: one of the predefined configurations for what each scanline looks
 4767: like.
 4768: 
 4769: Next each scanline is checked for any errors of either 'missing
 4770: bubbles' (it's an error because it may have been mis-scanned
 4771: because too light bubbling), 'double bubble' (each bubble line should
 4772: have no more that one letter picked), invalid or duplicated CODE,
 4773: invalid student/employee ID
 4774: 
 4775: If the CODE option is used that determines the randomization of the
 4776: homework problems, either way the student/employee ID is looked up into a
 4777: username:domain.
 4778: 
 4779: During the validation phase the instructor can choose to skip scanlines. 
 4780: 
 4781: After the validation phase, there are now 3 bubble sheet files
 4782: 
 4783:   scantron_original_filename (unmodified original file)
 4784:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 4785:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 4786: 
 4787: Also there is a separate hash nohist_scantrondata that contains extra
 4788: correction information that isn't representable in the bubble sheet
 4789: file (see &scantron_getfile() for more information)
 4790: 
 4791: After all scanlines are either valid, marked as valid or skipped, then
 4792: foreach line foreach problem in the picked sequence, an ssi request is
 4793: made that simulates a user submitting their selected letter(s) against
 4794: the homework problem.
 4795: 
 4796: =over 4
 4797: 
 4798: 
 4799: 
 4800: =item defaultFormData
 4801: 
 4802:   Returns html hidden inputs used to hold context/default values.
 4803: 
 4804:  Arguments:
 4805:   $symb - $symb of the current resource 
 4806: 
 4807: =cut
 4808: 
 4809: sub defaultFormData {
 4810:     my ($symb)=@_;
 4811:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
 4812: }
 4813: 
 4814: 
 4815: =pod 
 4816: 
 4817: =item getSequenceDropDown
 4818: 
 4819:    Return html dropdown of possible sequences to grade
 4820:  
 4821:  Arguments:
 4822:    $symb - $symb of the current resource
 4823:    $map_error - ref to scalar which will container error if
 4824:                 $navmap object is unavailable in &getSymbMap().
 4825: 
 4826: =cut
 4827: 
 4828: sub getSequenceDropDown {
 4829:     my ($symb,$map_error)=@_;
 4830:     my $result='<select name="selectpage">'."\n";
 4831:     my ($titles,$symbx) = &getSymbMap($map_error);
 4832:     if (ref($map_error)) {
 4833:         return if ($$map_error);
 4834:     }
 4835:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 4836:     my $ctr=0;
 4837:     foreach (@$titles) {
 4838: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4839: 	$result.='<option value="'.$$symbx{$_}.'" '.
 4840: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4841: 	    '>'.$showtitle.'</option>'."\n";
 4842: 	$ctr++;
 4843:     }
 4844:     $result.= '</select>';
 4845:     return $result;
 4846: }
 4847: 
 4848: my %bubble_lines_per_response;     # no. bubble lines for each response.
 4849:                                    # key is zero-based index - 0, 1, 2 ...
 4850: 
 4851: my %first_bubble_line;             # First bubble line no. for each bubble.
 4852: 
 4853: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 4854:                                    # matchresponse or rankresponse, where 
 4855:                                    # an individual response can have multiple 
 4856:                                    # lines
 4857: 
 4858: my %responsetype_per_response;     # responsetype for each response
 4859: 
 4860: # Save and restore the bubble lines array to the form env.
 4861: 
 4862: 
 4863: sub save_bubble_lines {
 4864:     foreach my $line (keys(%bubble_lines_per_response)) {
 4865: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 4866: 	$env{"form.scantron.first_bubble_line.$line"} =
 4867: 	    $first_bubble_line{$line};
 4868:         $env{"form.scantron.sub_bubblelines.$line"} = 
 4869:             $subdivided_bubble_lines{$line};
 4870:         $env{"form.scantron.responsetype.$line"} =
 4871:             $responsetype_per_response{$line};
 4872:     }
 4873: }
 4874: 
 4875: 
 4876: sub restore_bubble_lines {
 4877:     my $line = 0;
 4878:     %bubble_lines_per_response = ();
 4879:     while ($env{"form.scantron.bubblelines.$line"}) {
 4880: 	my $value = $env{"form.scantron.bubblelines.$line"};
 4881: 	$bubble_lines_per_response{$line} = $value;
 4882: 	$first_bubble_line{$line}  =
 4883: 	    $env{"form.scantron.first_bubble_line.$line"};
 4884:         $subdivided_bubble_lines{$line} =
 4885:             $env{"form.scantron.sub_bubblelines.$line"};
 4886:         $responsetype_per_response{$line} =
 4887:             $env{"form.scantron.responsetype.$line"};
 4888: 	$line++;
 4889:     }
 4890: }
 4891: 
 4892: #  Given the parsed scanline, get the response for 
 4893: #  'answer' number n:
 4894: 
 4895: sub get_response_bubbles {
 4896:     my ($parsed_line, $response)  = @_;
 4897: 
 4898:     my $bubble_line = $first_bubble_line{$response-1} +1;
 4899:     my $bubble_lines= $bubble_lines_per_response{$response-1};
 4900:     
 4901:     my $selected = "";
 4902: 
 4903:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
 4904: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
 4905: 	$bubble_line++;
 4906:     }
 4907:     return $selected;
 4908: }
 4909: 
 4910: =pod 
 4911: 
 4912: =item scantron_filenames
 4913: 
 4914:    Returns a list of the scantron files in the current course 
 4915: 
 4916: =cut
 4917: 
 4918: sub scantron_filenames {
 4919:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4920:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4921:     my $getpropath = 1;
 4922:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
 4923:                                        $getpropath);
 4924:     my @possiblenames;
 4925:     foreach my $filename (sort(@files)) {
 4926: 	($filename)=split(/&/,$filename);
 4927: 	if ($filename!~/^scantron_orig_/) { next ; }
 4928: 	$filename=~s/^scantron_orig_//;
 4929: 	push(@possiblenames,$filename);
 4930:     }
 4931:     return @possiblenames;
 4932: }
 4933: 
 4934: =pod 
 4935: 
 4936: =item scantron_uploads
 4937: 
 4938:    Returns  html drop-down list of scantron files in current course.
 4939: 
 4940:  Arguments:
 4941:    $file2grade - filename to set as selected in the dropdown
 4942: 
 4943: =cut
 4944: 
 4945: sub scantron_uploads {
 4946:     my ($file2grade) = @_;
 4947:     my $result=	'<select name="scantron_selectfile">';
 4948:     $result.="<option></option>";
 4949:     foreach my $filename (sort(&scantron_filenames())) {
 4950: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 4951:     }
 4952:     $result.="</select>";
 4953:     return $result;
 4954: }
 4955: 
 4956: =pod 
 4957: 
 4958: =item scantron_scantab
 4959: 
 4960:   Returns html drop down of the scantron formats in the scantronformat.tab
 4961:   file.
 4962: 
 4963: =cut
 4964: 
 4965: sub scantron_scantab {
 4966:     my $result='<select name="scantron_format">'."\n";
 4967:     $result.='<option></option>'."\n";
 4968:     my @lines = &get_scantronformat_file();
 4969:     if (@lines > 0) {
 4970:         foreach my $line (@lines) {
 4971:             next if (($line =~ /^\#/) || ($line eq ''));
 4972: 	    my ($name,$descrip)=split(/:/,$line);
 4973: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 4974:         }
 4975:     }
 4976:     $result.='</select>'."\n";
 4977:     return $result;
 4978: }
 4979: 
 4980: =pod
 4981: 
 4982: =item get_scantronformat_file
 4983: 
 4984:   Returns an array containing lines from the scantron format file for
 4985:   the domain of the course.
 4986: 
 4987:   If a url for a custom.tab file is listed in domain's configuration.db, 
 4988:   lines are from this file.
 4989: 
 4990:   Otherwise, if a default.tab has been published in RES space by the 
 4991:   domainconfig user, lines are from this file.
 4992: 
 4993:   Otherwise, fall back to getting lines from the legacy file on the
 4994:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 4995: 
 4996: =cut
 4997: 
 4998: sub get_scantronformat_file {
 4999:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5000:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 5001:     my $gottab = 0;
 5002:     my @lines;
 5003:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5004:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5005:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5006:             if ($formatfile ne '-1') {
 5007:                 @lines = split("\n",$formatfile,-1);
 5008:                 $gottab = 1;
 5009:             }
 5010:         }
 5011:     }
 5012:     if (!$gottab) {
 5013:         my $confname = $cdom.'-domainconfig';
 5014:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5015:         my $formatfile =  &Apache::lonnet::getfile($default);
 5016:         if ($formatfile ne '-1') {
 5017:             @lines = split("\n",$formatfile,-1);
 5018:             $gottab = 1;
 5019:         }
 5020:     }
 5021:     if (!$gottab) {
 5022:         my @domains = &Apache::lonnet::current_machine_domains();
 5023:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5024:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5025:             @lines = <$fh>;
 5026:             close($fh);
 5027:         } else {
 5028:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 5029:             @lines = <$fh>;
 5030:             close($fh);
 5031:         }
 5032:     }
 5033:     return @lines;
 5034: }
 5035: 
 5036: =pod 
 5037: 
 5038: =item scantron_CODElist
 5039: 
 5040:   Returns html drop down of the saved CODE lists from current course,
 5041:   generated from earlier printings.
 5042: 
 5043: =cut
 5044: 
 5045: sub scantron_CODElist {
 5046:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5047:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5048:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5049:     my $namechoice='<option></option>';
 5050:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5051: 	if ($name =~ /^error: 2 /) { next; }
 5052: 	if ($name =~ /^type\0/) { next; }
 5053: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5054:     }
 5055:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5056:     return $namechoice;
 5057: }
 5058: 
 5059: =pod 
 5060: 
 5061: =item scantron_CODEunique
 5062: 
 5063:   Returns the html for "Each CODE to be used once" radio.
 5064: 
 5065: =cut
 5066: 
 5067: sub scantron_CODEunique {
 5068:     my $result='<span class="LC_nobreak">
 5069:                  <label><input type="radio" name="scantron_CODEunique"
 5070:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5071:                 </span>
 5072:                 <span class="LC_nobreak">
 5073:                  <label><input type="radio" name="scantron_CODEunique"
 5074:                         value="no" />'.&mt('No').' </label>
 5075:                 </span>';
 5076:     return $result;
 5077: }
 5078: 
 5079: =pod 
 5080: 
 5081: =item scantron_selectphase
 5082: 
 5083:   Generates the initial screen to start the bubble sheet process.
 5084:   Allows for - starting a grading run.
 5085:              - downloading existing scan data (original, corrected
 5086:                                                 or skipped info)
 5087: 
 5088:              - uploading new scan data
 5089: 
 5090:  Arguments:
 5091:   $r          - The Apache request object
 5092:   $file2grade - name of the file that contain the scanned data to score
 5093: 
 5094: =cut
 5095: 
 5096: sub scantron_selectphase {
 5097:     my ($r,$file2grade,$symb) = @_;
 5098:     if (!$symb) {return '';}
 5099:     my $map_error;
 5100:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 5101:     if ($map_error) {
 5102:         $r->print('<br />'.&navmap_errormsg().'<br />');
 5103:         return;
 5104:     }
 5105:     my $default_form_data=&defaultFormData($symb);
 5106:     my $file_selector=&scantron_uploads($file2grade);
 5107:     my $format_selector=&scantron_scantab();
 5108:     my $CODE_selector=&scantron_CODElist();
 5109:     my $CODE_unique=&scantron_CODEunique();
 5110:     my $result;
 5111: 
 5112:     $ssi_error = 0;
 5113: 
 5114:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5115:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5116: 
 5117: 	# Chunk of form to prompt for a scantron file upload.
 5118: 
 5119:         $r->print('
 5120:     <br />
 5121:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5122:        '.&Apache::loncommon::start_data_table_header_row().'
 5123:             <th>
 5124:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 5125:             </th>
 5126:        '.&Apache::loncommon::end_data_table_header_row().'
 5127:        '.&Apache::loncommon::start_data_table_row().'
 5128:             <td>
 5129: ');
 5130:     my $default_form_data=&defaultFormData($symb);
 5131:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5132:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5133:     $r->print(&Apache::lonhtmlcommon::scripttag('
 5134:     function checkUpload(formname) {
 5135: 	if (formname.upfile.value == "") {
 5136: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 5137: 	    return false;
 5138: 	}
 5139: 	formname.submit();
 5140:     }'));
 5141:     $r->print('
 5142:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5143:                 '.$default_form_data.'
 5144:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5145:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5146:                 <input name="command" value="scantronupload_save" type="hidden" />
 5147:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5148:                 <br />
 5149:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 5150:               </form>
 5151: ');
 5152: 
 5153:         $r->print('
 5154:             </td>
 5155:        '.&Apache::loncommon::end_data_table_row().'
 5156:        '.&Apache::loncommon::end_data_table().'
 5157: ');
 5158:     }
 5159: 
 5160:     # Chunk of form to prompt for a file to grade and how:
 5161: 
 5162:     $result.= '
 5163:     <br />
 5164:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5165:     <input type="hidden" name="command" value="scantron_warning" />
 5166:     '.$default_form_data.'
 5167:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5168:        '.&Apache::loncommon::start_data_table_header_row().'
 5169:             <th colspan="2">
 5170:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5171:             </th>
 5172:        '.&Apache::loncommon::end_data_table_header_row().'
 5173:        '.&Apache::loncommon::start_data_table_row().'
 5174:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5175:        '.&Apache::loncommon::end_data_table_row().'
 5176:        '.&Apache::loncommon::start_data_table_row().'
 5177:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 5178:        '.&Apache::loncommon::end_data_table_row().'
 5179:        '.&Apache::loncommon::start_data_table_row().'
 5180:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 5181:        '.&Apache::loncommon::end_data_table_row().'
 5182:        '.&Apache::loncommon::start_data_table_row().'
 5183:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5184:        '.&Apache::loncommon::end_data_table_row().'
 5185:        '.&Apache::loncommon::start_data_table_row().'
 5186:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5187:        '.&Apache::loncommon::end_data_table_row().'
 5188:        '.&Apache::loncommon::start_data_table_row().'
 5189: 	    <td> '.&mt('Options:').' </td>
 5190:             <td>
 5191: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5192:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5193:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5194: 	    </td>
 5195:        '.&Apache::loncommon::end_data_table_row().'
 5196:        '.&Apache::loncommon::start_data_table_row().'
 5197:             <td colspan="2">
 5198:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 5199:             </td>
 5200:        '.&Apache::loncommon::end_data_table_row().'
 5201:     '.&Apache::loncommon::end_data_table().'
 5202:     </form>
 5203: ';
 5204:    
 5205:     $r->print($result);
 5206: 
 5207: 
 5208: 
 5209:     # Chunk of the form that prompts to view a scoring office file,
 5210:     # corrected file, skipped records in a file.
 5211: 
 5212:     $r->print('
 5213:    <br />
 5214:    <form action="/adm/grades" name="scantron_download">
 5215:      '.$default_form_data.'
 5216:      <input type="hidden" name="command" value="scantron_download" />
 5217:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5218:        '.&Apache::loncommon::start_data_table_header_row().'
 5219:               <th>
 5220:                 &nbsp;'.&mt('Download a scoring office file').'
 5221:               </th>
 5222:        '.&Apache::loncommon::end_data_table_header_row().'
 5223:        '.&Apache::loncommon::start_data_table_row().'
 5224:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5225:                 <br />
 5226:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5227:        '.&Apache::loncommon::end_data_table_row().'
 5228:      '.&Apache::loncommon::end_data_table().'
 5229:    </form>
 5230:    <br />
 5231: ');
 5232: 
 5233:     &Apache::lonpickcode::code_list($r,2);
 5234: 
 5235:     $r->print('<br /><form method="post" name="checkscantron">'.
 5236:              $default_form_data."\n".
 5237:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5238:              &Apache::loncommon::start_data_table_header_row()."\n".
 5239:              '<th colspan="2">
 5240:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 5241:              '</th>'."\n".
 5242:               &Apache::loncommon::end_data_table_header_row()."\n".
 5243:               &Apache::loncommon::start_data_table_row()."\n".
 5244:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5245:               '<td> '.$sequence_selector.' </td>'.
 5246:               &Apache::loncommon::end_data_table_row()."\n".
 5247:               &Apache::loncommon::start_data_table_row()."\n".
 5248:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5249:               '<td> '.$file_selector.' </td>'."\n".
 5250:               &Apache::loncommon::end_data_table_row()."\n".
 5251:               &Apache::loncommon::start_data_table_row()."\n".
 5252:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5253:               '<td> '.$format_selector.' </td>'."\n".
 5254:               &Apache::loncommon::end_data_table_row()."\n".
 5255:               &Apache::loncommon::start_data_table_row()."\n".
 5256:               '<td> '.&mt('Options').' </td>'."\n".
 5257:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 5258:               &Apache::loncommon::end_data_table_row()."\n".
 5259:               &Apache::loncommon::start_data_table_row()."\n".
 5260:               '<td colspan="2">'."\n".
 5261:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5262:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 5263:               '</td>'."\n".
 5264:               &Apache::loncommon::end_data_table_row()."\n".
 5265:               &Apache::loncommon::end_data_table()."\n".
 5266:               '</form><br />');
 5267:     return;
 5268: }
 5269: 
 5270: =pod
 5271: 
 5272: =item get_scantron_config
 5273: 
 5274:    Parse and return the scantron configuration line selected as a
 5275:    hash of configuration file fields.
 5276: 
 5277:  Arguments:
 5278:     which - the name of the configuration to parse from the file.
 5279: 
 5280: 
 5281:  Returns:
 5282:             If the named configuration is not in the file, an empty
 5283:             hash is returned.
 5284:     a hash with the fields
 5285:       name         - internal name for the this configuration setup
 5286:       description  - text to display to operator that describes this config
 5287:       CODElocation - if 0 or the string 'none'
 5288:                           - no CODE exists for this config
 5289:                      if -1 || the string 'letter'
 5290:                           - a CODE exists for this config and is
 5291:                             a string of letters
 5292:                      Unsupported value (but planned for future support)
 5293:                           if a positive integer
 5294:                                - The CODE exists as the first n items from
 5295:                                  the question section of the form
 5296:                           if the string 'number'
 5297:                                - The CODE exists for this config and is
 5298:                                  a string of numbers
 5299:       CODEstart   - (only matter if a CODE exists) column in the line where
 5300:                      the CODE starts
 5301:       CODElength  - length of the CODE
 5302:       IDstart     - column where the student/employee ID starts
 5303:       IDlength    - length of the student/employee ID info
 5304:       Qstart      - column where the information from the bubbled
 5305:                     'questions' start
 5306:       Qlength     - number of columns comprising a single bubble line from
 5307:                     the sheet. (usually either 1 or 10)
 5308:       Qon         - either a single character representing the character used
 5309:                     to signal a bubble was chosen in the positional setup, or
 5310:                     the string 'letter' if the letter of the chosen bubble is
 5311:                     in the final, or 'number' if a number representing the
 5312:                     chosen bubble is in the file (1->A 0->J)
 5313:       Qoff        - the character used to represent that a bubble was
 5314:                     left blank
 5315:       PaperID     - if the scanning process generates a unique number for each
 5316:                     sheet scanned the column that this ID number starts in
 5317:       PaperIDlength - number of columns that comprise the unique ID number
 5318:                       for the sheet of paper
 5319:       FirstName   - column that the first name starts in
 5320:       FirstNameLength - number of columns that the first name spans
 5321:  
 5322:       LastName    - column that the last name starts in
 5323:       LastNameLength - number of columns that the last name spans
 5324: 
 5325: =cut
 5326: 
 5327: sub get_scantron_config {
 5328:     my ($which) = @_;
 5329:     my @lines = &get_scantronformat_file();
 5330:     my %config;
 5331:     #FIXME probably should move to XML it has already gotten a bit much now
 5332:     foreach my $line (@lines) {
 5333: 	my ($name,$descrip)=split(/:/,$line);
 5334: 	if ($name ne $which ) { next; }
 5335: 	chomp($line);
 5336: 	my @config=split(/:/,$line);
 5337: 	$config{'name'}=$config[0];
 5338: 	$config{'description'}=$config[1];
 5339: 	$config{'CODElocation'}=$config[2];
 5340: 	$config{'CODEstart'}=$config[3];
 5341: 	$config{'CODElength'}=$config[4];
 5342: 	$config{'IDstart'}=$config[5];
 5343: 	$config{'IDlength'}=$config[6];
 5344: 	$config{'Qstart'}=$config[7];
 5345:  	$config{'Qlength'}=$config[8];
 5346: 	$config{'Qoff'}=$config[9];
 5347: 	$config{'Qon'}=$config[10];
 5348: 	$config{'PaperID'}=$config[11];
 5349: 	$config{'PaperIDlength'}=$config[12];
 5350: 	$config{'FirstName'}=$config[13];
 5351: 	$config{'FirstNamelength'}=$config[14];
 5352: 	$config{'LastName'}=$config[15];
 5353: 	$config{'LastNamelength'}=$config[16];
 5354: 	last;
 5355:     }
 5356:     return %config;
 5357: }
 5358: 
 5359: =pod 
 5360: 
 5361: =item username_to_idmap
 5362: 
 5363:     creates a hash keyed by student/employee ID with values of the corresponding
 5364:     student username:domain.
 5365: 
 5366:   Arguments:
 5367: 
 5368:     $classlist - reference to the class list hash. This is a hash
 5369:                  keyed by student name:domain  whose elements are references
 5370:                  to arrays containing various chunks of information
 5371:                  about the student. (See loncoursedata for more info).
 5372: 
 5373:   Returns
 5374:     %idmap - the constructed hash
 5375: 
 5376: =cut
 5377: 
 5378: sub username_to_idmap {
 5379:     my ($classlist)= @_;
 5380:     my %idmap;
 5381:     foreach my $student (keys(%$classlist)) {
 5382: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5383: 	    $student;
 5384:     }
 5385:     return %idmap;
 5386: }
 5387: 
 5388: =pod
 5389: 
 5390: =item scantron_fixup_scanline
 5391: 
 5392:    Process a requested correction to a scanline.
 5393: 
 5394:   Arguments:
 5395:     $scantron_config   - hash from &get_scantron_config()
 5396:     $scan_data         - hash of correction information 
 5397:                           (see &scantron_getfile())
 5398:     $line              - existing scanline
 5399:     $whichline         - line number of the passed in scanline
 5400:     $field             - type of change to process 
 5401:                          (either 
 5402:                           'ID'     -> correct the student/employee ID
 5403:                           'CODE'   -> correct the CODE
 5404:                           'answer' -> fixup the submitted answers)
 5405:     
 5406:    $args               - hash of additional info,
 5407:                           - 'ID' 
 5408:                                'newid' -> studentID to use in replacement
 5409:                                           of existing one
 5410:                           - 'CODE' 
 5411:                                'CODE_ignore_dup' - set to true if duplicates
 5412:                                                    should be ignored.
 5413: 	                       'CODE' - is new code or 'use_unfound'
 5414:                                         if the existing unfound code should
 5415:                                         be used as is
 5416:                           - 'answer'
 5417:                                'response' - new answer or 'none' if blank
 5418:                                'question' - the bubble line to change
 5419:                                'questionnum' - the question identifier,
 5420:                                                may include subquestion. 
 5421: 
 5422:   Returns:
 5423:     $line - the modified scanline
 5424: 
 5425:   Side effects: 
 5426:     $scan_data - may be updated
 5427: 
 5428: =cut
 5429: 
 5430: 
 5431: sub scantron_fixup_scanline {
 5432:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5433:     if ($field eq 'ID') {
 5434: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5435: 	    return ($line,1,'New value too large');
 5436: 	}
 5437: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5438: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5439: 				     $args->{'newid'});
 5440: 	}
 5441: 	substr($line,$$scantron_config{'IDstart'}-1,
 5442: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5443: 	if ($args->{'newid'}=~/^\s*$/) {
 5444: 	    &scan_data($scan_data,"$whichline.user",
 5445: 		       $args->{'username'}.':'.$args->{'domain'});
 5446: 	}
 5447:     } elsif ($field eq 'CODE') {
 5448: 	if ($args->{'CODE_ignore_dup'}) {
 5449: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5450: 	}
 5451: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5452: 	if ($args->{'CODE'} ne 'use_unfound') {
 5453: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5454: 		return ($line,1,'New CODE value too large');
 5455: 	    }
 5456: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5457: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5458: 	    }
 5459: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5460: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5461: 	}
 5462:     } elsif ($field eq 'answer') {
 5463: 	my $length=$scantron_config->{'Qlength'};
 5464: 	my $off=$scantron_config->{'Qoff'};
 5465: 	my $on=$scantron_config->{'Qon'};
 5466: 	my $answer=${off}x$length;
 5467: 	if ($args->{'response'} eq 'none') {
 5468: 	    &scan_data($scan_data,
 5469: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5470: 	} else {
 5471: 	    if ($on eq 'letter') {
 5472: 		my @alphabet=('A'..'Z');
 5473: 		$answer=$alphabet[$args->{'response'}];
 5474: 	    } elsif ($on eq 'number') {
 5475: 		$answer=$args->{'response'}+1;
 5476: 		if ($answer == 10) { $answer = '0'; }
 5477: 	    } else {
 5478: 		substr($answer,$args->{'response'},1)=$on;
 5479: 	    }
 5480: 	    &scan_data($scan_data,
 5481: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5482: 	}
 5483: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5484: 	substr($line,$where-1,$length)=$answer;
 5485:     }
 5486:     return $line;
 5487: }
 5488: 
 5489: =pod
 5490: 
 5491: =item scan_data
 5492: 
 5493:     Edit or look up  an item in the scan_data hash.
 5494: 
 5495:   Arguments:
 5496:     $scan_data  - The hash (see scantron_getfile)
 5497:     $key        - shorthand of the key to edit (actual key is
 5498:                   scantronfilename_key).
 5499:     $data        - New value of the hash entry.
 5500:     $delete      - If true, the entry is removed from the hash.
 5501: 
 5502:   Returns:
 5503:     The new value of the hash table field (undefined if deleted).
 5504: 
 5505: =cut
 5506: 
 5507: 
 5508: sub scan_data {
 5509:     my ($scan_data,$key,$value,$delete)=@_;
 5510:     my $filename=$env{'form.scantron_selectfile'};
 5511:     if (defined($value)) {
 5512: 	$scan_data->{$filename.'_'.$key} = $value;
 5513:     }
 5514:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5515:     return $scan_data->{$filename.'_'.$key};
 5516: }
 5517: 
 5518: # ----- These first few routines are general use routines.----
 5519: 
 5520: # Return the number of occurences of a pattern in a string.
 5521: 
 5522: sub occurence_count {
 5523:     my ($string, $pattern) = @_;
 5524: 
 5525:     my @matches = ($string =~ /$pattern/g);
 5526: 
 5527:     return scalar(@matches);
 5528: }
 5529: 
 5530: 
 5531: # Take a string known to have digits and convert all the
 5532: # digits into letters in the range J,A..I.
 5533: 
 5534: sub digits_to_letters {
 5535:     my ($input) = @_;
 5536: 
 5537:     my @alphabet = ('J', 'A'..'I');
 5538: 
 5539:     my @input    = split(//, $input);
 5540:     my $output ='';
 5541:     for (my $i = 0; $i < scalar(@input); $i++) {
 5542: 	if ($input[$i] =~ /\d/) {
 5543: 	    $output .= $alphabet[$input[$i]];
 5544: 	} else {
 5545: 	    $output .= $input[$i];
 5546: 	}
 5547:     }
 5548:     return $output;
 5549: }
 5550: 
 5551: =pod 
 5552: 
 5553: =item scantron_parse_scanline
 5554: 
 5555:   Decodes a scanline from the selected scantron file
 5556: 
 5557:  Arguments:
 5558:     line             - The text of the scantron file line to process
 5559:     whichline        - Line number
 5560:     scantron_config  - Hash describing the format of the scantron lines.
 5561:     scan_data        - Hash of extra information about the scanline
 5562:                        (see scantron_getfile for more information)
 5563:     just_header      - True if should not process question answers but only
 5564:                        the stuff to the left of the answers.
 5565:  Returns:
 5566:    Hash containing the result of parsing the scanline
 5567: 
 5568:    Keys are all proceeded by the string 'scantron.'
 5569: 
 5570:        CODE    - the CODE in use for this scanline
 5571:        useCODE - 1 if the CODE is invalid but it usage has been forced
 5572:                  by the operator
 5573:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 5574:                             CODEs were selected, but the usage has been
 5575:                             forced by the operator
 5576:        ID  - student/employee ID
 5577:        PaperID - if used, the ID number printed on the sheet when the 
 5578:                  paper was scanned
 5579:        FirstName - first name from the sheet
 5580:        LastName  - last name from the sheet
 5581: 
 5582:      if just_header was not true these key may also exist
 5583: 
 5584:        missingerror - a list of bubble ranges that are considered to be answers
 5585:                       to a single question that don't have any bubbles filled in.
 5586:                       Of the form questionnumber:firstbubblenumber:count.
 5587:        doubleerror  - a list of bubble ranges that are considered to be answers
 5588:                       to a single question that have more than one bubble filled in.
 5589:                       Of the form questionnumber::firstbubblenumber:count
 5590:    
 5591:                 In the above, count is the number of bubble responses in the
 5592:                 input line needed to represent the possible answers to the question.
 5593:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 5594:                 per line would have count = 2.
 5595: 
 5596:        maxquest     - the number of the last bubble line that was parsed
 5597: 
 5598:        (<number> starts at 1)
 5599:        <number>.answer - zero or more letters representing the selected
 5600:                          letters from the scanline for the bubble line 
 5601:                          <number>.
 5602:                          if blank there was either no bubble or there where
 5603:                          multiple bubbles, (consult the keys missingerror and
 5604:                          doubleerror if this is an error condition)
 5605: 
 5606: =cut
 5607: 
 5608: sub scantron_parse_scanline {
 5609:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
 5610: 
 5611:     my %record;
 5612:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 5613:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 5614:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
 5615:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 5616: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 5617: 	if ($$scantron_config{'CODElocation'} < 0 ||
 5618: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 5619: 	    $$scantron_config{'CODElocation'} eq 'number') {
 5620: 	    $record{'scantron.CODE'}=substr($data,
 5621: 					    $$scantron_config{'CODEstart'}-1,
 5622: 					    $$scantron_config{'CODElength'});
 5623: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 5624: 		$record{'scantron.useCODE'}=1;
 5625: 	    }
 5626: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 5627: 		$record{'scantron.CODE_ignore_dup'}=1;
 5628: 	    }
 5629: 	} else {
 5630: 	    #FIXME interpret first N questions
 5631: 	}
 5632:     }
 5633:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 5634: 				  $$scantron_config{'IDlength'});
 5635:     $record{'scantron.PaperID'}=
 5636: 	substr($data,$$scantron_config{'PaperID'}-1,
 5637: 	       $$scantron_config{'PaperIDlength'});
 5638:     $record{'scantron.FirstName'}=
 5639: 	substr($data,$$scantron_config{'FirstName'}-1,
 5640: 	       $$scantron_config{'FirstNamelength'});
 5641:     $record{'scantron.LastName'}=
 5642: 	substr($data,$$scantron_config{'LastName'}-1,
 5643: 	       $$scantron_config{'LastNamelength'});
 5644:     if ($just_header) { return \%record; }
 5645: 
 5646:     my @alphabet=('A'..'Z');
 5647:     my $questnum=0;
 5648:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 5649: 
 5650:     chomp($questions);		# Get rid of any trailing \n.
 5651:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 5652:     while (length($questions)) {
 5653: 	my $answers_needed = $bubble_lines_per_response{$questnum};
 5654:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 5655:                              || 1;
 5656:         $questnum++;
 5657:         my $quest_id = $questnum;
 5658:         my $currentquest = substr($questions,0,$answer_length);
 5659:         $questions       = substr($questions,$answer_length);
 5660:         if (length($currentquest) < $answer_length) { next; }
 5661: 
 5662:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
 5663:             my $subquestnum = 1;
 5664:             my $subquestions = $currentquest;
 5665:             my @subanswers_needed = 
 5666:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
 5667:             foreach my $subans (@subanswers_needed) {
 5668:                 my $subans_length =
 5669:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 5670:                 my $currsubquest = substr($subquestions,0,$subans_length);
 5671:                 $subquestions   = substr($subquestions,$subans_length);
 5672:                 $quest_id = "$questnum.$subquestnum";
 5673:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 5674:                     ($$scantron_config{'Qon'} eq 'number')) {
 5675:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 5676:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 5677:                         \@alphabet,\%record,$scantron_config,$scan_data);
 5678:                 } else {
 5679:                     $ansnum = &scantron_validator_positional($ansnum,
 5680:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
 5681:                 }
 5682:                 $subquestnum ++;
 5683:             }
 5684:         } else {
 5685:             if (($$scantron_config{'Qon'} eq 'letter') ||
 5686:                 ($$scantron_config{'Qon'} eq 'number')) {
 5687:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 5688:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5689:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5690:             } else {
 5691:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 5692:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5693:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5694:             }
 5695:         }
 5696:     }
 5697:     $record{'scantron.maxquest'}=$questnum;
 5698:     return \%record;
 5699: }
 5700: 
 5701: sub scantron_validator_lettnum {
 5702:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 5703:         $alphabet,$record,$scantron_config,$scan_data) = @_;
 5704: 
 5705:     # Qon 'letter' implies for each slot in currquest we have:
 5706:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 5707:     #    about anything else (esp. a value of Qoff) for missing
 5708:     #    bubbles.
 5709:     #
 5710:     # Qon 'number' implies each slot gives a digit that indexes the
 5711:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 5712:     #    and * or ? for double bubbles on a single line.
 5713:     #
 5714: 
 5715:     my $matchon;
 5716:     if ($$scantron_config{'Qon'} eq 'letter') {
 5717:         $matchon = '[A-Z]';
 5718:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 5719:         $matchon = '\d';
 5720:     }
 5721:     my $occurrences = 0;
 5722:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5723:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5724:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5725:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5726:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5727:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5728:         my @singlelines = split('',$currquest);
 5729:         foreach my $entry (@singlelines) {
 5730:             $occurrences = &occurence_count($entry,$matchon);
 5731:             if ($occurrences > 1) {
 5732:                 last;
 5733:             }
 5734:         } 
 5735:     } else {
 5736:         $occurrences = &occurence_count($currquest,$matchon); 
 5737:     }
 5738:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 5739:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5740:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5741:             my $bubble = substr($currquest,$ans,1);
 5742:             if ($bubble =~ /$matchon/ ) {
 5743:                 if ($$scantron_config{'Qon'} eq 'number') {
 5744:                     if ($bubble == 0) {
 5745:                         $bubble = 10; 
 5746:                     }
 5747:                     $record->{"scantron.$ansnum.answer"} = 
 5748:                         $alphabet->[$bubble-1];
 5749:                 } else {
 5750:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 5751:                 }
 5752:             } else {
 5753:                 $record->{"scantron.$ansnum.answer"}='';
 5754:             }
 5755:             $ansnum++;
 5756:         }
 5757:     } elsif (!defined($currquest)
 5758:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 5759:             || (&occurence_count($currquest,$matchon) == 0)) {
 5760:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5761:             $record->{"scantron.$ansnum.answer"}='';
 5762:             $ansnum++;
 5763:         }
 5764:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5765:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 5766:         }
 5767:     } else {
 5768:         if ($$scantron_config{'Qon'} eq 'number') {
 5769:             $currquest = &digits_to_letters($currquest);            
 5770:         }
 5771:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5772:             my $bubble = substr($currquest,$ans,1);
 5773:             $record->{"scantron.$ansnum.answer"} = $bubble;
 5774:             $ansnum++;
 5775:         }
 5776:     }
 5777:     return $ansnum;
 5778: }
 5779: 
 5780: sub scantron_validator_positional {
 5781:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 5782:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
 5783: 
 5784:     # Otherwise there's a positional notation;
 5785:     # each bubble line requires Qlength items, and there are filled in
 5786:     # bubbles for each case where there 'Qon' characters.
 5787:     #
 5788: 
 5789:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 5790: 
 5791:     # If the split only gives us one element.. the full length of the
 5792:     # answer string, no bubbles are filled in:
 5793: 
 5794:     if ($answers_needed eq '') {
 5795:         return;
 5796:     }
 5797: 
 5798:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 5799:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5800:             $record->{"scantron.$ansnum.answer"}='';
 5801:             $ansnum++;
 5802:         }
 5803:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5804:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 5805:         }
 5806:     } elsif (scalar(@array) == 2) {
 5807:         my $location = length($array[0]);
 5808:         my $line_num = int($location / $$scantron_config{'Qlength'});
 5809:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 5810:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5811:             if ($ans eq $line_num) {
 5812:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 5813:             } else {
 5814:                 $record->{"scantron.$ansnum.answer"} = ' ';
 5815:             }
 5816:             $ansnum++;
 5817:          }
 5818:     } else {
 5819:         #  If there's more than one instance of a bubble character
 5820:         #  That's a double bubble; with positional notation we can
 5821:         #  record all the bubbles filled in as well as the
 5822:         #  fact this response consists of multiple bubbles.
 5823:         #
 5824:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5825:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5826:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5827:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5828:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5829:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5830:             my $doubleerror = 0;
 5831:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 5832:                    (!$doubleerror)) {
 5833:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 5834:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 5835:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 5836:                if (length(@currarray) > 2) {
 5837:                    $doubleerror = 1;
 5838:                } 
 5839:             }
 5840:             if ($doubleerror) {
 5841:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5842:             }
 5843:         } else {
 5844:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5845:         }
 5846:         my $item = $ansnum;
 5847:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5848:             $record->{"scantron.$item.answer"} = '';
 5849:             $item ++;
 5850:         }
 5851: 
 5852:         my @ans=@array;
 5853:         my $i=0;
 5854:         my $increment = 0;
 5855:         while ($#ans) {
 5856:             $i+=length($ans[0]) + $increment;
 5857:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 5858:             my $bubble = $i%$$scantron_config{'Qlength'};
 5859:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 5860:             shift(@ans);
 5861:             $increment = 1;
 5862:         }
 5863:         $ansnum += $answers_needed;
 5864:     }
 5865:     return $ansnum;
 5866: }
 5867: 
 5868: =pod
 5869: 
 5870: =item scantron_add_delay
 5871: 
 5872:    Adds an error message that occurred during the grading phase to a
 5873:    queue of messages to be shown after grading pass is complete
 5874: 
 5875:  Arguments:
 5876:    $delayqueue  - arrary ref of hash ref of error messages
 5877:    $scanline    - the scanline that caused the error
 5878:    $errormesage - the error message
 5879:    $errorcode   - a numeric code for the error
 5880: 
 5881:  Side Effects:
 5882:    updates the $delayqueue to have a new hash ref of the error
 5883: 
 5884: =cut
 5885: 
 5886: sub scantron_add_delay {
 5887:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 5888:     push(@$delayqueue,
 5889: 	 {'line' => $scanline, 'emsg' => $errormessage,
 5890: 	  'ecode' => $errorcode }
 5891: 	 );
 5892: }
 5893: 
 5894: =pod
 5895: 
 5896: =item scantron_find_student
 5897: 
 5898:    Finds the username for the current scanline
 5899: 
 5900:   Arguments:
 5901:    $scantron_record - hash result from scantron_parse_scanline
 5902:    $scan_data       - hash of correction information 
 5903:                       (see &scantron_getfile() form more information)
 5904:    $idmap           - hash from &username_to_idmap()
 5905:    $line            - number of current scanline
 5906:  
 5907:   Returns:
 5908:    Either 'username:domain' or undef if unknown
 5909: 
 5910: =cut
 5911: 
 5912: sub scantron_find_student {
 5913:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 5914:     my $scanID=$$scantron_record{'scantron.ID'};
 5915:     if ($scanID =~ /^\s*$/) {
 5916:  	return &scan_data($scan_data,"$line.user");
 5917:     }
 5918:     foreach my $id (keys(%$idmap)) {
 5919:  	if (lc($id) eq lc($scanID)) {
 5920:  	    return $$idmap{$id};
 5921:  	}
 5922:     }
 5923:     return undef;
 5924: }
 5925: 
 5926: =pod
 5927: 
 5928: =item scantron_filter
 5929: 
 5930:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 5931:    hidden resources was selected
 5932: 
 5933: =cut
 5934: 
 5935: sub scantron_filter {
 5936:     my ($curres)=@_;
 5937: 
 5938:     if (ref($curres) && $curres->is_problem()) {
 5939: 	# if the user has asked to not have either hidden
 5940: 	# or 'randomout' controlled resources to be graded
 5941: 	# don't include them
 5942: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 5943: 	    && $curres->randomout) {
 5944: 	    return 0;
 5945: 	}
 5946: 	return 1;
 5947:     }
 5948:     return 0;
 5949: }
 5950: 
 5951: =pod
 5952: 
 5953: =item scantron_process_corrections
 5954: 
 5955:    Gets correction information out of submitted form data and corrects
 5956:    the scanline
 5957: 
 5958: =cut
 5959: 
 5960: sub scantron_process_corrections {
 5961:     my ($r) = @_;
 5962:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 5963:     my ($scanlines,$scan_data)=&scantron_getfile();
 5964:     my $classlist=&Apache::loncoursedata::get_classlist();
 5965:     my $which=$env{'form.scantron_line'};
 5966:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 5967:     my ($skip,$err,$errmsg);
 5968:     if ($env{'form.scantron_skip_record'}) {
 5969: 	$skip=1;
 5970:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 5971: 	my $newstudent=$env{'form.scantron_username'}.':'.
 5972: 	    $env{'form.scantron_domain'};
 5973: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 5974: 	($line,$err,$errmsg)=
 5975: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 5976: 				     'ID',{'newid'=>$newid,
 5977: 				    'username'=>$env{'form.scantron_username'},
 5978: 				    'domain'=>$env{'form.scantron_domain'}});
 5979:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 5980: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 5981: 	my $newCODE;
 5982: 	my %args;
 5983: 	if      ($resolution eq 'use_unfound') {
 5984: 	    $newCODE='use_unfound';
 5985: 	} elsif ($resolution eq 'use_found') {
 5986: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 5987: 	} elsif ($resolution eq 'use_typed') {
 5988: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 5989: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 5990: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 5991: 	}
 5992: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 5993: 	    $args{'CODE_ignore_dup'}=1;
 5994: 	}
 5995: 	$args{'CODE'}=$newCODE;
 5996: 	($line,$err,$errmsg)=
 5997: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 5998: 				     'CODE',\%args);
 5999:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6000: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6001: 	    ($line,$err,$errmsg)=
 6002: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6003: 					 $which,'answer',
 6004: 					 { 'question'=>$question,
 6005: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6006:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6007: 	    if ($err) { last; }
 6008: 	}
 6009:     }
 6010:     if ($err) {
 6011: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
 6012:     } else {
 6013: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 6014: 	&scantron_putfile($scanlines,$scan_data);
 6015:     }
 6016: }
 6017: 
 6018: =pod
 6019: 
 6020: =item reset_skipping_status
 6021: 
 6022:    Forgets the current set of remember skipped scanlines (and thus
 6023:    reverts back to considering all lines in the
 6024:    scantron_skipped_<filename> file)
 6025: 
 6026: =cut
 6027: 
 6028: sub reset_skipping_status {
 6029:     my ($scanlines,$scan_data)=&scantron_getfile();
 6030:     &scan_data($scan_data,'remember_skipping',undef,1);
 6031:     &scantron_putfile(undef,$scan_data);
 6032: }
 6033: 
 6034: =pod
 6035: 
 6036: =item start_skipping
 6037: 
 6038:    Marks a scanline to be skipped. 
 6039: 
 6040: =cut
 6041: 
 6042: sub start_skipping {
 6043:     my ($scan_data,$i)=@_;
 6044:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6045:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6046: 	$remembered{$i}=2;
 6047:     } else {
 6048: 	$remembered{$i}=1;
 6049:     }
 6050:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6051: }
 6052: 
 6053: =pod
 6054: 
 6055: =item should_be_skipped
 6056: 
 6057:    Checks whether a scanline should be skipped.
 6058: 
 6059: =cut
 6060: 
 6061: sub should_be_skipped {
 6062:     my ($scanlines,$scan_data,$i)=@_;
 6063:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6064: 	# not redoing old skips
 6065: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6066: 	return 0;
 6067:     }
 6068:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6069: 
 6070:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6071: 	return 0;
 6072:     }
 6073:     return 1;
 6074: }
 6075: 
 6076: =pod
 6077: 
 6078: =item remember_current_skipped
 6079: 
 6080:    Discovers what scanlines are in the scantron_skipped_<filename>
 6081:    file and remembers them into scan_data for later use.
 6082: 
 6083: =cut
 6084: 
 6085: sub remember_current_skipped {
 6086:     my ($scanlines,$scan_data)=&scantron_getfile();
 6087:     my %to_remember;
 6088:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6089: 	if ($scanlines->{'skipped'}[$i]) {
 6090: 	    $to_remember{$i}=1;
 6091: 	}
 6092:     }
 6093: 
 6094:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6095:     &scantron_putfile(undef,$scan_data);
 6096: }
 6097: 
 6098: =pod
 6099: 
 6100: =item check_for_error
 6101: 
 6102:     Checks if there was an error when attempting to remove a specific
 6103:     scantron_.. bubble sheet data file. Prints out an error if
 6104:     something went wrong.
 6105: 
 6106: =cut
 6107: 
 6108: sub check_for_error {
 6109:     my ($r,$result)=@_;
 6110:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6111: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6112:     }
 6113: }
 6114: 
 6115: =pod
 6116: 
 6117: =item scantron_warning_screen
 6118: 
 6119:    Interstitial screen to make sure the operator has selected the
 6120:    correct options before we start the validation phase.
 6121: 
 6122: =cut
 6123: 
 6124: sub scantron_warning_screen {
 6125:     my ($button_text)=@_;
 6126:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6127:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6128:     my $CODElist;
 6129:     if ($scantron_config{'CODElocation'} &&
 6130: 	$scantron_config{'CODEstart'} &&
 6131: 	$scantron_config{'CODElength'}) {
 6132: 	$CODElist=$env{'form.scantron_CODElist'};
 6133: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
 6134: 	$CODElist=
 6135: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6136: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6137:     }
 6138:     return ('
 6139: <p>
 6140: <span class="LC_warning">
 6141: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
 6142: </p>
 6143: <table>
 6144: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6145: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6146: '.$CODElist.'
 6147: </table>
 6148: <br />
 6149: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
 6150: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
 6151: 
 6152: <br />
 6153: ');
 6154: }
 6155: 
 6156: =pod
 6157: 
 6158: =item scantron_do_warning
 6159: 
 6160:    Check if the operator has picked something for all required
 6161:    fields. Error out if something is missing.
 6162: 
 6163: =cut
 6164: 
 6165: sub scantron_do_warning {
 6166:     my ($r,$symb)=@_;
 6167:     if (!$symb) {return '';}
 6168:     my $default_form_data=&defaultFormData($symb);
 6169:     $r->print(&scantron_form_start().$default_form_data);
 6170:     if ( $env{'form.selectpage'} eq '' ||
 6171: 	 $env{'form.scantron_selectfile'} eq '' ||
 6172: 	 $env{'form.scantron_format'} eq '' ) {
 6173: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
 6174: 	if ( $env{'form.selectpage'} eq '') {
 6175: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6176: 	} 
 6177: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6178: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a file that contains the student\'s response data.').'</span></p>');
 6179: 	} 
 6180: 	if ( $env{'form.scantron_format'} eq '') {
 6181: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a the format of the student\'s response data.').'</span></p>');
 6182: 	} 
 6183:     } else {
 6184: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
 6185: 	$r->print('
 6186: '.$warning.'
 6187: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6188: <input type="hidden" name="command" value="scantron_validate" />
 6189: ');
 6190:     }
 6191:     $r->print("</form><br />");
 6192:     return '';
 6193: }
 6194: 
 6195: =pod
 6196: 
 6197: =item scantron_form_start
 6198: 
 6199:     html hidden input for remembering all selected grading options
 6200: 
 6201: =cut
 6202: 
 6203: sub scantron_form_start {
 6204:     my ($max_bubble)=@_;
 6205:     my $result= <<SCANTRONFORM;
 6206: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6207:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6208:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6209:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6210:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6211:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6212:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6213:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6214:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6215:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6216: SCANTRONFORM
 6217: 
 6218:   my $line = 0;
 6219:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6220:        my $chunk =
 6221: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6222:        $chunk .=
 6223: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6224:        $chunk .= 
 6225:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6226:        $chunk .=
 6227:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6228:        $result .= $chunk;
 6229:        $line++;
 6230:    }
 6231:     return $result;
 6232: }
 6233: 
 6234: =pod
 6235: 
 6236: =item scantron_validate_file
 6237: 
 6238:     Dispatch routine for doing validation of a bubble sheet data file.
 6239: 
 6240:     Also processes any necessary information resets that need to
 6241:     occur before validation begins (ignore previous corrections,
 6242:     restarting the skipped records processing)
 6243: 
 6244: =cut
 6245: 
 6246: sub scantron_validate_file {
 6247:     my ($r,$symb) = @_;
 6248:     if (!$symb) {return '';}
 6249:     my $default_form_data=&defaultFormData($symb);
 6250:     
 6251:     # do the detection of only doing skipped records first befroe we delete
 6252:     # them when doing the corrections reset
 6253:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6254: 	&reset_skipping_status();
 6255:     }
 6256:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6257: 	&remember_current_skipped();
 6258: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6259:     }
 6260: 
 6261:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6262: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6263: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6264: 	&check_for_error($r,&scantron_remove_scan_data());
 6265: 	$env{'form.scantron_options_ignore'}='done';
 6266:     }
 6267: 
 6268:     if ($env{'form.scantron_corrections'}) {
 6269: 	&scantron_process_corrections($r);
 6270:     }
 6271:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6272:     #get the student pick code ready
 6273:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6274:     my $nav_error;
 6275:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
 6276:     if ($nav_error) {
 6277:         $r->print(&navmap_errormsg());
 6278:         return '';
 6279:     }
 6280:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6281:     $r->print($result);
 6282:     
 6283:     my @validate_phases=( 'sequence',
 6284: 			  'ID',
 6285: 			  'CODE',
 6286: 			  'doublebubble',
 6287: 			  'missingbubbles');
 6288:     if (!$env{'form.validatepass'}) {
 6289: 	$env{'form.validatepass'} = 0;
 6290:     }
 6291:     my $currentphase=$env{'form.validatepass'};
 6292: 
 6293: 
 6294:     my $stop=0;
 6295:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6296: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6297: 	$r->rflush();
 6298: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6299: 	{
 6300: 	    no strict 'refs';
 6301: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6302: 	}
 6303:     }
 6304:     if (!$stop) {
 6305: 	my $warning=&scantron_warning_screen('Start Grading');
 6306: 	$r->print(&mt('Validation process complete.').'<br />'.
 6307:                   $warning.
 6308:                   &mt('Perform verification for each student after storage of submissions?').
 6309:                   '&nbsp;<span class="LC_nobreak"><label>'.
 6310:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 6311:                   ('&nbsp;'x3).'<label>'.
 6312:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 6313:                   '</label></span><br />'.
 6314:                   &mt('Grading will take longer if you use verification.').'<br />'.
 6315:                   &mt("Alternatively, the 'Review bubblesheet data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
 6316:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 6317:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 6318:     } else {
 6319: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6320: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6321:     }
 6322:     if ($stop) {
 6323: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6324: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 6325: 	    $r->print(' '.&mt('this error').' <br />');
 6326: 
 6327: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
 6328: 	} else {
 6329:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6330: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 6331:             } else {
 6332:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 6333:             }
 6334: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6335: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6336: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6337: 	}
 6338:     }
 6339:     $r->print(" </form><br />");
 6340:     return '';
 6341: }
 6342: 
 6343: 
 6344: =pod
 6345: 
 6346: =item scantron_remove_file
 6347: 
 6348:    Removes the requested bubble sheet data file, makes sure that
 6349:    scantron_original_<filename> is never removed
 6350: 
 6351: 
 6352: =cut
 6353: 
 6354: sub scantron_remove_file {
 6355:     my ($which)=@_;
 6356:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6357:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6358:     my $file='scantron_';
 6359:     if ($which eq 'corrected' || $which eq 'skipped') {
 6360: 	$file.=$which.'_';
 6361:     } else {
 6362: 	return 'refused';
 6363:     }
 6364:     $file.=$env{'form.scantron_selectfile'};
 6365:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6366: }
 6367: 
 6368: 
 6369: =pod
 6370: 
 6371: =item scantron_remove_scan_data
 6372: 
 6373:    Removes all scan_data correction for the requested bubble sheet
 6374:    data file.  (In the case that both the are doing skipped records we need
 6375:    to remember the old skipped lines for the time being so that element
 6376:    persists for a while.)
 6377: 
 6378: =cut
 6379: 
 6380: sub scantron_remove_scan_data {
 6381:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6382:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6383:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6384:     my @todelete;
 6385:     my $filename=$env{'form.scantron_selectfile'};
 6386:     foreach my $key (@keys) {
 6387: 	if ($key=~/^\Q$filename\E_/) {
 6388: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6389: 		$key=~/remember_skipping/) {
 6390: 		next;
 6391: 	    }
 6392: 	    push(@todelete,$key);
 6393: 	}
 6394:     }
 6395:     my $result;
 6396:     if (@todelete) {
 6397: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6398: 				       \@todelete,$cdom,$cname);
 6399:     } else {
 6400: 	$result = 'ok';
 6401:     }
 6402:     return $result;
 6403: }
 6404: 
 6405: 
 6406: =pod
 6407: 
 6408: =item scantron_getfile
 6409: 
 6410:     Fetches the requested bubble sheet data file (all 3 versions), and
 6411:     the scan_data hash
 6412:   
 6413:   Arguments:
 6414:     None
 6415: 
 6416:   Returns:
 6417:     2 hash references
 6418: 
 6419:      - first one has 
 6420:          orig      -
 6421:          corrected -
 6422:          skipped   -  each of which points to an array ref of the specified
 6423:                       file broken up into individual lines
 6424:          count     - number of scanlines
 6425:  
 6426:      - second is the scan_data hash possible keys are
 6427:        ($number refers to scanline numbered $number and thus the key affects
 6428:         only that scanline
 6429:         $bubline refers to the specific bubble line element and the aspects
 6430:         refers to that specific bubble line element)
 6431: 
 6432:        $number.user - username:domain to use
 6433:        $number.CODE_ignore_dup 
 6434:                     - ignore the duplicate CODE error 
 6435:        $number.useCODE
 6436:                     - use the CODE in the scanline as is
 6437:        $number.no_bubble.$bubline
 6438:                     - it is valid that there is no bubbled in bubble
 6439:                       at $number $bubline
 6440:        remember_skipping
 6441:                     - a frozen hash containing keys of $number and values
 6442:                       of either 
 6443:                         1 - we are on a 'do skipped records pass' and plan
 6444:                             on processing this line
 6445:                         2 - we are on a 'do skipped records pass' and this
 6446:                             scanline has been marked to skip yet again
 6447: 
 6448: =cut
 6449: 
 6450: sub scantron_getfile {
 6451:     #FIXME really would prefer a scantron directory
 6452:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6453:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6454:     my $lines;
 6455:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6456: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 6457:     my %scanlines;
 6458:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 6459:     my $temp=$scanlines{'orig'};
 6460:     $scanlines{'count'}=$#$temp;
 6461: 
 6462:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6463: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 6464:     if ($lines eq '-1') {
 6465: 	$scanlines{'corrected'}=[];
 6466:     } else {
 6467: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 6468:     }
 6469:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6470: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 6471:     if ($lines eq '-1') {
 6472: 	$scanlines{'skipped'}=[];
 6473:     } else {
 6474: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 6475:     }
 6476:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 6477:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 6478:     my %scan_data = @tmp;
 6479:     return (\%scanlines,\%scan_data);
 6480: }
 6481: 
 6482: =pod
 6483: 
 6484: =item lonnet_putfile
 6485: 
 6486:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 6487: 
 6488:  Arguments:
 6489:    $contents - data to store
 6490:    $filename - filename to store $contents into
 6491: 
 6492:  Returns:
 6493:    result value from &Apache::lonnet::finishuserfileupload
 6494: 
 6495: =cut
 6496: 
 6497: sub lonnet_putfile {
 6498:     my ($contents,$filename)=@_;
 6499:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6500:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6501:     $env{'form.sillywaytopassafilearound'}=$contents;
 6502:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 6503: 
 6504: }
 6505: 
 6506: =pod
 6507: 
 6508: =item scantron_putfile
 6509: 
 6510:     Stores the current version of the bubble sheet data files, and the
 6511:     scan_data hash. (Does not modify the original version only the
 6512:     corrected and skipped versions.
 6513: 
 6514:  Arguments:
 6515:     $scanlines - hash ref that looks like the first return value from
 6516:                  &scantron_getfile()
 6517:     $scan_data - hash ref that looks like the second return value from
 6518:                  &scantron_getfile()
 6519: 
 6520: =cut
 6521: 
 6522: sub scantron_putfile {
 6523:     my ($scanlines,$scan_data) = @_;
 6524:     #FIXME really would prefer a scantron directory
 6525:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6526:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6527:     if ($scanlines) {
 6528: 	my $prefix='scantron_';
 6529: # no need to update orig, shouldn't change
 6530: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 6531: #		    $env{'form.scantron_selectfile'});
 6532: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 6533: 			$prefix.'corrected_'.
 6534: 			$env{'form.scantron_selectfile'});
 6535: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 6536: 			$prefix.'skipped_'.
 6537: 			$env{'form.scantron_selectfile'});
 6538:     }
 6539:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 6540: }
 6541: 
 6542: =pod
 6543: 
 6544: =item scantron_get_line
 6545: 
 6546:    Returns the correct version of the scanline
 6547: 
 6548:  Arguments:
 6549:     $scanlines - hash ref that looks like the first return value from
 6550:                  &scantron_getfile()
 6551:     $scan_data - hash ref that looks like the second return value from
 6552:                  &scantron_getfile()
 6553:     $i         - number of the requested line (starts at 0)
 6554: 
 6555:  Returns:
 6556:    A scanline, (either the original or the corrected one if it
 6557:    exists), or undef if the requested scanline should be
 6558:    skipped. (Either because it's an skipped scanline, or it's an
 6559:    unskipped scanline and we are not doing a 'do skipped scanlines'
 6560:    pass.
 6561: 
 6562: =cut
 6563: 
 6564: sub scantron_get_line {
 6565:     my ($scanlines,$scan_data,$i)=@_;
 6566:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 6567:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 6568:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 6569:     return $scanlines->{'orig'}[$i]; 
 6570: }
 6571: 
 6572: =pod
 6573: 
 6574: =item scantron_todo_count
 6575: 
 6576:     Counts the number of scanlines that need processing.
 6577: 
 6578:  Arguments:
 6579:     $scanlines - hash ref that looks like the first return value from
 6580:                  &scantron_getfile()
 6581:     $scan_data - hash ref that looks like the second return value from
 6582:                  &scantron_getfile()
 6583: 
 6584:  Returns:
 6585:     $count - number of scanlines to process
 6586: 
 6587: =cut
 6588: 
 6589: sub get_todo_count {
 6590:     my ($scanlines,$scan_data)=@_;
 6591:     my $count=0;
 6592:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6593: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6594: 	if ($line=~/^[\s\cz]*$/) { next; }
 6595: 	$count++;
 6596:     }
 6597:     return $count;
 6598: }
 6599: 
 6600: =pod
 6601: 
 6602: =item scantron_put_line
 6603: 
 6604:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
 6605:     data file.
 6606: 
 6607:  Arguments:
 6608:     $scanlines - hash ref that looks like the first return value from
 6609:                  &scantron_getfile()
 6610:     $scan_data - hash ref that looks like the second return value from
 6611:                  &scantron_getfile()
 6612:     $i         - line number to update
 6613:     $newline   - contents of the updated scanline
 6614:     $skip      - if true make the line for skipping and update the
 6615:                  'skipped' file
 6616: 
 6617: =cut
 6618: 
 6619: sub scantron_put_line {
 6620:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 6621:     if ($skip) {
 6622: 	$scanlines->{'skipped'}[$i]=$newline;
 6623: 	&start_skipping($scan_data,$i);
 6624: 	return;
 6625:     }
 6626:     $scanlines->{'corrected'}[$i]=$newline;
 6627: }
 6628: 
 6629: =pod
 6630: 
 6631: =item scantron_clear_skip
 6632: 
 6633:    Remove a line from the 'skipped' file
 6634: 
 6635:  Arguments:
 6636:     $scanlines - hash ref that looks like the first return value from
 6637:                  &scantron_getfile()
 6638:     $scan_data - hash ref that looks like the second return value from
 6639:                  &scantron_getfile()
 6640:     $i         - line number to update
 6641: 
 6642: =cut
 6643: 
 6644: sub scantron_clear_skip {
 6645:     my ($scanlines,$scan_data,$i)=@_;
 6646:     if (exists($scanlines->{'skipped'}[$i])) {
 6647: 	undef($scanlines->{'skipped'}[$i]);
 6648: 	return 1;
 6649:     }
 6650:     return 0;
 6651: }
 6652: 
 6653: =pod
 6654: 
 6655: =item scantron_filter_not_exam
 6656: 
 6657:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 6658:    filter out resources that are not marked as 'exam' mode
 6659: 
 6660: =cut
 6661: 
 6662: sub scantron_filter_not_exam {
 6663:     my ($curres)=@_;
 6664:     
 6665:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 6666: 	# if the user has asked to not have either hidden
 6667: 	# or 'randomout' controlled resources to be graded
 6668: 	# don't include them
 6669: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6670: 	    && $curres->randomout) {
 6671: 	    return 0;
 6672: 	}
 6673: 	return 1;
 6674:     }
 6675:     return 0;
 6676: }
 6677: 
 6678: =pod
 6679: 
 6680: =item scantron_validate_sequence
 6681: 
 6682:     Validates the selected sequence, checking for resource that are
 6683:     not set to exam mode.
 6684: 
 6685: =cut
 6686: 
 6687: sub scantron_validate_sequence {
 6688:     my ($r,$currentphase) = @_;
 6689: 
 6690:     my $navmap=Apache::lonnavmaps::navmap->new();
 6691:     unless (ref($navmap)) {
 6692:         $r->print(&navmap_errormsg());
 6693:         return (1,$currentphase);
 6694:     }
 6695:     my (undef,undef,$sequence)=
 6696: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6697: 
 6698:     my $map=$navmap->getResourceByUrl($sequence);
 6699: 
 6700:     $r->print('<input type="hidden" name="validate_sequence_exam"
 6701:                                     value="ignore" />');
 6702:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 6703: 	my @resources=
 6704: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 6705: 	if (@resources) {
 6706: 	    $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>");
 6707: 	    return (1,$currentphase);
 6708: 	}
 6709:     }
 6710: 
 6711:     return (0,$currentphase+1);
 6712: }
 6713: 
 6714: 
 6715: 
 6716: sub scantron_validate_ID {
 6717:     my ($r,$currentphase) = @_;
 6718:     
 6719:     #get student info
 6720:     my $classlist=&Apache::loncoursedata::get_classlist();
 6721:     my %idmap=&username_to_idmap($classlist);
 6722: 
 6723:     #get scantron line setup
 6724:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6725:     my ($scanlines,$scan_data)=&scantron_getfile();
 6726: 
 6727:     my $nav_error;
 6728:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble_lines.. array.
 6729:     if ($nav_error) {
 6730:         $r->print(&navmap_errormsg());
 6731:         return(1,$currentphase);
 6732:     }
 6733: 
 6734:     my %found=('ids'=>{},'usernames'=>{});
 6735:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6736: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6737: 	if ($line=~/^[\s\cz]*$/) { next; }
 6738: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6739: 						 $scan_data);
 6740: 	my $id=$$scan_record{'scantron.ID'};
 6741: 	my $found;
 6742: 	foreach my $checkid (keys(%idmap)) {
 6743: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 6744: 	}
 6745: 	if ($found) {
 6746: 	    my $username=$idmap{$found};
 6747: 	    if ($found{'ids'}{$found}) {
 6748: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6749: 					 $line,'duplicateID',$found);
 6750: 		return(1,$currentphase);
 6751: 	    } elsif ($found{'usernames'}{$username}) {
 6752: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6753: 					 $line,'duplicateID',$username);
 6754: 		return(1,$currentphase);
 6755: 	    }
 6756: 	    #FIXME store away line we previously saw the ID on to use above
 6757: 	    $found{'ids'}{$found}++;
 6758: 	    $found{'usernames'}{$username}++;
 6759: 	} else {
 6760: 	    if ($id =~ /^\s*$/) {
 6761: 		my $username=&scan_data($scan_data,"$i.user");
 6762: 		if (defined($username) && $found{'usernames'}{$username}) {
 6763: 		    &scantron_get_correction($r,$i,$scan_record,
 6764: 					     \%scantron_config,
 6765: 					     $line,'duplicateID',$username);
 6766: 		    return(1,$currentphase);
 6767: 		} elsif (!defined($username)) {
 6768: 		    &scantron_get_correction($r,$i,$scan_record,
 6769: 					     \%scantron_config,
 6770: 					     $line,'incorrectID');
 6771: 		    return(1,$currentphase);
 6772: 		}
 6773: 		$found{'usernames'}{$username}++;
 6774: 	    } else {
 6775: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6776: 					 $line,'incorrectID');
 6777: 		return(1,$currentphase);
 6778: 	    }
 6779: 	}
 6780:     }
 6781: 
 6782:     return (0,$currentphase+1);
 6783: }
 6784: 
 6785: 
 6786: sub scantron_get_correction {
 6787:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
 6788: #FIXME in the case of a duplicated ID the previous line, probably need
 6789: #to show both the current line and the previous one and allow skipping
 6790: #the previous one or the current one
 6791: 
 6792:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 6793: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6794: 			    " for PaperID <tt>[_1]</tt>",
 6795: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
 6796:     } else {
 6797: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6798: 			    " in scanline [_1] <pre>[_2]</pre>",
 6799: 			    $i,$line)."</p> \n");
 6800:     }
 6801:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
 6802: 			  "The name on the paper is [_2],[_3]",
 6803: 			  $$scan_record{'scantron.ID'},
 6804: 			  $$scan_record{'scantron.LastName'},
 6805: 			  $$scan_record{'scantron.FirstName'})."</p>";
 6806: 
 6807:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 6808:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 6809:                            # Array populated for doublebubble or
 6810:     my @lines_to_correct;  # missingbubble errors to build javascript
 6811:                            # to validate radio button checking   
 6812: 
 6813:     if ($error =~ /ID$/) {
 6814: 	if ($error eq 'incorrectID') {
 6815: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
 6816: 		      "</p>\n");
 6817: 	} elsif ($error eq 'duplicateID') {
 6818: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 6819: 	}
 6820: 	$r->print($message);
 6821: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6822: 	$r->print("\n<ul><li> ");
 6823: 	#FIXME it would be nice if this sent back the user ID and
 6824: 	#could do partial userID matches
 6825: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 6826: 				       'scantron_username','scantron_domain'));
 6827: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 6828: 	$r->print("\n@".
 6829: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 6830: 
 6831: 	$r->print('</li>');
 6832:     } elsif ($error =~ /CODE$/) {
 6833: 	if ($error eq 'incorrectCODE') {
 6834: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 6835: 	} elsif ($error eq 'duplicateCODE') {
 6836: 	    $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");
 6837: 	}
 6838: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
 6839: 			    $$scan_record{'scantron.CODE'})."<br />\n");
 6840: 	$r->print($message);
 6841: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6842: 	$r->print("\n<br /> ");
 6843: 	my $i=0;
 6844: 	if ($error eq 'incorrectCODE' 
 6845: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 6846: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 6847: 	    if ($closest > 0) {
 6848: 		foreach my $testcode (@{$closest}) {
 6849: 		    my $checked='';
 6850: 		    if (!$i) { $checked=' checked="checked"'; }
 6851: 		    $r->print("
 6852:    <label>
 6853:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 6854:        ".&mt("Use the similar CODE [_1] instead.",
 6855: 	    "<b><tt>".$testcode."</tt></b>")."
 6856:     </label>
 6857:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 6858: 		    $r->print("\n<br />");
 6859: 		    $i++;
 6860: 		}
 6861: 	    }
 6862: 	}
 6863: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 6864: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 6865: 	    $r->print("
 6866:     <label>
 6867:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 6868:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
 6869: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 6870:     </label>");
 6871: 	    $r->print("\n<br />");
 6872: 	}
 6873: 
 6874: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
 6875: function change_radio(field) {
 6876:     var slct=document.scantronupload.scantron_CODE_resolution;
 6877:     var i;
 6878:     for (i=0;i<slct.length;i++) {
 6879:         if (slct[i].value==field) { slct[i].checked=true; }
 6880:     }
 6881: }
 6882: ENDSCRIPT
 6883: 	my $href="/adm/pickcode?".
 6884: 	   "form=".&escape("scantronupload").
 6885: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 6886: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 6887: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 6888: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 6889: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 6890: 	    $r->print("
 6891:     <label>
 6892:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 6893:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 6894: 	     "<a target='_blank' href='$href'>","</a>")."
 6895:     </label> 
 6896:     ".&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\')" />'));
 6897: 	    $r->print("\n<br />");
 6898: 	}
 6899: 	$r->print("
 6900:     <label>
 6901:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 6902:        ".&mt("Use [_1] as the CODE.",
 6903: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 6904: 	$r->print("\n<br /><br />");
 6905:     } elsif ($error eq 'doublebubble') {
 6906: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 6907: 
 6908: 	# The form field scantron_questions is acutally a list of line numbers.
 6909: 	# represented by this form so:
 6910: 
 6911: 	my $line_list = &questions_to_line_list($arg);
 6912: 
 6913: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6914: 		  $line_list.'" />');
 6915: 	$r->print($message);
 6916: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 6917: 	foreach my $question (@{$arg}) {
 6918: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6919:                                                    $scan_record, $error);
 6920:             push(@lines_to_correct,@linenums);
 6921: 	}
 6922:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6923:     } elsif ($error eq 'missingbubble') {
 6924: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
 6925: 	$r->print($message);
 6926: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 6927: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 6928: 
 6929: 	# The form field scantron_questions is actually a list of line numbers not
 6930: 	# a list of question numbers. Therefore:
 6931: 	#
 6932: 	
 6933: 	my $line_list = &questions_to_line_list($arg);
 6934: 
 6935: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6936: 		  $line_list.'" />');
 6937: 	foreach my $question (@{$arg}) {
 6938: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6939:                                                    $scan_record, $error);
 6940:             push(@lines_to_correct,@linenums);
 6941: 	}
 6942:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6943:     } else {
 6944: 	$r->print("\n<ul>");
 6945:     }
 6946:     $r->print("\n</li></ul>");
 6947: }
 6948: 
 6949: sub verify_bubbles_checked {
 6950:     my (@ansnums) = @_;
 6951:     my $ansnumstr = join('","',@ansnums);
 6952:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 6953:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
 6954: function verify_bubble_radio(form) {
 6955:     var ansnumArray = new Array ("$ansnumstr");
 6956:     var need_bubble_count = 0;
 6957:     for (var i=0; i<ansnumArray.length; i++) {
 6958:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 6959:             var bubble_picked = 0; 
 6960:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 6961:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 6962:                     bubble_picked = 1;
 6963:                 }
 6964:             }
 6965:             if (bubble_picked == 0) {
 6966:                 need_bubble_count ++;
 6967:             }
 6968:         }
 6969:     }
 6970:     if (need_bubble_count) {
 6971:         alert("$warning");
 6972:         return;
 6973:     }
 6974:     form.submit(); 
 6975: }
 6976: ENDSCRIPT
 6977:     return $output;
 6978: }
 6979: 
 6980: =pod
 6981: 
 6982: =item  questions_to_line_list
 6983: 
 6984: Converts a list of questions into a string of comma separated
 6985: line numbers in the answer sheet used by the questions.  This is
 6986: used to fill in the scantron_questions form field.
 6987: 
 6988:   Arguments:
 6989:      questions    - Reference to an array of questions.
 6990: 
 6991: =cut
 6992: 
 6993: 
 6994: sub questions_to_line_list {
 6995:     my ($questions) = @_;
 6996:     my @lines;
 6997: 
 6998:     foreach my $item (@{$questions}) {
 6999:         my $question = $item;
 7000:         my ($first,$count,$last);
 7001:         if ($item =~ /^(\d+)\.(\d+)$/) {
 7002:             $question = $1;
 7003:             my $subquestion = $2;
 7004:             $first = $first_bubble_line{$question-1} + 1;
 7005:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7006:             my $subcount = 1;
 7007:             while ($subcount<$subquestion) {
 7008:                 $first += $subans[$subcount-1];
 7009:                 $subcount ++;
 7010:             }
 7011:             $count = $subans[$subquestion-1];
 7012:         } else {
 7013: 	    $first   = $first_bubble_line{$question-1} + 1;
 7014: 	    $count   = $bubble_lines_per_response{$question-1};
 7015:         }
 7016:         $last = $first+$count-1;
 7017:         push(@lines, ($first..$last));
 7018:     }
 7019:     return join(',', @lines);
 7020: }
 7021: 
 7022: =pod 
 7023: 
 7024: =item prompt_for_corrections
 7025: 
 7026: Prompts for a potentially multiline correction to the
 7027: user's bubbling (factors out common code from scantron_get_correction
 7028: for multi and missing bubble cases).
 7029: 
 7030:  Arguments:
 7031:    $r           - Apache request object.
 7032:    $question    - The question number to prompt for.
 7033:    $scan_config - The scantron file configuration hash.
 7034:    $scan_record - Reference to the hash that has the the parsed scanlines.
 7035:    $error       - Type of error
 7036: 
 7037:  Implicit inputs:
 7038:    %bubble_lines_per_response   - Starting line numbers for each question.
 7039:                                   Numbered from 0 (but question numbers are from
 7040:                                   1.
 7041:    %first_bubble_line           - Starting bubble line for each question.
 7042:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 7043:                                   type problems render as separate sub-questions, 
 7044:                                   in exam mode. This hash contains a 
 7045:                                   comma-separated list of the lines per 
 7046:                                   sub-question.
 7047:    %responsetype_per_response   - essayresponse, formularesponse,
 7048:                                   stringresponse, imageresponse, reactionresponse,
 7049:                                   and organicresponse type problem parts can have
 7050:                                   multiple lines per response if the weight
 7051:                                   assigned exceeds 10.  In this case, only
 7052:                                   one bubble per line is permitted, but more 
 7053:                                   than one line might contain bubbles, e.g.
 7054:                                   bubbling of: line 1 - J, line 2 - J, 
 7055:                                   line 3 - B would assign 22 points.  
 7056: 
 7057: =cut
 7058: 
 7059: sub prompt_for_corrections {
 7060:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
 7061:     my ($current_line,$lines);
 7062:     my @linenums;
 7063:     my $questionnum = $question;
 7064:     if ($question =~ /^(\d+)\.(\d+)$/) {
 7065:         $question = $1;
 7066:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7067:         my $subquestion = $2;
 7068:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7069:         my $subcount = 1;
 7070:         while ($subcount<$subquestion) {
 7071:             $current_line += $subans[$subcount-1];
 7072:             $subcount ++;
 7073:         }
 7074:         $lines = $subans[$subquestion-1];
 7075:     } else {
 7076:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7077:         $lines        = $bubble_lines_per_response{$question-1};
 7078:     }
 7079:     if ($lines > 1) {
 7080:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7081:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
 7082:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
 7083:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
 7084:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
 7085:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
 7086:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
 7087:             $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 />');
 7088:         } else {
 7089:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7090:         }
 7091:     }
 7092:     for (my $i =0; $i < $lines; $i++) {
 7093:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7094: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
 7095: 	        		  $questionnum,$error,split('', $selected));
 7096:         push(@linenums,$current_line);
 7097: 	$current_line++;
 7098:     }
 7099:     if ($lines > 1) {
 7100: 	$r->print("<hr /><br />");
 7101:     }
 7102:     return @linenums;
 7103: }
 7104: 
 7105: =pod
 7106: 
 7107: =item scantron_bubble_selector
 7108:   
 7109:    Generates the html radiobuttons to correct a single bubble line
 7110:    possibly showing the existing the selected bubbles if known
 7111: 
 7112:  Arguments:
 7113:     $r           - Apache request object
 7114:     $scan_config - hash from &get_scantron_config()
 7115:     $line        - Number of the line being displayed.
 7116:     $questionnum - Question number (may include subquestion)
 7117:     $error       - Type of error.
 7118:     @selected    - Array of bubbles picked on this line.
 7119: 
 7120: =cut
 7121: 
 7122: sub scantron_bubble_selector {
 7123:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7124:     my $max=$$scan_config{'Qlength'};
 7125: 
 7126:     my $scmode=$$scan_config{'Qon'};
 7127:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
 7128: 
 7129:     my @alphabet=('A'..'Z');
 7130:     $r->print(&Apache::loncommon::start_data_table().
 7131:               &Apache::loncommon::start_data_table_row());
 7132:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7133:     for (my $i=0;$i<$max+1;$i++) {
 7134: 	$r->print("\n".'<td align="center">');
 7135: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7136: 	else { $r->print('&nbsp;'); }
 7137: 	$r->print('</td>');
 7138:     }
 7139:     $r->print(&Apache::loncommon::end_data_table_row().
 7140:               &Apache::loncommon::start_data_table_row());
 7141:     for (my $i=0;$i<$max;$i++) {
 7142: 	$r->print("\n".
 7143: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7144: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7145:     }
 7146:     my $nobub_checked = ' ';
 7147:     if ($error eq 'missingbubble') {
 7148:         $nobub_checked = ' checked = "checked" ';
 7149:     }
 7150:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7151: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7152:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7153:               $line.'" value="'.$questionnum.'" /></td>');
 7154:     $r->print(&Apache::loncommon::end_data_table_row().
 7155:               &Apache::loncommon::end_data_table());
 7156: }
 7157: 
 7158: =pod
 7159: 
 7160: =item num_matches
 7161: 
 7162:    Counts the number of characters that are the same between the two arguments.
 7163: 
 7164:  Arguments:
 7165:    $orig - CODE from the scanline
 7166:    $code - CODE to match against
 7167: 
 7168:  Returns:
 7169:    $count - integer count of the number of same characters between the
 7170:             two arguments
 7171: 
 7172: =cut
 7173: 
 7174: sub num_matches {
 7175:     my ($orig,$code) = @_;
 7176:     my @code=split(//,$code);
 7177:     my @orig=split(//,$orig);
 7178:     my $same=0;
 7179:     for (my $i=0;$i<scalar(@code);$i++) {
 7180: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7181:     }
 7182:     return $same;
 7183: }
 7184: 
 7185: =pod
 7186: 
 7187: =item scantron_get_closely_matching_CODEs
 7188: 
 7189:    Cycles through all CODEs and finds the set that has the greatest
 7190:    number of same characters as the provided CODE
 7191: 
 7192:  Arguments:
 7193:    $allcodes - hash ref returned by &get_codes()
 7194:    $CODE     - CODE from the current scanline
 7195: 
 7196:  Returns:
 7197:    2 element list
 7198:     - first elements is number of how closely matching the best fit is 
 7199:       (5 means best set has 5 matching characters)
 7200:     - second element is an arrary ref containing the set of valid CODEs
 7201:       that best fit the passed in CODE
 7202: 
 7203: =cut
 7204: 
 7205: sub scantron_get_closely_matching_CODEs {
 7206:     my ($allcodes,$CODE)=@_;
 7207:     my @CODEs;
 7208:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7209: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7210:     }
 7211: 
 7212:     return ($#CODEs,$CODEs[-1]);
 7213: }
 7214: 
 7215: =pod
 7216: 
 7217: =item get_codes
 7218: 
 7219:    Builds a hash which has keys of all of the valid CODEs from the selected
 7220:    set of remembered CODEs.
 7221: 
 7222:  Arguments:
 7223:   $old_name - name of the set of remembered CODEs
 7224:   $cdom     - domain of the course
 7225:   $cnum     - internal course name
 7226: 
 7227:  Returns:
 7228:   %allcodes - keys are the valid CODEs, values are all 1
 7229: 
 7230: =cut
 7231: 
 7232: sub get_codes {
 7233:     my ($old_name, $cdom, $cnum) = @_;
 7234:     if (!$old_name) {
 7235: 	$old_name=$env{'form.scantron_CODElist'};
 7236:     }
 7237:     if (!$cdom) {
 7238: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7239:     }
 7240:     if (!$cnum) {
 7241: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7242:     }
 7243:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7244: 				    $cdom,$cnum);
 7245:     my %allcodes;
 7246:     if ($result{"type\0$old_name"} eq 'number') {
 7247: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7248:     } else {
 7249: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7250:     }
 7251:     return %allcodes;
 7252: }
 7253: 
 7254: =pod
 7255: 
 7256: =item scantron_validate_CODE
 7257: 
 7258:    Validates all scanlines in the selected file to not have any
 7259:    invalid or underspecified CODEs and that none of the codes are
 7260:    duplicated if this was requested.
 7261: 
 7262: =cut
 7263: 
 7264: sub scantron_validate_CODE {
 7265:     my ($r,$currentphase) = @_;
 7266:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7267:     if ($scantron_config{'CODElocation'} &&
 7268: 	$scantron_config{'CODEstart'} &&
 7269: 	$scantron_config{'CODElength'}) {
 7270: 	if (!defined($env{'form.scantron_CODElist'})) {
 7271: 	    &FIXME_blow_up()
 7272: 	}
 7273:     } else {
 7274: 	return (0,$currentphase+1);
 7275:     }
 7276:     
 7277:     my %usedCODEs;
 7278: 
 7279:     my %allcodes=&get_codes();
 7280: 
 7281:     my $nav_error;
 7282:     &scantron_get_maxbubble(\$nav_error); # parse needs the lines per response array.
 7283:     if ($nav_error) {
 7284:         $r->print(&navmap_errormsg());
 7285:         return(1,$currentphase);
 7286:     }
 7287: 
 7288:     my ($scanlines,$scan_data)=&scantron_getfile();
 7289:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7290: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7291: 	if ($line=~/^[\s\cz]*$/) { next; }
 7292: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7293: 						 $scan_data);
 7294: 	my $CODE=$$scan_record{'scantron.CODE'};
 7295: 	my $error=0;
 7296: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7297: 	    &scantron_get_correction($r,$i,$scan_record,
 7298: 				     \%scantron_config,
 7299: 				     $line,'incorrectCODE',\%allcodes);
 7300: 	    return(1,$currentphase);
 7301: 	}
 7302: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7303: 	    && !$$scan_record{'scantron.useCODE'}) {
 7304: 	    &scantron_get_correction($r,$i,$scan_record,
 7305: 				     \%scantron_config,
 7306: 				     $line,'incorrectCODE',\%allcodes);
 7307: 	    return(1,$currentphase);
 7308: 	}
 7309: 	if (exists($usedCODEs{$CODE}) 
 7310: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 7311: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 7312: 	    &scantron_get_correction($r,$i,$scan_record,
 7313: 				     \%scantron_config,
 7314: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 7315: 	    return(1,$currentphase);
 7316: 	}
 7317: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 7318:     }
 7319:     return (0,$currentphase+1);
 7320: }
 7321: 
 7322: =pod
 7323: 
 7324: =item scantron_validate_doublebubble
 7325: 
 7326:    Validates all scanlines in the selected file to not have any
 7327:    bubble lines with multiple bubbles marked.
 7328: 
 7329: =cut
 7330: 
 7331: sub scantron_validate_doublebubble {
 7332:     my ($r,$currentphase) = @_;
 7333:     #get student info
 7334:     my $classlist=&Apache::loncoursedata::get_classlist();
 7335:     my %idmap=&username_to_idmap($classlist);
 7336: 
 7337:     #get scantron line setup
 7338:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7339:     my ($scanlines,$scan_data)=&scantron_getfile();
 7340:     my $nav_error;
 7341:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble line array.
 7342:     if ($nav_error) {
 7343:         $r->print(&navmap_errormsg());
 7344:         return(1,$currentphase);
 7345:     }
 7346: 
 7347:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7348: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7349: 	if ($line=~/^[\s\cz]*$/) { next; }
 7350: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7351: 						 $scan_data);
 7352: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 7353: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 7354: 				 'doublebubble',
 7355: 				 $$scan_record{'scantron.doubleerror'});
 7356:     	return (1,$currentphase);
 7357:     }
 7358:     return (0,$currentphase+1);
 7359: }
 7360: 
 7361: 
 7362: sub scantron_get_maxbubble {
 7363:     my ($nav_error) = @_;
 7364:     if (defined($env{'form.scantron_maxbubble'}) &&
 7365: 	$env{'form.scantron_maxbubble'}) {
 7366: 	&restore_bubble_lines();
 7367: 	return $env{'form.scantron_maxbubble'};
 7368:     }
 7369: 
 7370:     my (undef, undef, $sequence) =
 7371: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7372: 
 7373:     my $navmap=Apache::lonnavmaps::navmap->new();
 7374:     unless (ref($navmap)) {
 7375:         if (ref($nav_error)) {
 7376:             $$nav_error = 1;
 7377:         }
 7378:         return;
 7379:     }
 7380:     my $map=$navmap->getResourceByUrl($sequence);
 7381:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7382: 
 7383:     &Apache::lonxml::clear_problem_counter();
 7384: 
 7385:     my $uname       = $env{'user.name'};
 7386:     my $udom        = $env{'user.domain'};
 7387:     my $cid         = $env{'request.course.id'};
 7388:     my $total_lines = 0;
 7389:     %bubble_lines_per_response = ();
 7390:     %first_bubble_line         = ();
 7391:     %subdivided_bubble_lines   = ();
 7392:     %responsetype_per_response = ();
 7393: 
 7394:     my $response_number = 0;
 7395:     my $bubble_line     = 0;
 7396:     foreach my $resource (@resources) {
 7397:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
 7398:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 7399: 	    foreach my $part_id (@{$parts}) {
 7400:                 my $lines;
 7401: 
 7402: 	        # TODO - make this a persistent hash not an array.
 7403: 
 7404:                 # optionresponse, matchresponse and rankresponse type items 
 7405:                 # render as separate sub-questions in exam mode.
 7406:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 7407:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 7408:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 7409:                     my ($numbub,$numshown);
 7410:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 7411:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 7412:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 7413:                         }
 7414:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 7415:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 7416:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 7417:                         }
 7418:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 7419:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 7420:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 7421:                         }
 7422:                     }
 7423:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 7424:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 7425:                     }
 7426:                     my $bubbles_per_line = 10;
 7427:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
 7428:                     if (($numbub % $bubbles_per_line) != 0) {
 7429:                         $inner_bubble_lines++;
 7430:                     }
 7431:                     for (my $i=0; $i<$numshown; $i++) {
 7432:                         $subdivided_bubble_lines{$response_number} .= 
 7433:                             $inner_bubble_lines.',';
 7434:                     }
 7435:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 7436:                     $lines = $numshown * $inner_bubble_lines;
 7437:                 } else {
 7438:                     $lines = $analysis->{"$part_id.bubble_lines"};
 7439:                 } 
 7440: 
 7441:                 $first_bubble_line{$response_number} = $bubble_line;
 7442: 	        $bubble_lines_per_response{$response_number} = $lines;
 7443:                 $responsetype_per_response{$response_number} = 
 7444:                     $analysis->{$part_id.'.type'};
 7445: 	        $response_number++;
 7446: 
 7447: 	        $bubble_line +=  $lines;
 7448: 	        $total_lines +=  $lines;
 7449: 	    }
 7450:         }
 7451:     }
 7452:     &Apache::lonnet::delenv('scantron.');
 7453: 
 7454:     &save_bubble_lines();
 7455:     $env{'form.scantron_maxbubble'} =
 7456: 	$total_lines;
 7457:     return $env{'form.scantron_maxbubble'};
 7458: }
 7459: 
 7460: sub scantron_validate_missingbubbles {
 7461:     my ($r,$currentphase) = @_;
 7462:     #get student info
 7463:     my $classlist=&Apache::loncoursedata::get_classlist();
 7464:     my %idmap=&username_to_idmap($classlist);
 7465: 
 7466:     #get scantron line setup
 7467:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7468:     my ($scanlines,$scan_data)=&scantron_getfile();
 7469:     my $nav_error;
 7470:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
 7471:     if ($nav_error) {
 7472:         return(1,$currentphase);
 7473:     }
 7474:     if (!$max_bubble) { $max_bubble=2**31; }
 7475:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7476: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7477: 	if ($line=~/^[\s\cz]*$/) { next; }
 7478: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7479: 						 $scan_data);
 7480: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 7481: 	my @to_correct;
 7482: 	
 7483: 	# Probably here's where the error is...
 7484: 
 7485: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 7486:             my $lastbubble;
 7487:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 7488:                my $question = $1;
 7489:                my $subquestion = $2;
 7490:                if (!defined($first_bubble_line{$question -1})) { next; }
 7491:                my $first = $first_bubble_line{$question-1};
 7492:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7493:                my $subcount = 1;
 7494:                while ($subcount<$subquestion) {
 7495:                    $first += $subans[$subcount-1];
 7496:                    $subcount ++;
 7497:                }
 7498:                my $count = $subans[$subquestion-1];
 7499:                $lastbubble = $first + $count;
 7500:             } else {
 7501:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
 7502:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
 7503:             }
 7504:             if ($lastbubble > $max_bubble) { next; }
 7505: 	    push(@to_correct,$missing);
 7506: 	}
 7507: 	if (@to_correct) {
 7508: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7509: 				     $line,'missingbubble',\@to_correct);
 7510: 	    return (1,$currentphase);
 7511: 	}
 7512: 
 7513:     }
 7514:     return (0,$currentphase+1);
 7515: }
 7516: 
 7517: 
 7518: sub scantron_process_students {
 7519:     my ($r,$symb) = @_;
 7520: 
 7521:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7522:     if (!$symb) {
 7523: 	return '';
 7524:     }
 7525:     my $default_form_data=&defaultFormData($symb);
 7526: 
 7527:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7528:     my ($scanlines,$scan_data)=&scantron_getfile();
 7529:     my $classlist=&Apache::loncoursedata::get_classlist();
 7530:     my %idmap=&username_to_idmap($classlist);
 7531:     my $navmap=Apache::lonnavmaps::navmap->new();
 7532:     unless (ref($navmap)) {
 7533:         $r->print(&navmap_errormsg());
 7534:         return '';
 7535:     }  
 7536:     my $map=$navmap->getResourceByUrl($sequence);
 7537:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7538:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 7539:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 7540:                             \%grader_randomlists_by_symb);
 7541:     my $resource_error;
 7542:     foreach my $resource (@resources) {
 7543:         my $ressymb;
 7544:         if (ref($resource)) {
 7545:             $ressymb = $resource->symb();
 7546:         } else {
 7547:             $resource_error = 1;
 7548:             last;
 7549:         }
 7550:         my ($analysis,$parts) =
 7551:             &scantron_partids_tograde($resource,$env{'request.course.id'},
 7552:                                       $env{'user.name'},$env{'user.domain'},1);
 7553:         $grader_partids_by_symb{$ressymb} = $parts;
 7554:         if (ref($analysis) eq 'HASH') {
 7555:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7556:                 $grader_randomlists_by_symb{$ressymb} = 
 7557:                     $analysis->{'parts_withrandomlist'};
 7558:             }
 7559:         }
 7560:     }
 7561:     if ($resource_error) {
 7562:         $r->print(&navmap_errormsg());
 7563:         return '';
 7564:     }
 7565: 
 7566:     my ($uname,$udom);
 7567:     my $result= <<SCANTRONFORM;
 7568: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7569:   <input type="hidden" name="command" value="scantron_configphase" />
 7570:   $default_form_data
 7571: SCANTRONFORM
 7572:     $r->print($result);
 7573: 
 7574:     my @delayqueue;
 7575:     my (%completedstudents,%scandata);
 7576:     
 7577:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 7578:     my $count=&get_todo_count($scanlines,$scan_data);
 7579:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
 7580:  				    'Bubblesheet Progress',$count,
 7581: 				    'inline',undef,'scantronupload');
 7582:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 7583: 					  'Processing first student');
 7584:     $r->print('<br />');
 7585:     my $start=&Time::HiRes::time();
 7586:     my $i=-1;
 7587:     my $started;
 7588: 
 7589:     my $nav_error;
 7590:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
 7591:     if ($nav_error) {
 7592:         $r->print(&navmap_errormsg());
 7593:         return '';
 7594:     }
 7595: 
 7596:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 7597:     # the user and return.
 7598: 
 7599:     if ($ssi_error) {
 7600: 	$r->print("</form>");
 7601: 	&ssi_print_error($r);
 7602:         &Apache::lonnet::remove_lock($lock);
 7603: 	return '';		# Dunno why the other returns return '' rather than just returning.
 7604:     }
 7605: 
 7606:     my %lettdig = &letter_to_digits();
 7607:     my $numletts = scalar(keys(%lettdig));
 7608: 
 7609:     while ($i<$scanlines->{'count'}) {
 7610:  	($uname,$udom)=('','');
 7611:  	$i++;
 7612:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7613:  	if ($line=~/^[\s\cz]*$/) { next; }
 7614: 	if ($started) {
 7615: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 7616: 						     'last student');
 7617: 	}
 7618: 	$started=1;
 7619:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7620:  						 $scan_data);
 7621:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 7622:  					      \%idmap,$i)) {
 7623:   	    &scantron_add_delay(\@delayqueue,$line,
 7624:  				'Unable to find a student that matches',1);
 7625:  	    next;
 7626:   	}
 7627:  	if (exists $completedstudents{$uname}) {
 7628:  	    &scantron_add_delay(\@delayqueue,$line,
 7629:  				'Student '.$uname.' has multiple sheets',2);
 7630:  	    next;
 7631:  	}
 7632:   	($uname,$udom)=split(/:/,$uname);
 7633: 
 7634:         my (%partids_by_symb,$res_error);
 7635:         foreach my $resource (@resources) {
 7636:             my $ressymb;
 7637:             if (ref($resource)) {
 7638:                 $ressymb = $resource->symb();
 7639:             } else {
 7640:                 $res_error = 1;
 7641:                 last;
 7642:             }
 7643:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 7644:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 7645:                 my ($analysis,$parts) =
 7646:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
 7647:                 $partids_by_symb{$ressymb} = $parts;
 7648:             } else {
 7649:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 7650:             }
 7651:         }
 7652: 
 7653:         if ($res_error) {
 7654:             &scantron_add_delay(\@delayqueue,$line,
 7655:                                 'An error occurred while grading student '.$uname,2);
 7656:             next;
 7657:         }
 7658: 
 7659: 	&Apache::lonxml::clear_problem_counter();
 7660:   	&Apache::lonnet::appenv($scan_record);
 7661: 
 7662: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 7663: 	    &scantron_putfile($scanlines,$scan_data);
 7664: 	}
 7665: 	
 7666:         my $scancode;
 7667:         if ((exists($scan_record->{'scantron.CODE'})) &&
 7668:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 7669:             $scancode = $scan_record->{'scantron.CODE'};
 7670:         } else {
 7671:             $scancode = '';
 7672:         }
 7673: 
 7674:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7675:                                    \@resources,\%partids_by_symb) eq 'ssi_error') {
 7676:             $ssi_error = 0; # So end of handler error message does not trigger.
 7677:             $r->print("</form>");
 7678:             &ssi_print_error($r);
 7679:             &Apache::lonnet::remove_lock($lock);
 7680:             return '';      # Why return ''?  Beats me.
 7681:         }
 7682: 
 7683: 	$completedstudents{$uname}={'line'=>$line};
 7684:         if ($env{'form.verifyrecord'}) {
 7685:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 7686:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 7687:             chomp($studentdata);
 7688:             $studentdata =~ s/\r$//;
 7689:             my $studentrecord = '';
 7690:             my $counter = -1;
 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:                 &Apache::lonxml::clear_problem_counter();
 7701:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7702:                                            \@resources,\%partids_by_symb) eq 'ssi_error') {
 7703:                     $ssi_error = 0; # So end of handler error message does not trigger.
 7704:                     $r->print("</form>");
 7705:                     &ssi_print_error($r);
 7706:                     &Apache::lonnet::remove_lock($lock);
 7707:                     delete($completedstudents{$uname});
 7708:                     return '';
 7709:                 }
 7710:                 $counter = -1;
 7711:                 $studentrecord = '';
 7712:                 foreach my $resource (@resources) {
 7713:                     my $ressymb = $resource->symb();
 7714:                     ($counter,my $recording) =
 7715:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7716:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 7717:                                                  \%scantron_config,\%lettdig,$numletts);
 7718:                     $studentrecord .= $recording;
 7719:                 }
 7720:                 if ($studentrecord ne $studentdata) {
 7721:                     $r->print('<p><span class="LC_error">');
 7722:                     if ($scancode eq '') {
 7723:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
 7724:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 7725:                     } else {
 7726:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
 7727:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 7728:                     }
 7729:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 7730:                               &Apache::loncommon::start_data_table_header_row()."\n".
 7731:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 7732:                               &Apache::loncommon::end_data_table_header_row()."\n".
 7733:                               &Apache::loncommon::start_data_table_row().
 7734:                               '<td>'.&mt('Bubble Sheet').'</td>'.
 7735:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
 7736:                               &Apache::loncommon::end_data_table_row().
 7737:                               &Apache::loncommon::start_data_table_row().
 7738:                               '<td>Stored submissions</td>'.
 7739:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
 7740:                               &Apache::loncommon::end_data_table_row().
 7741:                               &Apache::loncommon::end_data_table().'</p>');
 7742:                 } else {
 7743:                     $r->print('<br /><span class="LC_warning">'.
 7744:                              &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 />'.
 7745:                              &mt("As a consequence, this user's submission history records two tries.").
 7746:                                  '</span><br />');
 7747:                 }
 7748:             }
 7749:         }
 7750:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 7751:     } continue {
 7752: 	&Apache::lonxml::clear_problem_counter();
 7753: 	&Apache::lonnet::delenv('scantron.');
 7754:     }
 7755:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 7756:     &Apache::lonnet::remove_lock($lock);
 7757: #    my $lasttime = &Time::HiRes::time()-$start;
 7758: #    $r->print("<p>took $lasttime</p>");
 7759: 
 7760:     $r->print("</form>");
 7761:     return '';
 7762: }
 7763: 
 7764: sub graders_resources_pass {
 7765:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
 7766:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 7767:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 7768:         foreach my $resource (@{$resources}) {
 7769:             my $ressymb = $resource->symb();
 7770:             my ($analysis,$parts) =
 7771:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 7772:                                           $env{'user.name'},$env{'user.domain'},1);
 7773:             $grader_partids_by_symb->{$ressymb} = $parts;
 7774:             if (ref($analysis) eq 'HASH') {
 7775:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7776:                     $grader_randomlists_by_symb->{$ressymb} =
 7777:                         $analysis->{'parts_withrandomlist'};
 7778:                 }
 7779:             }
 7780:         }
 7781:     }
 7782:     return;
 7783: }
 7784: 
 7785: sub grade_student_bubbles {
 7786:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
 7787:     if (ref($resources) eq 'ARRAY') {
 7788:         my $count = 0;
 7789:         foreach my $resource (@{$resources}) {
 7790:             my $ressymb = $resource->symb();
 7791:             my %form = ('submitted'      => 'scantron',
 7792:                         'grade_target'   => 'grade',
 7793:                         'grade_username' => $uname,
 7794:                         'grade_domain'   => $udom,
 7795:                         'grade_courseid' => $env{'request.course.id'},
 7796:                         'grade_symb'     => $ressymb,
 7797:                         'CODE'           => $scancode
 7798:                        );
 7799:             if (ref($parts) eq 'HASH') {
 7800:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 7801:                     foreach my $part (@{$parts->{$ressymb}}) {
 7802:                         $form{'scantron_questnum_start.'.$part} =
 7803:                             1+$env{'form.scantron.first_bubble_line.'.$count};
 7804:                         $count++;
 7805:                     }
 7806:                 }
 7807:             }
 7808:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 7809:             return 'ssi_error' if ($ssi_error);
 7810:             last if (&Apache::loncommon::connection_aborted($r));
 7811:         }
 7812:     }
 7813:     return;
 7814: }
 7815: 
 7816: sub scantron_upload_scantron_data {
 7817:     my ($r,$symb)=@_;
 7818:     my $dom = $env{'request.role.domain'};
 7819:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 7820:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 7821:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 7822: 							  'domainid',
 7823: 							  'coursename',$dom);
 7824:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 7825:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
 7826:     my $default_form_data=&defaultFormData($symb);
 7827:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 7828:     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.");
 7829:     $r->print(&Apache::lonhtmlcommon::scripttag('
 7830:     function checkUpload(formname) {
 7831: 	if (formname.upfile.value == "") {
 7832: 	    alert("'.$nofile_alert.'");
 7833: 	    return false;
 7834: 	}
 7835:         if (formname.courseid.value == "") {
 7836:             alert("'.$nocourseid_alert.'");
 7837:             return false;
 7838:         }
 7839: 	formname.submit();
 7840:     }
 7841: 
 7842:     function ToSyllabus() {
 7843:         var cdom = '."'$dom'".';
 7844:         var cnum = document.rules.courseid.value;
 7845:         if (cdom == "" || cdom == null) {
 7846:             return;
 7847:         }
 7848:         if (cnum == "" || cnum == null) {
 7849:            return;
 7850:         }
 7851:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 7852:                             "height=350,width=350,scrollbars=yes,menubar=no");
 7853:         return;
 7854:     }
 7855: 
 7856: '));
 7857:     $r->print('
 7858: <h3>'.&mt('Send scanned bubblesheet data to a course').'</h3>
 7859: 
 7860: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 7861: '.$default_form_data.
 7862:   &Apache::lonhtmlcommon::start_pick_box().
 7863:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 7864:   '<input name="courseid" type="text" size="30" />'.$select_link.
 7865:   &Apache::lonhtmlcommon::row_closure().
 7866:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 7867:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 7868:   &Apache::lonhtmlcommon::row_closure().
 7869:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 7870:   '<input name="domainid" type="hidden" />'.$domdesc.
 7871:   &Apache::lonhtmlcommon::row_closure().
 7872:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 7873:   '<input type="file" name="upfile" size="50" />'.
 7874:   &Apache::lonhtmlcommon::row_closure(1).
 7875:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 7876: 
 7877: <input name="command" value="scantronupload_save" type="hidden" />
 7878: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 7879: </form>
 7880: ');
 7881:     return '';
 7882: }
 7883: 
 7884: 
 7885: sub scantron_upload_scantron_data_save {
 7886:     my($r,$symb)=@_;
 7887:     my $doanotherupload=
 7888: 	'<br /><form action="/adm/grades" method="post">'."\n".
 7889: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 7890: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 7891: 	'</form>'."\n";
 7892:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 7893: 	!&Apache::lonnet::allowed('usc',
 7894: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 7895: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 7896: 	unless ($symb) {
 7897: 	    $r->print($doanotherupload);
 7898: 	}
 7899: 	return '';
 7900:     }
 7901:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 7902:     my $uploadedfile;
 7903:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
 7904:     if (length($env{'form.upfile'}) < 2) {
 7905:         $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>'));
 7906:     } else {
 7907:         my $result = 
 7908:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
 7909:                                             $env{'form.courseid'},$env{'form.domainid'});
 7910: 	if ($result =~ m{^/uploaded/}) {
 7911: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
 7912:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
 7913: 			  '<span class="LC_filename">'.$result.'</span>'));
 7914:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 7915:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 7916:                                                        $env{'form.courseid'},$uploadedfile));
 7917: 	} else {
 7918: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
 7919:                           '<span class="LC_error">','</span>',$result,
 7920: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 7921: 	}
 7922:     }
 7923:     if ($symb) {
 7924: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
 7925:     } else {
 7926: 	$r->print($doanotherupload);
 7927:     }
 7928:     return '';
 7929: }
 7930: 
 7931: sub validate_uploaded_scantron_file {
 7932:     my ($cdom,$cname,$fname) = @_;
 7933:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 7934:     my @lines;
 7935:     if ($scanlines ne '-1') {
 7936:         @lines=split("\n",$scanlines,-1);
 7937:     }
 7938:     my $output;
 7939:     if (@lines) {
 7940:         my (%counts,$max_match_format);
 7941:         my ($max_match_count,$max_match_pct) = (0,0);
 7942:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 7943:         my %idmap = &username_to_idmap($classlist);
 7944:         foreach my $key (keys(%idmap)) {
 7945:             my $lckey = lc($key);
 7946:             $idmap{$lckey} = $idmap{$key};
 7947:         }
 7948:         my %unique_formats;
 7949:         my @formatlines = &get_scantronformat_file();
 7950:         foreach my $line (@formatlines) {
 7951:             chomp($line);
 7952:             my @config = split(/:/,$line);
 7953:             my $idstart = $config[5];
 7954:             my $idlength = $config[6];
 7955:             if (($idstart ne '') && ($idlength > 0)) {
 7956:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 7957:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 7958:                 } else {
 7959:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 7960:                 }
 7961:             }
 7962:         }
 7963:         foreach my $key (keys(%unique_formats)) {
 7964:             my ($idstart,$idlength) = split(':',$key);
 7965:             %{$counts{$key}} = (
 7966:                                'found'   => 0,
 7967:                                'total'   => 0,
 7968:                               );
 7969:             foreach my $line (@lines) {
 7970:                 next if ($line =~ /^#/);
 7971:                 next if ($line =~ /^[\s\cz]*$/);
 7972:                 my $id = substr($line,$idstart-1,$idlength);
 7973:                 $id = lc($id);
 7974:                 if (exists($idmap{$id})) {
 7975:                     $counts{$key}{'found'} ++;
 7976:                 }
 7977:                 $counts{$key}{'total'} ++;
 7978:             }
 7979:             if ($counts{$key}{'total'}) {
 7980:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 7981:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 7982:                     $max_match_pct = $percent_match;
 7983:                     $max_match_format = $key;
 7984:                     $max_match_count = $counts{$key}{'total'};
 7985:                 }
 7986:             }
 7987:         }
 7988:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 7989:             my $format_descs;
 7990:             my $numwithformat = @{$unique_formats{$max_match_format}};
 7991:             for (my $i=0; $i<$numwithformat; $i++) {
 7992:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 7993:                 if ($i<$numwithformat-2) {
 7994:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 7995:                 } elsif ($i==$numwithformat-2) {
 7996:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 7997:                 } elsif ($i==$numwithformat-1) {
 7998:                     $format_descs .= '"<i>'.$desc.'</i>"';
 7999:                 }
 8000:             }
 8001:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 8002:             $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).
 8003:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
 8004:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
 8005:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
 8006:                                   '<i>'.$cdom.'</i>').'</li>'.
 8007:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 8008:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
 8009:                        '</ul>';
 8010:         }
 8011:     } else {
 8012:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
 8013:     }
 8014:     return $output;
 8015: }
 8016: 
 8017: sub valid_file {
 8018:     my ($requested_file)=@_;
 8019:     foreach my $filename (sort(&scantron_filenames())) {
 8020: 	if ($requested_file eq $filename) { return 1; }
 8021:     }
 8022:     return 0;
 8023: }
 8024: 
 8025: sub scantron_download_scantron_data {
 8026:     my ($r,$symb)=@_;
 8027:     my $default_form_data=&defaultFormData($symb);
 8028:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8029:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8030:     my $file=$env{'form.scantron_selectfile'};
 8031:     if (! &valid_file($file)) {
 8032: 	$r->print('
 8033: 	<p>
 8034: 	    '.&mt('The requested file name was invalid.').'
 8035:         </p>
 8036: ');
 8037: 	return;
 8038:     }
 8039:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 8040:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 8041:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 8042:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 8043:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 8044:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 8045:     $r->print('
 8046:     <p>
 8047: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
 8048: 	      '<a href="'.$orig.'">','</a>').'
 8049:     </p>
 8050:     <p>
 8051: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 8052: 	      '<a href="'.$corrected.'">','</a>').'
 8053:     </p>
 8054:     <p>
 8055: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 8056: 	      '<a href="'.$skipped.'">','</a>').'
 8057:     </p>
 8058: ');
 8059:     return '';
 8060: }
 8061: 
 8062: sub checkscantron_results {
 8063:     my ($r,$symb) = @_;
 8064:     if (!$symb) {return '';}
 8065:     my $cid = $env{'request.course.id'};
 8066:     my %lettdig = &letter_to_digits();
 8067:     my $numletts = scalar(keys(%lettdig));
 8068:     my $cnum = $env{'course.'.$cid.'.num'};
 8069:     my $cdom = $env{'course.'.$cid.'.domain'};
 8070:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8071:     my %record;
 8072:     my %scantron_config =
 8073:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 8074:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 8075:     my $classlist=&Apache::loncoursedata::get_classlist();
 8076:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 8077:     my $navmap=Apache::lonnavmaps::navmap->new();
 8078:     unless (ref($navmap)) {
 8079:         $r->print(&navmap_errormsg());
 8080:         return '';
 8081:     }
 8082:     my $map=$navmap->getResourceByUrl($sequence);
 8083:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8084:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 8085:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
 8086: 
 8087:     my ($uname,$udom);
 8088:     my (%scandata,%lastname,%bylast);
 8089:     $r->print('
 8090: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 8091: 
 8092:     my @delayqueue;
 8093:     my %completedstudents;
 8094: 
 8095:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
 8096:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
 8097:                                     'Progress of Bubblesheet Data/Submission Records Comparison',$count,
 8098:                                     'inline',undef,'checkscantron');
 8099:     my ($username,$domain,$started);
 8100:     my $nav_error;
 8101:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
 8102:     if ($nav_error) {
 8103:         $r->print(&navmap_errormsg());
 8104:         return '';
 8105:     }
 8106: 
 8107:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 8108:                                           'Processing first student');
 8109:     my $start=&Time::HiRes::time();
 8110:     my $i=-1;
 8111: 
 8112:     while ($i<$scanlines->{'count'}) {
 8113:         ($username,$domain,$uname)=('','','');
 8114:         $i++;
 8115:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 8116:         if ($line=~/^[\s\cz]*$/) { next; }
 8117:         if ($started) {
 8118:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 8119:                                                      'last student');
 8120:         }
 8121:         $started=1;
 8122:         my $scan_record=
 8123:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 8124:                                                      $scan_data);
 8125:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
 8126:                                                               \%idmap,$i)) {
 8127:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8128:                                 'Unable to find a student that matches',1);
 8129:             next;
 8130:         }
 8131:         if (exists $completedstudents{$uname}) {
 8132:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8133:                                 'Student '.$uname.' has multiple sheets',2);
 8134:             next;
 8135:         }
 8136:         my $pid = $scan_record->{'scantron.ID'};
 8137:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 8138:         push(@{$bylast{$lastname{$pid}}},$pid);
 8139:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8140:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8141:         chomp($scandata{$pid});
 8142:         $scandata{$pid} =~ s/\r$//;
 8143:         ($username,$domain)=split(/:/,$uname);
 8144:         my $counter = -1;
 8145:         foreach my $resource (@resources) {
 8146:             my $parts;
 8147:             my $ressymb = $resource->symb();
 8148:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8149:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8150:                 (my $analysis,$parts) =
 8151:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
 8152:             } else {
 8153:                 $parts = $grader_partids_by_symb{$ressymb};
 8154:             }
 8155:             ($counter,my $recording) =
 8156:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 8157:                                          $scandata{$pid},$parts,
 8158:                                          \%scantron_config,\%lettdig,$numletts);
 8159:             $record{$pid} .= $recording;
 8160:         }
 8161:     }
 8162:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8163:     $r->print('<br />');
 8164:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 8165:     $passed = 0;
 8166:     $failed = 0;
 8167:     $numstudents = 0;
 8168:     foreach my $last (sort(keys(%bylast))) {
 8169:         if (ref($bylast{$last}) eq 'ARRAY') {
 8170:             foreach my $pid (sort(@{$bylast{$last}})) {
 8171:                 my $showscandata = $scandata{$pid};
 8172:                 my $showrecord = $record{$pid};
 8173:                 $showscandata =~ s/\s/&nbsp;/g;
 8174:                 $showrecord =~ s/\s/&nbsp;/g;
 8175:                 if ($scandata{$pid} eq $record{$pid}) {
 8176:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 8177:                     $okstudents .= '<tr class="'.$css_class.'">'.
 8178: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 8179: '</tr>'."\n".
 8180: '<tr class="'.$css_class.'">'."\n".
 8181: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
 8182:                     $passed ++;
 8183:                 } else {
 8184:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 8185:                     $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".
 8186: '</tr>'."\n".
 8187: '<tr class="'.$css_class.'">'."\n".
 8188: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 8189: '</tr>'."\n";
 8190:                     $failed ++;
 8191:                 }
 8192:                 $numstudents ++;
 8193:             }
 8194:         }
 8195:     }
 8196:     $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>');
 8197:     $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>');
 8198:     if ($passed) {
 8199:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 8200:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8201:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8202:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8203:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8204:                  $okstudents."\n".
 8205:                  &Apache::loncommon::end_data_table().'<br />');
 8206:     }
 8207:     if ($failed) {
 8208:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 8209:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8210:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8211:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8212:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8213:                  $badstudents."\n".
 8214:                  &Apache::loncommon::end_data_table()).'<br />'.
 8215:                  &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.');  
 8216:     }
 8217:     $r->print('</form><br />');
 8218:     return;
 8219: }
 8220: 
 8221: sub verify_scantron_grading {
 8222:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 8223:         $scantron_config,$lettdig,$numletts) = @_;
 8224:     my ($record,%expected,%startpos);
 8225:     return ($counter,$record) if (!ref($resource));
 8226:     return ($counter,$record) if (!$resource->is_problem());
 8227:     my $symb = $resource->symb();
 8228:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 8229:     foreach my $part_id (@{$partids}) {
 8230:         $counter ++;
 8231:         $expected{$part_id} = 0;
 8232:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
 8233:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
 8234:             foreach my $item (@sub_lines) {
 8235:                 $expected{$part_id} += $item;
 8236:             }
 8237:         } else {
 8238:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
 8239:         }
 8240:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 8241:     }
 8242:     if ($symb) {
 8243:         my %recorded;
 8244:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 8245:         if ($returnhash{'version'}) {
 8246:             my %lasthash=();
 8247:             my $version;
 8248:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 8249:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 8250:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 8251:                 }
 8252:             }
 8253:             foreach my $key (keys(%lasthash)) {
 8254:                 if ($key =~ /\.scantron$/) {
 8255:                     my $value = &unescape($lasthash{$key});
 8256:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 8257:                     if ($value eq '') {
 8258:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 8259:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 8260:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8261:                             }
 8262:                         }
 8263:                     } else {
 8264:                         my @tocheck;
 8265:                         my @items = split(//,$value);
 8266:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 8267:                             ($scantron_config->{'Qon'} eq 'number')) {
 8268:                             if (@items < $expected{$part_id}) {
 8269:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 8270:                                 my @singles = split(//,$fragment);
 8271:                                 foreach my $pos (@singles) {
 8272:                                     if ($pos eq ' ') {
 8273:                                         push(@tocheck,$pos);
 8274:                                     } else {
 8275:                                         my $next = shift(@items);
 8276:                                         push(@tocheck,$next);
 8277:                                     }
 8278:                                 }
 8279:                             } else {
 8280:                                 @tocheck = @items;
 8281:                             }
 8282:                             foreach my $letter (@tocheck) {
 8283:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 8284:                                     if ($letter !~ /^[A-J]$/) {
 8285:                                         $letter = $scantron_config->{'Qoff'};
 8286:                                     }
 8287:                                     $recorded{$part_id} .= $letter;
 8288:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 8289:                                     my $digit;
 8290:                                     if ($letter !~ /^[A-J]$/) {
 8291:                                         $digit = $scantron_config->{'Qoff'};
 8292:                                     } else {
 8293:                                         $digit = $lettdig->{$letter};
 8294:                                     }
 8295:                                     $recorded{$part_id} .= $digit;
 8296:                                 }
 8297:                             }
 8298:                         } else {
 8299:                             @tocheck = @items;
 8300:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 8301:                                 my $curr_sub = shift(@tocheck);
 8302:                                 my $digit;
 8303:                                 if ($curr_sub =~ /^[A-J]$/) {
 8304:                                     $digit = $lettdig->{$curr_sub}-1;
 8305:                                 }
 8306:                                 if ($curr_sub eq 'J') {
 8307:                                     $digit += scalar($numletts);
 8308:                                 }
 8309:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8310:                                     if ($j == $digit) {
 8311:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 8312:                                     } else {
 8313:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8314:                                     }
 8315:                                 }
 8316:                             }
 8317:                         }
 8318:                     }
 8319:                 }
 8320:             }
 8321:         }
 8322:         foreach my $part_id (@{$partids}) {
 8323:             if ($recorded{$part_id} eq '') {
 8324:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 8325:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8326:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8327:                     }
 8328:                 }
 8329:             }
 8330:             $record .= $recorded{$part_id};
 8331:         }
 8332:     }
 8333:     return ($counter,$record);
 8334: }
 8335: 
 8336: sub letter_to_digits { 
 8337:     my %lettdig = (
 8338:                     A => 1,
 8339:                     B => 2,
 8340:                     C => 3,
 8341:                     D => 4,
 8342:                     E => 5,
 8343:                     F => 6,
 8344:                     G => 7,
 8345:                     H => 8,
 8346:                     I => 9,
 8347:                     J => 0,
 8348:                   );
 8349:     return %lettdig;
 8350: }
 8351: 
 8352: 
 8353: #-------- end of section for handling grading scantron forms -------
 8354: #
 8355: #-------------------------------------------------------------------
 8356: 
 8357: #-------------------------- Menu interface -------------------------
 8358: #
 8359: #--- Href with symb and command ---
 8360: 
 8361: sub href_symb_cmd {
 8362:     my ($symb,$cmd)=@_;
 8363:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&command='.$cmd;
 8364: }
 8365: 
 8366: sub grading_menu {
 8367:     my ($request,$symb) = @_;
 8368:     if (!$symb) {return '';}
 8369: 
 8370:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 8371:                   'command'=>'individual');
 8372:     
 8373:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8374: 
 8375:     $fields{'command'}='ungraded';
 8376:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8377: 
 8378:     $fields{'command'}='table';
 8379:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8380: 
 8381:     $fields{'command'}='all_for_one';
 8382:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8383: 
 8384:     $fields{'command'}='downloadfilesselect';
 8385:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8386: 
 8387:     $fields{'command'} = 'csvform';
 8388:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8389:     
 8390:     $fields{'command'} = 'processclicker';
 8391:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8392:     
 8393:     $fields{'command'} = 'scantron_selectphase';
 8394:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8395: 
 8396:     $fields{'command'} = 'initialverifyreceipt';
 8397:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8398:     
 8399:     my @menu = ({	categorytitle=>'Hand Grading',
 8400:             items =>[
 8401:                         {	linktext => 'Select individual students to grade',
 8402:                     		url => $url1a,
 8403:                     		permission => 'F',
 8404:                     		icon => 'edit-find-replace.png',
 8405:                     		linktitle => 'Grade current resource for a selection of students.'
 8406:                         }, 
 8407:                         {       linktext => 'Grade ungraded submissions.',
 8408:                                 url => $url1b,
 8409:                                 permission => 'F',
 8410:                                 icon => 'edit-find-replace.png',
 8411:                                 linktitle => 'Grade all submissions that have not been graded yet.'
 8412:                         },
 8413: 
 8414:                         {       linktext => 'Grading table',
 8415:                                 url => $url1c,
 8416:                                 permission => 'F',
 8417:                                 icon => 'edit-find-replace.png',
 8418:                                 linktitle => 'Grade current resource for all students.'
 8419:                         },
 8420:                         {       linktext => 'Grade page/folder for one student',
 8421:                                 url => $url1d,
 8422:                                 permission => 'F',
 8423:                                 icon => 'edit-find-replace.png',
 8424:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
 8425:                         },
 8426:                         {       linktext => 'Download submissions',
 8427:                                 url => $url1e,
 8428:                                 permission => 'F',
 8429:                                 icon => 'edit-find-replace.png',
 8430:                                 linktitle => 'Download all students submissions.'
 8431:                         }]},
 8432:                          { categorytitle=>'Automated Grading',
 8433:                items =>[
 8434: 
 8435:                 	    {	linktext => 'Upload Scores',
 8436:                     		url => $url2,
 8437:                     		permission => 'F',
 8438:                     		icon => 'uploadscores.png',
 8439:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 8440:                 	    },
 8441:                 	    {	linktext => 'Process Clicker',
 8442:                     		url => $url3,
 8443:                     		permission => 'F',
 8444:                     		icon => 'addClickerInfoFile.png',
 8445:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 8446:                 	    },
 8447:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
 8448:                     		url => $url4,
 8449:                     		permission => 'F',
 8450:                     		icon => 'stat.png',
 8451:                     		linktitle => 'Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.'
 8452:                 	    },
 8453:                             {   linktext => 'Verify Receipt Number',
 8454:                                 url => $url5,
 8455:                                 permission => 'F',
 8456:                                 icon => 'edit-find-replace.png',
 8457:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
 8458:                             }
 8459: 
 8460:                     ]
 8461:             });
 8462: 
 8463:     # Create the menu
 8464:     my $Str;
 8465:     $Str .= '<form method="post" action="" name="gradingMenu">';
 8466:     $Str .= '<input type="hidden" name="command" value="" />'.
 8467:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8468: 
 8469:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
 8470:     return $Str;    
 8471: }
 8472: 
 8473: 
 8474: sub ungraded {
 8475:     my ($request)=@_;
 8476:     &submit_options($request);
 8477: }
 8478: 
 8479: sub submit_options_sequence {
 8480:     my ($request,$symb) = @_;
 8481:     if (!$symb) {return '';}
 8482:     &commonJSfunctions($request);
 8483:     my $result;
 8484: 
 8485:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8486:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8487:     $result.=&selectfield(0).
 8488:             '<input type="hidden" name="command" value="pickStudentPage" />
 8489:             <div>
 8490:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 8491:             </div>
 8492:         </div>
 8493:   </form>';
 8494:     return $result;
 8495: }
 8496: 
 8497: sub submit_options_table {
 8498:     my ($request,$symb) = @_;
 8499:     if (!$symb) {return '';}
 8500:     &commonJSfunctions($request);
 8501:     my $result;
 8502: 
 8503:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8504:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8505: 
 8506:     $result.=&selectfield(0).
 8507:             '<input type="hidden" name="command" value="viewgrades" />
 8508:             <div>
 8509:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 8510:             </div>
 8511:         </div>
 8512:   </form>';
 8513:     return $result;
 8514: }
 8515: 
 8516: sub submit_options_download {
 8517:     my ($request,$symb) = @_;
 8518:     if (!$symb) {return '';}
 8519: 
 8520:     &commonJSfunctions($request);
 8521: 
 8522:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8523:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8524:     $result.='
 8525: <h2>
 8526:   '.&mt('Select Students for Which to Download Submissions').'
 8527: </h2>'.&selectfield(1).'
 8528:                 <input type="hidden" name="command" value="downloadfileslink" /> 
 8529:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 8530:             </div>
 8531:           </div>
 8532: 
 8533: 
 8534:   </form>';
 8535:     return $result;
 8536: }
 8537: 
 8538: #--- Displays the submissions first page -------
 8539: sub submit_options {
 8540:     my ($request,$symb) = @_;
 8541:     if (!$symb) {return '';}
 8542: 
 8543:     &commonJSfunctions($request);
 8544:     my $result;
 8545: 
 8546:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8547: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8548:     $result.=&selectfield(1).'
 8549:                 <input type="hidden" name="command" value="submission" /> 
 8550: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
 8551:             </div>
 8552:           </div>
 8553: 
 8554: 
 8555:   </form>';
 8556:     return $result;
 8557: }
 8558: 
 8559: sub selectfield {
 8560:    my ($full)=@_;
 8561:    my $result='<div class="LC_columnSection">
 8562:   
 8563:     <fieldset>
 8564:       <legend>
 8565:        '.&mt('Sections').'
 8566:       </legend>
 8567:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
 8568:     </fieldset>
 8569:   
 8570:     <fieldset>
 8571:       <legend>
 8572:         '.&mt('Groups').'
 8573:       </legend>
 8574:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 8575:     </fieldset>
 8576:   
 8577:     <fieldset>
 8578:       <legend>
 8579:         '.&mt('Access Status').'
 8580:       </legend>
 8581:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
 8582:     </fieldset>';
 8583:     if ($full) {
 8584:        $result.='
 8585:     <fieldset>
 8586:       <legend>
 8587:         '.&mt('Submission Status').'
 8588:       </legend>'.
 8589:        &Apache::loncommon::select_form('all','submitonly',
 8590:           (&Apache::lonlocal::texthash(
 8591:              'yes'       => 'with submissions',
 8592:              'queued'    => 'in grading queue',
 8593:              'graded'    => 'with ungraded submissions',
 8594:              'incorrect' => 'with incorrect submissions',
 8595:              'all'       => 'with any status'),
 8596:              'select_form_order' => ['yes','queued','graded','incorrect','all'])).
 8597:    '</fieldset>';
 8598:     }
 8599:     $result.='</div><br />';
 8600:     return $result;
 8601: }
 8602: 
 8603: sub reset_perm {
 8604:     undef(%perm);
 8605: }
 8606: 
 8607: sub init_perm {
 8608:     &reset_perm();
 8609:     foreach my $test_perm ('vgr','mgr','opa') {
 8610: 
 8611: 	my $scope = $env{'request.course.id'};
 8612: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 8613: 
 8614: 	    $scope .= '/'.$env{'request.course.sec'};
 8615: 	    if ( $perm{$test_perm}=
 8616: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 8617: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 8618: 	    } else {
 8619: 		delete($perm{$test_perm});
 8620: 	    }
 8621: 	}
 8622:     }
 8623: }
 8624: 
 8625: sub gather_clicker_ids {
 8626:     my %clicker_ids;
 8627: 
 8628:     my $classlist = &Apache::loncoursedata::get_classlist();
 8629: 
 8630:     # Set up a couple variables.
 8631:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 8632:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 8633:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 8634: 
 8635:     foreach my $student (keys(%$classlist)) {
 8636:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 8637:         my $username = $classlist->{$student}->[$username_idx];
 8638:         my $domain   = $classlist->{$student}->[$domain_idx];
 8639:         my $clickers =
 8640: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 8641:         foreach my $id (split(/\,/,$clickers)) {
 8642:             $id=~s/^[\#0]+//;
 8643:             $id=~s/[\-\:]//g;
 8644:             if (exists($clicker_ids{$id})) {
 8645: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 8646:             } else {
 8647: 		$clicker_ids{$id}=$username.':'.$domain;
 8648:             }
 8649:         }
 8650:     }
 8651:     return %clicker_ids;
 8652: }
 8653: 
 8654: sub gather_adv_clicker_ids {
 8655:     my %clicker_ids;
 8656:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 8657:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8658:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 8659:     foreach my $element (sort(keys(%coursepersonnel))) {
 8660:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 8661:             my ($puname,$pudom)=split(/\:/,$person);
 8662:             my $clickers =
 8663: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 8664:             foreach my $id (split(/\,/,$clickers)) {
 8665: 		$id=~s/^[\#0]+//;
 8666:                 $id=~s/[\-\:]//g;
 8667: 		if (exists($clicker_ids{$id})) {
 8668: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 8669: 		} else {
 8670: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 8671: 		}
 8672:             }
 8673:         }
 8674:     }
 8675:     return %clicker_ids;
 8676: }
 8677: 
 8678: sub clicker_grading_parameters {
 8679:     return ('gradingmechanism' => 'scalar',
 8680:             'upfiletype' => 'scalar',
 8681:             'specificid' => 'scalar',
 8682:             'pcorrect' => 'scalar',
 8683:             'pincorrect' => 'scalar');
 8684: }
 8685: 
 8686: sub process_clicker {
 8687:     my ($r,$symb)=@_;
 8688:     if (!$symb) {return '';}
 8689:     my $result=&checkforfile_js();
 8690:     $result.=&Apache::loncommon::start_data_table().
 8691:              &Apache::loncommon::start_data_table_header_row().
 8692:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
 8693:              &Apache::loncommon::end_data_table_header_row().
 8694:              &Apache::loncommon::start_data_table_row()."<td>\n";
 8695: # Attempt to restore parameters from last session, set defaults if not present
 8696:     my %Saveable_Parameters=&clicker_grading_parameters();
 8697:     &Apache::loncommon::restore_course_settings('grades_clicker',
 8698:                                                  \%Saveable_Parameters);
 8699:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 8700:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 8701:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 8702:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 8703: 
 8704:     my %checked;
 8705:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 8706:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 8707:           $checked{$gradingmechanism}=' checked="checked"';
 8708:        }
 8709:     }
 8710: 
 8711:     my $upload=&mt("Evaluate File");
 8712:     my $type=&mt("Type");
 8713:     my $attendance=&mt("Award points just for participation");
 8714:     my $personnel=&mt("Correctness determined from response by course personnel");
 8715:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 8716:     my $given=&mt("Correctness determined from given list of answers").' '.
 8717:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 8718:     my $pcorrect=&mt("Percentage points for correct solution");
 8719:     my $pincorrect=&mt("Percentage points for incorrect solution");
 8720:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 8721: 						   ('iclicker' => 'i>clicker',
 8722:                                                     'interwrite' => 'interwrite PRS'));
 8723:     $symb = &Apache::lonenc::check_encrypt($symb);
 8724:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
 8725: function sanitycheck() {
 8726: // Accept only integer percentages
 8727:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 8728:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 8729: // Find out grading choice
 8730:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8731:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 8732:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 8733:       }
 8734:    }
 8735: // By default, new choice equals user selection
 8736:    newgradingchoice=gradingchoice;
 8737: // Not good to give more points for false answers than correct ones
 8738:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 8739:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 8740:    }
 8741: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 8742:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 8743:       document.forms.gradesupload.pcorrect.value=100;
 8744:       document.forms.gradesupload.pincorrect.value=100;
 8745:    }
 8746: // If the values are different, cannot be attendance only
 8747:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 8748:        (gradingchoice=='attendance')) {
 8749:        newgradingchoice='personnel';
 8750:    }
 8751: // Change grading choice to new one
 8752:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8753:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 8754:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 8755:       } else {
 8756:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 8757:       }
 8758:    }
 8759: // Remember the old state
 8760:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 8761: }
 8762: ENDUPFORM
 8763:     $result.= <<ENDUPFORM;
 8764: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 8765: <input type="hidden" name="symb" value="$symb" />
 8766: <input type="hidden" name="command" value="processclickerfile" />
 8767: <input type="file" name="upfile" size="50" />
 8768: <br /><label>$type: $selectform</label>
 8769: ENDUPFORM
 8770:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
 8771:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
 8772:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
 8773: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
 8774: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
 8775: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 8776: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
 8777: <br />&nbsp;&nbsp;&nbsp;
 8778: <input type="text" name="givenanswer" size="50" />
 8779: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 8780: ENDGRADINGFORM
 8781:          $result.='</td>'.&Apache::loncommon::end_data_table_row().
 8782:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
 8783:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
 8784: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
 8785: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 8786: </form>'
 8787: ENDPERCFORM
 8788:     $result.='</td>'.
 8789:              &Apache::loncommon::end_data_table_row().
 8790:              &Apache::loncommon::end_data_table();
 8791:     return $result;
 8792: }
 8793: 
 8794: sub process_clicker_file {
 8795:     my ($r,$symb)=@_;
 8796:     if (!$symb) {return '';}
 8797: 
 8798:     my %Saveable_Parameters=&clicker_grading_parameters();
 8799:     &Apache::loncommon::store_course_settings('grades_clicker',
 8800:                                               \%Saveable_Parameters);
 8801:     my $result='';
 8802:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 8803: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 8804: 	return $result;
 8805:     }
 8806:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 8807:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 8808:         return $result;
 8809:     }
 8810:     my $foundgiven=0;
 8811:     if ($env{'form.gradingmechanism'} eq 'given') {
 8812:         $env{'form.givenanswer'}=~s/^\s*//gs;
 8813:         $env{'form.givenanswer'}=~s/\s*$//gs;
 8814:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
 8815:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 8816:         my @answers=split(/\,/,$env{'form.givenanswer'});
 8817:         $foundgiven=$#answers+1;
 8818:     }
 8819:     my %clicker_ids=&gather_clicker_ids();
 8820:     my %correct_ids;
 8821:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 8822: 	%correct_ids=&gather_adv_clicker_ids();
 8823:     }
 8824:     if ($env{'form.gradingmechanism'} eq 'specific') {
 8825: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 8826: 	   $correct_id=~tr/a-z/A-Z/;
 8827: 	   $correct_id=~s/\s//gs;
 8828: 	   $correct_id=~s/^[\#0]+//;
 8829:            $correct_id=~s/[\-\:]//g;
 8830:            if ($correct_id) {
 8831: 	      $correct_ids{$correct_id}='specified';
 8832:            }
 8833:         }
 8834:     }
 8835:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 8836: 	$result.=&mt('Score based on attendance only');
 8837:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
 8838:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
 8839:     } else {
 8840: 	my $number=0;
 8841: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 8842: 	foreach my $id (sort(keys(%correct_ids))) {
 8843: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 8844: 	    if ($correct_ids{$id} eq 'specified') {
 8845: 		$result.=&mt('specified');
 8846: 	    } else {
 8847: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 8848: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 8849: 	    }
 8850: 	    $number++;
 8851: 	}
 8852:         $result.="</p>\n";
 8853: 	if ($number==0) {
 8854: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
 8855: 	    return $result;
 8856: 	}
 8857:     }
 8858:     if (length($env{'form.upfile'}) < 2) {
 8859:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
 8860: 		     '<span class="LC_error">',
 8861: 		     '</span>',
 8862: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
 8863:         return $result;
 8864:     }
 8865: 
 8866: # Were able to get all the info needed, now analyze the file
 8867: 
 8868:     $result.=&Apache::loncommon::studentbrowser_javascript();
 8869:     $symb = &Apache::lonenc::check_encrypt($symb);
 8870:     $result.=&Apache::loncommon::start_data_table().
 8871:              &Apache::loncommon::start_data_table_header_row().
 8872:              '<th>'.&mt('Evaluate clicker file').'</th>'.
 8873:              &Apache::loncommon::end_data_table_header_row().
 8874:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
 8875: <td>
 8876: <form method="post" action="/adm/grades" name="clickeranalysis">
 8877: <input type="hidden" name="symb" value="$symb" />
 8878: <input type="hidden" name="command" value="assignclickergrades" />
 8879: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 8880: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 8881: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 8882: ENDHEADER
 8883:     if ($env{'form.gradingmechanism'} eq 'given') {
 8884:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
 8885:     } 
 8886:     my %responses;
 8887:     my @questiontitles;
 8888:     my $errormsg='';
 8889:     my $number=0;
 8890:     if ($env{'form.upfiletype'} eq 'iclicker') {
 8891: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 8892:     }
 8893:     if ($env{'form.upfiletype'} eq 'interwrite') {
 8894:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 8895:     }
 8896:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 8897:              '<input type="hidden" name="number" value="'.$number.'" />'.
 8898:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 8899:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 8900:              '<br />';
 8901:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
 8902:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
 8903:        return $result;
 8904:     } 
 8905: # Remember Question Titles
 8906: # FIXME: Possibly need delimiter other than ":"
 8907:     for (my $i=0;$i<$number;$i++) {
 8908:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 8909:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 8910:     }
 8911:     my $correct_count=0;
 8912:     my $student_count=0;
 8913:     my $unknown_count=0;
 8914: # Match answers with usernames
 8915: # FIXME: Possibly need delimiter other than ":"
 8916:     foreach my $id (keys(%responses)) {
 8917:        if ($correct_ids{$id}) {
 8918:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 8919:           $correct_count++;
 8920:        } elsif ($clicker_ids{$id}) {
 8921:           if ($clicker_ids{$id}=~/\,/) {
 8922: # More than one user with the same clicker!
 8923:              $result.="</td>".&Apache::loncommon::end_data_table_row().
 8924:                            &Apache::loncommon::start_data_table_row()."<td>".
 8925:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 8926:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 8927:                            "<select name='multi".$id."'>";
 8928:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 8929:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 8930:              }
 8931:              $result.='</select>';
 8932:              $unknown_count++;
 8933:           } else {
 8934: # Good: found one and only one user with the right clicker
 8935:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 8936:              $student_count++;
 8937:           }
 8938:        } else {
 8939:           $result.="</td>".&Apache::loncommon::end_data_table_row().
 8940:                            &Apache::loncommon::start_data_table_row()."<td>".
 8941:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 8942:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 8943:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 8944:                    "\n".&mt("Domain").": ".
 8945:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 8946:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
 8947:           $unknown_count++;
 8948:        }
 8949:     }
 8950:     $result.='<hr />'.
 8951:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 8952:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
 8953:        if ($correct_count==0) {
 8954:           $errormsg.="Found no correct answers answers for grading!";
 8955:        } elsif ($correct_count>1) {
 8956:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 8957:        }
 8958:     }
 8959:     if ($number<1) {
 8960:        $errormsg.="Found no questions.";
 8961:     }
 8962:     if ($errormsg) {
 8963:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 8964:     } else {
 8965:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 8966:     }
 8967:     $result.='</form></td>'.
 8968:              &Apache::loncommon::end_data_table_row().
 8969:              &Apache::loncommon::end_data_table();
 8970:     return $result;
 8971: }
 8972: 
 8973: sub iclicker_eval {
 8974:     my ($questiontitles,$responses)=@_;
 8975:     my $number=0;
 8976:     my $errormsg='';
 8977:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 8978:         my %components=&Apache::loncommon::record_sep($line);
 8979:         my @entries=map {$components{$_}} (sort(keys(%components)));
 8980: 	if ($entries[0] eq 'Question') {
 8981: 	    for (my $i=3;$i<$#entries;$i+=6) {
 8982: 		$$questiontitles[$number]=$entries[$i];
 8983: 		$number++;
 8984: 	    }
 8985: 	}
 8986: 	if ($entries[0]=~/^\#/) {
 8987: 	    my $id=$entries[0];
 8988: 	    my @idresponses;
 8989: 	    $id=~s/^[\#0]+//;
 8990: 	    for (my $i=0;$i<$number;$i++) {
 8991: 		my $idx=3+$i*6;
 8992: 		push(@idresponses,$entries[$idx]);
 8993: 	    }
 8994: 	    $$responses{$id}=join(',',@idresponses);
 8995: 	}
 8996:     }
 8997:     return ($errormsg,$number);
 8998: }
 8999: 
 9000: sub interwrite_eval {
 9001:     my ($questiontitles,$responses)=@_;
 9002:     my $number=0;
 9003:     my $errormsg='';
 9004:     my $skipline=1;
 9005:     my $questionnumber=0;
 9006:     my %idresponses=();
 9007:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9008:         my %components=&Apache::loncommon::record_sep($line);
 9009:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9010:         if ($entries[1] eq 'Time') { $skipline=0; next; }
 9011:         if ($entries[1] eq 'Response') { $skipline=1; }
 9012:         next if $skipline;
 9013:         if ($entries[0]!=$questionnumber) {
 9014:            $questionnumber=$entries[0];
 9015:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
 9016:            $number++;
 9017:         }
 9018:         my $id=$entries[4];
 9019:         $id=~s/^[\#0]+//;
 9020:         $id=~s/^v\d*\://i;
 9021:         $id=~s/[\-\:]//g;
 9022:         $idresponses{$id}[$number]=$entries[6];
 9023:     }
 9024:     foreach my $id (keys(%idresponses)) {
 9025:        $$responses{$id}=join(',',@{$idresponses{$id}});
 9026:        $$responses{$id}=~s/^\s*\,//;
 9027:     }
 9028:     return ($errormsg,$number);
 9029: }
 9030: 
 9031: sub assign_clicker_grades {
 9032:     my ($r,$symb)=@_;
 9033:     if (!$symb) {return '';}
 9034: # See which part we are saving to
 9035:     my $res_error;
 9036:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 9037:     if ($res_error) {
 9038:         return &navmap_errormsg();
 9039:     }
 9040: # FIXME: This should probably look for the first handgradeable part
 9041:     my $part=$$partlist[0];
 9042: # Start screen output
 9043:     my $result=&Apache::loncommon::start_data_table().
 9044:              &Apache::loncommon::start_data_table_header_row().
 9045:              '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
 9046:              &Apache::loncommon::end_data_table_header_row().
 9047:              &Apache::loncommon::start_data_table_row().'<td>';
 9048: # Get correct result
 9049: # FIXME: Possibly need delimiter other than ":"
 9050:     my @correct=();
 9051:     my $gradingmechanism=$env{'form.gradingmechanism'};
 9052:     my $number=$env{'form.number'};
 9053:     if ($gradingmechanism ne 'attendance') {
 9054:        foreach my $key (keys(%env)) {
 9055:           if ($key=~/^form\.correct\:/) {
 9056:              my @input=split(/\,/,$env{$key});
 9057:              for (my $i=0;$i<=$#input;$i++) {
 9058:                  if (($correct[$i]) && ($input[$i]) &&
 9059:                      ($correct[$i] ne $input[$i])) {
 9060:                     $result.='<br /><span class="LC_warning">'.
 9061:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
 9062:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
 9063:                  } elsif ($input[$i]) {
 9064:                     $correct[$i]=$input[$i];
 9065:                  }
 9066:              }
 9067:           }
 9068:        }
 9069:        for (my $i=0;$i<$number;$i++) {
 9070:           if (!$correct[$i]) {
 9071:              $result.='<br /><span class="LC_error">'.
 9072:                       &mt('No correct result given for question "[_1]"!',
 9073:                           $env{'form.question:'.$i}).'</span>';
 9074:           }
 9075:        }
 9076:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
 9077:     }
 9078: # Start grading
 9079:     my $pcorrect=$env{'form.pcorrect'};
 9080:     my $pincorrect=$env{'form.pincorrect'};
 9081:     my $storecount=0;
 9082:     my %users=();
 9083:     foreach my $key (keys(%env)) {
 9084:        my $user='';
 9085:        if ($key=~/^form\.student\:(.*)$/) {
 9086:           $user=$1;
 9087:        }
 9088:        if ($key=~/^form\.unknown\:(.*)$/) {
 9089:           my $id=$1;
 9090:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
 9091:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
 9092:           } elsif ($env{'form.multi'.$id}) {
 9093:              $user=$env{'form.multi'.$id};
 9094:           }
 9095:        }
 9096:        if ($user) {
 9097:           if ($users{$user}) {
 9098:              $result.='<br /><span class="LC_warning">'.
 9099:                       &mt("More than one entry found for <tt>[_1]</tt>!",$user).
 9100:                       '</span><br />';
 9101:           }
 9102:           $users{$user}=1; 
 9103:           my @answer=split(/\,/,$env{$key});
 9104:           my $sum=0;
 9105:           my $realnumber=$number;
 9106:           for (my $i=0;$i<$number;$i++) {
 9107:              if  ($correct[$i] eq '-') {
 9108:                 $realnumber--;
 9109:              } elsif ($answer[$i]) {
 9110:                 if ($gradingmechanism eq 'attendance') {
 9111:                    $sum+=$pcorrect;
 9112:                 } elsif ($correct[$i] eq '*') {
 9113:                    $sum+=$pcorrect;
 9114:                 } else {
 9115:                    if ($answer[$i] eq $correct[$i]) {
 9116:                       $sum+=$pcorrect;
 9117:                    } else {
 9118:                       $sum+=$pincorrect;
 9119:                    }
 9120:                 }
 9121:              }
 9122:           }
 9123:           my $ave=$sum/(100*$realnumber);
 9124: # Store
 9125:           my ($username,$domain)=split(/\:/,$user);
 9126:           my %grades=();
 9127:           $grades{"resource.$part.solved"}='correct_by_override';
 9128:           $grades{"resource.$part.awarded"}=$ave;
 9129:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 9130:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
 9131:                                                  $env{'request.course.id'},
 9132:                                                  $domain,$username);
 9133:           if ($returncode ne 'ok') {
 9134:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
 9135:           } else {
 9136:              $storecount++;
 9137:           }
 9138:        }
 9139:     }
 9140: # We are done
 9141:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
 9142:              '</td>'.
 9143:              &Apache::loncommon::end_data_table_row().
 9144:              &Apache::loncommon::end_data_table();
 9145:     return $result;
 9146: }
 9147: 
 9148: sub navmap_errormsg {
 9149:     return '<div class="LC_error">'.
 9150:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
 9151:            &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>').
 9152:            '</div>';
 9153: }
 9154: 
 9155: sub startpage {
 9156:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag) = @_;
 9157:     unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
 9158:     $r->print(&Apache::loncommon::start_page('Grading',undef,
 9159:                                           {'bread_crumbs' => $crumbs}));
 9160:     $r->print('<h3>'.$$crumbs[-1]{'text'}.'</h3>');
 9161:     unless ($nodisplayflag) {
 9162:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag));
 9163:     }
 9164: }
 9165: 
 9166: sub select_problem {
 9167:     my ($r)=@_;
 9168:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
 9169:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1));
 9170:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
 9171:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
 9172: }
 9173: 
 9174: sub handler {
 9175:     my $request=$_[0];
 9176:     &reset_caches();
 9177:     if ($env{'browser.mathml'}) {
 9178: 	&Apache::loncommon::content_type($request,'text/xml');
 9179:     } else {
 9180: 	&Apache::loncommon::content_type($request,'text/html');
 9181:     }
 9182:     $request->send_http_header;
 9183:     return '' if $request->header_only;
 9184:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
 9185: 
 9186: # see what command we need to execute
 9187: 
 9188:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
 9189:     my $command=$commands[0];
 9190: 
 9191:     if ($#commands > 0) {
 9192: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
 9193:     }
 9194: 
 9195: # see what the symb is
 9196: 
 9197:     my $symb=$env{'form.symb'};
 9198:     unless ($symb) {
 9199:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
 9200:        $symb=&Apache::lonnet::symbread($url);
 9201:     }
 9202:     &Apache::lonenc::check_decrypt(\$symb);                             
 9203: 
 9204:     $ssi_error = 0;
 9205:     if ($symb eq '' || $command eq '') {
 9206: #
 9207: # Not called from a resource
 9208: #    
 9209:         &startpage($request,undef,[],1,1);
 9210:         &select_problem($request);
 9211:     } else {
 9212: 	&init_perm();
 9213: 	if ($command eq 'submission' && $perm{'vgr'}) {
 9214:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}]);
 9215: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
 9216: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
 9217:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
 9218:                                        {href=>'',text=>'Select student'}],1,1);
 9219: 	    &pickStudentPage($request,$symb);
 9220: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
 9221:             &startpage($request,$symb,
 9222:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
 9223:                                        {href=>'',text=>'Select student'},
 9224:                                        {href=>'',text=>'Grade student'}],1,1);
 9225: 	    &displayPage($request,$symb);
 9226: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
 9227:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
 9228:                                        {href=>'',text=>'Select student'},
 9229:                                        {href=>'',text=>'Grade student'},
 9230:                                        {href=>'',text=>'Store grades'}],1,1);
 9231: 	    &updateGradeByPage($request,$symb);
 9232: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
 9233:             &startpage($request,$symb,[{href=>'',text=>'...'},
 9234:                                        {href=>'',text=>'Modify grades'}]);
 9235: 	    &processGroup($request,$symb);
 9236: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
 9237:             &startpage($request,$symb);
 9238: 	    $request->print(&grading_menu($request,$symb));
 9239: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
 9240:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
 9241: 	    $request->print(&submit_options($request,$symb));
 9242:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
 9243:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
 9244:             $request->print(&listStudents($request,$symb,'graded'));
 9245:         } elsif ($command eq 'table' && $perm{'vgr'}) {
 9246:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
 9247:             $request->print(&submit_options_table($request,$symb));
 9248:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
 9249:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
 9250:             $request->print(&submit_options_sequence($request,$symb));
 9251: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
 9252:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
 9253: 	    $request->print(&viewgrades($request,$symb));
 9254: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
 9255:             &startpage($request,$symb,[{href=>'',text=>'...'},
 9256:                                        {href=>'',text=>'Store grades'}]);
 9257: 	    $request->print(&processHandGrade($request,$symb));
 9258: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
 9259:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
 9260:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
 9261:                                                                              text=>"Modify grades"},
 9262:                                        {href=>'', text=>"Store grades"}]);
 9263: 	    $request->print(&editgrades($request,$symb));
 9264:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
 9265:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
 9266:             $request->print(&initialverifyreceipt($request,$symb));
 9267: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
 9268:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
 9269:                                        {href=>'',text=>'Verification Result'}]);
 9270: 	    $request->print(&verifyreceipt($request,$symb));
 9271:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
 9272:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
 9273:             $request->print(&process_clicker($request,$symb));
 9274:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
 9275:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
 9276:                                        {href=>'', text=>'Process clicker file'}]);
 9277:             $request->print(&process_clicker_file($request,$symb));
 9278:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
 9279:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
 9280:                                        {href=>'', text=>'Process clicker file'},
 9281:                                        {href=>'', text=>'Store grades'}]);
 9282:             $request->print(&assign_clicker_grades($request,$symb));
 9283: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
 9284:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
 9285: 	    $request->print(&upcsvScores_form($request,$symb));
 9286: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
 9287:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
 9288: 	    $request->print(&csvupload($request,$symb));
 9289: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
 9290:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
 9291: 	    $request->print(&csvuploadmap($request,$symb));
 9292: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
 9293: 	    if ($env{'form.associate'} ne 'Reverse Association') {
 9294:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
 9295: 		$request->print(&csvuploadoptions($request,$symb));
 9296: 	    } else {
 9297: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
 9298: 		    $env{'form.upfile_associate'} = 'reverse';
 9299: 		} else {
 9300: 		    $env{'form.upfile_associate'} = 'forward';
 9301: 		}
 9302:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
 9303: 		$request->print(&csvuploadmap($request,$symb));
 9304: 	    }
 9305: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
 9306:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
 9307: 	    $request->print(&csvuploadassign($request,$symb));
 9308: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
 9309:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9310: 	    $request->print(&scantron_selectphase($request,undef,$symb));
 9311:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
 9312:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9313:  	    $request->print(&scantron_do_warning($request,$symb));
 9314: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
 9315:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9316: 	    $request->print(&scantron_validate_file($request,$symb));
 9317: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
 9318:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9319: 	    $request->print(&scantron_process_students($request,$symb));
 9320:  	} elsif ($command eq 'scantronupload' && 
 9321:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9322: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9323:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9324:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
 9325:  	} elsif ($command eq 'scantronupload_save' &&
 9326:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9327: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9328:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9329:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
 9330:  	} elsif ($command eq 'scantron_download' &&
 9331: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 9332:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9333:  	    $request->print(&scantron_download_scantron_data($request,$symb));
 9334:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
 9335:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9336:             $request->print(&checkscantron_results($request,$symb));
 9337:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
 9338:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
 9339:             $request->print(&submit_options_download($request,$symb));
 9340:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
 9341:             &startpage($request,$symb,
 9342:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
 9343:     {href=>'', text=>'Download submissions'}]);
 9344:             &submit_download_link($request,$symb);
 9345: 	} elsif ($command) {
 9346:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
 9347: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
 9348: 	}
 9349:     }
 9350:     if ($ssi_error) {
 9351: 	&ssi_print_error($request);
 9352:     }
 9353:     $request->print(&Apache::loncommon::end_page());
 9354:     &reset_caches();
 9355:     return '';
 9356: }
 9357: 
 9358: 1;
 9359: 
 9360: __END__;
 9361: 
 9362: 
 9363: =head1 NAME
 9364: 
 9365: Apache::grades
 9366: 
 9367: =head1 SYNOPSIS
 9368: 
 9369: Handles the viewing of grades.
 9370: 
 9371: This is part of the LearningOnline Network with CAPA project
 9372: described at http://www.lon-capa.org.
 9373: 
 9374: =head1 OVERVIEW
 9375: 
 9376: Do an ssi with retries:
 9377: While I'd love to factor out this with the vesrion in lonprintout,
 9378: 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
 9379: I'm not quite ready to invent (e.g. an ssi_with_retry object).
 9380: 
 9381: At least the logic that drives this has been pulled out into loncommon.
 9382: 
 9383: 
 9384: 
 9385: ssi_with_retries - Does the server side include of a resource.
 9386:                      if the ssi call returns an error we'll retry it up to
 9387:                      the number of times requested by the caller.
 9388:                      If we still have a proble, no text is appended to the
 9389:                      output and we set some global variables.
 9390:                      to indicate to the caller an SSI error occurred.  
 9391:                      All of this is supposed to deal with the issues described
 9392:                      in LonCAPA BZ 5631 see:
 9393:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
 9394:                      by informing the user that this happened.
 9395: 
 9396: Parameters:
 9397:   resource   - The resource to include.  This is passed directly, without
 9398:                interpretation to lonnet::ssi.
 9399:   form       - The form hash parameters that guide the interpretation of the resource
 9400:                
 9401:   retries    - Number of retries allowed before giving up completely.
 9402: Returns:
 9403:   On success, returns the rendered resource identified by the resource parameter.
 9404: Side Effects:
 9405:   The following global variables can be set:
 9406:    ssi_error                - If an unrecoverable error occurred this becomes true.
 9407:                               It is up to the caller to initialize this to false
 9408:                               if desired.
 9409:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
 9410:                               of the resource that could not be rendered by the ssi
 9411:                               call.
 9412:    ssi_error_message   - The error string fetched from the ssi response
 9413:                               in the event of an error.
 9414: 
 9415: 
 9416: =head1 HANDLER SUBROUTINE
 9417: 
 9418: ssi_with_retries()
 9419: 
 9420: =head1 SUBROUTINES
 9421: 
 9422: =over
 9423: 
 9424: =item scantron_get_correction() : 
 9425: 
 9426:    Builds the interface screen to interact with the operator to fix a
 9427:    specific error condition in a specific scanline
 9428: 
 9429:  Arguments:
 9430:     $r           - Apache request object
 9431:     $i           - number of the current scanline
 9432:     $scan_record - hash ref as returned from &scantron_parse_scanline()
 9433:     $scan_config - hash ref as returned from &get_scantron_config()
 9434:     $line        - full contents of the current scanline
 9435:     $error       - error condition, valid values are
 9436:                    'incorrectCODE', 'duplicateCODE',
 9437:                    'doublebubble', 'missingbubble',
 9438:                    'duplicateID', 'incorrectID'
 9439:     $arg         - extra information needed
 9440:        For errors:
 9441:          - duplicateID   - paper number that this studentID was seen before on
 9442:          - duplicateCODE - array ref of the paper numbers this CODE was
 9443:                            seen on before
 9444:          - incorrectCODE - current incorrect CODE 
 9445:          - doublebubble  - array ref of the bubble lines that have double
 9446:                            bubble errors
 9447:          - missingbubble - array ref of the bubble lines that have missing
 9448:                            bubble errors
 9449: 
 9450: =item  scantron_get_maxbubble() : 
 9451: 
 9452:    Arguments:
 9453:        $nav_error  - Reference to scalar which is a flag to indicate a
 9454:                       failure to retrieve a navmap object.
 9455:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
 9456:        calling routine should trap the error condition and display the warning
 9457:        found in &navmap_errormsg().
 9458: 
 9459:    Returns the maximum number of bubble lines that are expected to
 9460:    occur. Does this by walking the selected sequence rendering the
 9461:    resource and then checking &Apache::lonxml::get_problem_counter()
 9462:    for what the current value of the problem counter is.
 9463: 
 9464:    Caches the results to $env{'form.scantron_maxbubble'},
 9465:    $env{'form.scantron.bubble_lines.n'}, 
 9466:    $env{'form.scantron.first_bubble_line.n'} and
 9467:    $env{"form.scantron.sub_bubblelines.n"}
 9468:    which are the total number of bubble, lines, the number of bubble
 9469:    lines for response n and number of the first bubble line for response n,
 9470:    and a comma separated list of numbers of bubble lines for sub-questions
 9471:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
 9472: 
 9473: 
 9474: =item  scantron_validate_missingbubbles() : 
 9475: 
 9476:    Validates all scanlines in the selected file to not have any
 9477:     answers that don't have bubbles that have not been verified
 9478:     to be bubble free.
 9479: 
 9480: =item  scantron_process_students() : 
 9481: 
 9482:    Routine that does the actual grading of the bubble sheet information.
 9483: 
 9484:    The parsed scanline hash is added to %env 
 9485: 
 9486:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
 9487:    foreach resource , with the form data of
 9488: 
 9489: 	'submitted'     =>'scantron' 
 9490: 	'grade_target'  =>'grade',
 9491: 	'grade_username'=> username of student
 9492: 	'grade_domain'  => domain of student
 9493: 	'grade_courseid'=> of course
 9494: 	'grade_symb'    => symb of resource to grade
 9495: 
 9496:     This triggers a grading pass. The problem grading code takes care
 9497:     of converting the bubbled letter information (now in %env) into a
 9498:     valid submission.
 9499: 
 9500: =item  scantron_upload_scantron_data() :
 9501: 
 9502:     Creates the screen for adding a new bubble sheet data file to a course.
 9503: 
 9504: =item  scantron_upload_scantron_data_save() : 
 9505: 
 9506:    Adds a provided bubble information data file to the course if user
 9507:    has the correct privileges to do so. 
 9508: 
 9509: =item  valid_file() :
 9510: 
 9511:    Validates that the requested bubble data file exists in the course.
 9512: 
 9513: =item  scantron_download_scantron_data() : 
 9514: 
 9515:    Shows a list of the three internal files (original, corrected,
 9516:    skipped) for a specific bubble sheet data file that exists in the
 9517:    course.
 9518: 
 9519: =item  scantron_validate_ID() : 
 9520: 
 9521:    Validates all scanlines in the selected file to not have any
 9522:    invalid or underspecified student/employee IDs
 9523: 
 9524: =item navmap_errormsg() :
 9525: 
 9526:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
 9527:    Should be called whenever the request to instantiate a navmap object fails.  
 9528: 
 9529: =back
 9530: 
 9531: =cut

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