File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.717: download - view: text, annotated - select for diffs
Thu Jan 30 19:11:05 2014 UTC (10 years, 3 months ago) by bisitz
Branches: MAIN
CVS tags: HEAD
- Internationalization - added missing &mt() calls
- Error style for error message

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.717 2014/01/30 19:11:05 bisitz Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: 
   30: 
   31: package Apache::grades;
   32: use strict;
   33: use Apache::style;
   34: use Apache::lonxml;
   35: use Apache::lonnet;
   36: use Apache::loncommon;
   37: use Apache::lonhtmlcommon;
   38: use Apache::lonnavmaps;
   39: use Apache::lonhomework;
   40: use Apache::lonpickcode;
   41: use Apache::loncoursedata;
   42: use Apache::lonmsg();
   43: use Apache::Constants qw(:common :http);
   44: use Apache::lonlocal;
   45: use Apache::lonenc;
   46: use Apache::lonstathelpers;
   47: use Apache::lonquickgrades;
   48: use Apache::bridgetask();
   49: use String::Similarity;
   50: use LONCAPA;
   51: 
   52: use POSIX qw(floor);
   53: 
   54: 
   55: 
   56: my %perm=();
   57: my %old_essays=();
   58: 
   59: #  These variables are used to recover from ssi errors
   60: 
   61: my $ssi_retries = 5;
   62: my $ssi_error;
   63: my $ssi_error_resource;
   64: my $ssi_error_message;
   65: 
   66: 
   67: sub ssi_with_retries {
   68:     my ($resource, $retries, %form) = @_;
   69:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
   70:     if ($response->is_error) {
   71: 	$ssi_error          = 1;
   72: 	$ssi_error_resource = $resource;
   73: 	$ssi_error_message  = $response->code . " " . $response->message;
   74:     }
   75: 
   76:     return $content;
   77: 
   78: }
   79: #
   80: #  Prodcuces an ssi retry failure error message to the user:
   81: #
   82: 
   83: sub ssi_print_error {
   84:     my ($r) = @_;
   85:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
   86:     $r->print('
   87: <br />
   88: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
   89: <p>
   90: '.&mt('Unable to retrieve a resource from a server:').'<br />
   91: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
   92: '.&mt('Error:').' '.$ssi_error_message.'
   93: </p>
   94: <p>'.
   95: &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 />'.
   96: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
   97: '</p>');
   98:     return;
   99: }
  100: 
  101: #
  102: # --- Retrieve the parts from the metadata file.---
  103: # Returns an array of everything that the resources stores away
  104: #
  105: 
  106: sub getpartlist {
  107:     my ($symb,$errorref) = @_;
  108: 
  109:     my $navmap   = Apache::lonnavmaps::navmap->new();
  110:     unless (ref($navmap)) {
  111:         if (ref($errorref)) { 
  112:             $$errorref = 'navmap';
  113:             return;
  114:         }
  115:     }
  116:     my $res      = $navmap->getBySymb($symb);
  117:     my $partlist = $res->parts();
  118:     my $url      = $res->src();
  119:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
  120: 
  121:     my @stores;
  122:     foreach my $part (@{ $partlist }) {
  123: 	foreach my $key (@metakeys) {
  124: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
  125: 	}
  126:     }
  127:     return @stores;
  128: }
  129: 
  130: #--- Format fullname, username:domain if different for display
  131: #--- Use anywhere where the student names are listed
  132: sub nameUserString {
  133:     my ($type,$fullname,$uname,$udom) = @_;
  134:     if ($type eq 'header') {
  135: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
  136:     } else {
  137: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
  138: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
  139:     }
  140: }
  141: 
  142: #--- Get the partlist and the response type for a given problem. ---
  143: #--- Indicate if a response type is coded handgraded or not. ---
  144: #--- Sets response_error pointer to "1" if navmaps object broken ---
  145: sub response_type {
  146:     my ($symb,$response_error) = @_;
  147: 
  148:     my $navmap = Apache::lonnavmaps::navmap->new();
  149:     unless (ref($navmap)) {
  150:         if (ref($response_error)) {
  151:             $$response_error = 1;
  152:         }
  153:         return;
  154:     }
  155:     my $res = $navmap->getBySymb($symb);
  156:     unless (ref($res)) {
  157:         $$response_error = 1;
  158:         return;
  159:     }
  160:     my $partlist = $res->parts();
  161:     my %vPart = 
  162: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
  163:     my (%response_types,%handgrade);
  164:     foreach my $part (@{ $partlist }) {
  165: 	next if (%vPart && !exists($vPart{$part}));
  166: 
  167: 	my @types = $res->responseType($part);
  168: 	my @ids = $res->responseIds($part);
  169: 	for (my $i=0; $i < scalar(@ids); $i++) {
  170: 	    $response_types{$part}{$ids[$i]} = $types[$i];
  171: 	    $handgrade{$part.'_'.$ids[$i]} = 
  172: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
  173: 				     '.handgrade',$symb);
  174: 	}
  175:     }
  176:     return ($partlist,\%handgrade,\%response_types);
  177: }
  178: 
  179: sub flatten_responseType {
  180:     my ($responseType) = @_;
  181:     my @part_response_id =
  182: 	map { 
  183: 	    my $part = $_;
  184: 	    map {
  185: 		[$part,$_]
  186: 		} sort(keys(%{ $responseType->{$part} }));
  187: 	} sort(keys(%$responseType));
  188:     return @part_response_id;
  189: }
  190: 
  191: sub get_display_part {
  192:     my ($partID,$symb)=@_;
  193:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
  194:     if (defined($display) and $display ne '') {
  195:         $display.= ' (<span class="LC_internal_info">'
  196:                   .&mt('Part ID: [_1]',$partID).'</span>)';
  197:     } else {
  198: 	$display=$partID;
  199:     }
  200:     return $display;
  201: }
  202: 
  203: sub reset_caches {
  204:     &reset_analyze_cache();
  205:     &reset_perm();
  206:     &reset_old_essays();
  207: }
  208: 
  209: {
  210:     my %analyze_cache;
  211:     my %analyze_cache_formkeys;
  212: 
  213:     sub reset_analyze_cache {
  214: 	undef(%analyze_cache);
  215:         undef(%analyze_cache_formkeys);
  216:     }
  217: 
  218:     sub get_analyze {
  219: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
  220: 	my $key = "$symb\0$uname\0$udom";
  221:         if ($type eq 'randomizetry') {
  222:             if ($trial ne '') {
  223:                 $key .= "\0".$trial;
  224:             }
  225:         }
  226: 	if (exists($analyze_cache{$key})) {
  227:             my $getupdate = 0;
  228:             if (ref($add_to_hash) eq 'HASH') {
  229:                 foreach my $item (keys(%{$add_to_hash})) {
  230:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
  231:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
  232:                             $getupdate = 1;
  233:                             last;
  234:                         }
  235:                     } else {
  236:                         $getupdate = 1;
  237:                     }
  238:                 }
  239:             }
  240:             if (!$getupdate) {
  241:                 return $analyze_cache{$key};
  242:             }
  243:         }
  244: 
  245: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  246: 	$url=&Apache::lonnet::clutter($url);
  247:         my %form = ('grade_target'      => 'analyze',
  248:                     'grade_domain'      => $udom,
  249:                     'grade_symb'        => $symb,
  250:                     'grade_courseid'    =>  $env{'request.course.id'},
  251:                     'grade_username'    => $uname,
  252:                     'grade_noincrement' => $no_increment);
  253:         if ($bubbles_per_row ne '') {
  254:             $form{'bubbles_per_row'} = $bubbles_per_row;
  255:         }
  256:         if ($type eq 'randomizetry') {
  257:             $form{'grade_questiontype'} = $type;
  258:             if ($rndseed ne '') {
  259:                 $form{'grade_rndseed'} = $rndseed;
  260:             }
  261:         }
  262:         if (ref($add_to_hash)) {
  263:             %form = (%form,%{$add_to_hash});
  264:         }
  265: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
  266: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  267: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  268:         if (ref($add_to_hash) eq 'HASH') {
  269:             $analyze_cache_formkeys{$key} = $add_to_hash;
  270:         } else {
  271:             $analyze_cache_formkeys{$key} = {};
  272:         }
  273: 	return $analyze_cache{$key} = \%analyze;
  274:     }
  275: 
  276:     sub get_order {
  277: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
  278: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
  279: 	return $analyze->{"$partid.$respid.shown"};
  280:     }
  281: 
  282:     sub get_radiobutton_correct_foil {
  283: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
  284: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
  285:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
  286:         if (ref($foils) eq 'ARRAY') {
  287: 	    foreach my $foil (@{$foils}) {
  288: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  289: 		    return $foil;
  290: 	        }
  291: 	    }
  292: 	}
  293:     }
  294: 
  295:     sub scantron_partids_tograde {
  296:         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row) = @_;
  297:         my (%analysis,@parts);
  298:         if (ref($resource)) {
  299:             my $symb = $resource->symb();
  300:             my $add_to_form;
  301:             if ($check_for_randomlist) {
  302:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
  303:             }
  304:             my $analyze = 
  305:                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
  306:                              undef,undef,undef,$bubbles_per_row);
  307:             if (ref($analyze) eq 'HASH') {
  308:                 %analysis = %{$analyze};
  309:             }
  310:             if (ref($analysis{'parts'}) eq 'ARRAY') {
  311:                 foreach my $part (@{$analysis{'parts'}}) {
  312:                     my ($id,$respid) = split(/\./,$part);
  313:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
  314:                         push(@parts,$part);
  315:                     }
  316:                 }
  317:             }
  318:         }
  319:         return (\%analysis,\@parts);
  320:     }
  321: 
  322: }
  323: 
  324: #--- Clean response type for display
  325: #--- Currently filters option/rank/radiobutton/match/essay/Task
  326: #        response types only.
  327: sub cleanRecord {
  328:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  329: 	$uname,$udom,$type,$trial,$rndseed) = @_;
  330:     my $grayFont = '<span class="LC_internal_info">';
  331:     if ($response =~ /^(option|rank)$/) {
  332: 	my %answer=&Apache::lonnet::str2hash($answer);
  333: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  334: 	my ($toprow,$bottomrow);
  335: 	foreach my $foil (@$order) {
  336: 	    if ($grading{$foil} == 1) {
  337: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  338: 	    } else {
  339: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</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('Option ID').'</span></td>'.
  346: 	    $bottomrow.'</tr></table></blockquote>';
  347:     } elsif ($response eq 'match') {
  348: 	my %answer=&Apache::lonnet::str2hash($answer);
  349: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  350: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  351: 	my ($toprow,$middlerow,$bottomrow);
  352: 	foreach my $foil (@$order) {
  353: 	    my $item=shift(@items);
  354: 	    if ($grading{$foil} == 1) {
  355: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  356: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  357: 	    } else {
  358: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  359: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  360: 	    }
  361: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  362: 	}
  363: 	return '<blockquote><table border="1">'.
  364: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  365: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  366: 	    $middlerow.'</tr>'.
  367: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  368: 	    $bottomrow.'</tr></table></blockquote>';
  369:     } elsif ($response eq 'radiobutton') {
  370: 	my %answer=&Apache::lonnet::str2hash($answer);
  371: 	my ($toprow,$bottomrow);
  372: 	my $correct = 
  373: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
  374: 	foreach my $foil (@$order) {
  375: 	    if (exists($answer{$foil})) {
  376: 		if ($foil eq $correct) {
  377: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  378: 		} else {
  379: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  380: 		}
  381: 	    } else {
  382: 		$toprow.='<td>'.&mt('false').'</td>';
  383: 	    }
  384: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  385: 	}
  386: 	return '<blockquote><table border="1">'.
  387: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  388: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  389: 	    $bottomrow.'</tr></table></blockquote>';
  390:     } elsif ($response eq 'essay') {
  391: 	if (! exists ($env{'form.'.$symb})) {
  392: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  393: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  394: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  395: 
  396: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  397: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  398: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  399: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  400: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  401: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  402: 	}
  403: 	$answer =~ s-\n-<br />-g;
  404: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  405:     } elsif ( $response eq 'organic') {
  406: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
  407: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  408: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  409: 	return $result;
  410:     } elsif ( $response eq 'Task') {
  411: 	if ( $answer eq 'SUBMITTED') {
  412: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  413: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  414: 	    return $result;
  415: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  416: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  417: 			       keys(%{$record}));
  418: 	    return join('<br />',($version,@matches));
  419: 			       
  420: 			       
  421: 	} else {
  422: 	    my $result =
  423: 		'<p>'
  424: 		.&mt('Overall result: [_1]',
  425: 		     $record->{$version."resource.$respid.$partid.status"})
  426: 		.'</p>';
  427: 	    
  428: 	    $result .= '<ul>';
  429: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  430: 			     keys(%{$record}));
  431: 	    foreach my $grade (sort(@grade)) {
  432: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  433: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  434: 				     $dim, $record->{$grade}).
  435: 			  '</li>';
  436: 	    }
  437: 	    $result.='</ul>';
  438: 	    return $result;
  439: 	}
  440:     } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
  441:         # Respect multiple input fields, see Bug #5409
  442: 	$answer = 
  443: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  444: 							      $answer);
  445:     }
  446:     return $answer;
  447: }
  448: 
  449: #-- A couple of common js functions
  450: sub commonJSfunctions {
  451:     my $request = shift;
  452:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
  453:     function radioSelection(radioButton) {
  454: 	var selection=null;
  455: 	if (radioButton.length > 1) {
  456: 	    for (var i=0; i<radioButton.length; i++) {
  457: 		if (radioButton[i].checked) {
  458: 		    return radioButton[i].value;
  459: 		}
  460: 	    }
  461: 	} else {
  462: 	    if (radioButton.checked) return radioButton.value;
  463: 	}
  464: 	return selection;
  465:     }
  466: 
  467:     function pullDownSelection(selectOne) {
  468: 	var selection="";
  469: 	if (selectOne.length > 1) {
  470: 	    for (var i=0; i<selectOne.length; i++) {
  471: 		if (selectOne[i].selected) {
  472: 		    return selectOne[i].value;
  473: 		}
  474: 	    }
  475: 	} else {
  476:             // only one value it must be the selected one
  477: 	    return selectOne.value;
  478: 	}
  479:     }
  480: COMMONJSFUNCTIONS
  481: }
  482: 
  483: #--- Dumps the class list with usernames,list of sections,
  484: #--- section, ids and fullnames for each user.
  485: sub getclasslist {
  486:     my ($getsec,$filterlist,$getgroup) = @_;
  487:     my @getsec;
  488:     my @getgroup;
  489:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  490:     if (!ref($getsec)) {
  491: 	if ($getsec ne '' && $getsec ne 'all') {
  492: 	    @getsec=($getsec);
  493: 	}
  494:     } else {
  495: 	@getsec=@{$getsec};
  496:     }
  497:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  498:     if (!ref($getgroup)) {
  499: 	if ($getgroup ne '' && $getgroup ne 'all') {
  500: 	    @getgroup=($getgroup);
  501: 	}
  502:     } else {
  503: 	@getgroup=@{$getgroup};
  504:     }
  505:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  506: 
  507:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  508:     # Bail out if we were unable to get the classlist
  509:     return if (! defined($classlist));
  510:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  511:     #
  512:     my %sections;
  513:     my %fullnames;
  514:     foreach my $student (keys(%$classlist)) {
  515:         my $end      = 
  516:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  517:         my $start    = 
  518:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  519:         my $id       = 
  520:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  521:         my $section  = 
  522:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  523:         my $fullname = 
  524:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  525:         my $status   = 
  526:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  527:         my $group   = 
  528:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  529: 	# filter students according to status selected
  530: 	if ($filterlist && (!($stu_status =~ /Any/))) {
  531: 	    if (!($stu_status =~ $status)) {
  532: 		delete($classlist->{$student});
  533: 		next;
  534: 	    }
  535: 	}
  536: 	# filter students according to groups selected
  537: 	my @stu_groups = split(/,/,$group);
  538: 	if (@getgroup) {
  539: 	    my $exclude = 1;
  540: 	    foreach my $grp (@getgroup) {
  541: 	        foreach my $stu_group (@stu_groups) {
  542: 	            if ($stu_group eq $grp) {
  543: 	                $exclude = 0;
  544:     	            } 
  545: 	        }
  546:     	        if (($grp eq 'none') && !$group) {
  547:         	        $exclude = 0;
  548:         	}
  549: 	    }
  550: 	    if ($exclude) {
  551: 	        delete($classlist->{$student});
  552: 	    }
  553: 	}
  554: 	$section = ($section ne '' ? $section : 'none');
  555: 	if (&canview($section)) {
  556: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  557: 		$sections{$section}++;
  558: 		if ($classlist->{$student}) {
  559: 		    $fullnames{$student}=$fullname;
  560: 		}
  561: 	    } else {
  562: 		delete($classlist->{$student});
  563: 	    }
  564: 	} else {
  565: 	    delete($classlist->{$student});
  566: 	}
  567:     }
  568:     my %seen = ();
  569:     my @sections = sort(keys(%sections));
  570:     return ($classlist,\@sections,\%fullnames);
  571: }
  572: 
  573: sub canmodify {
  574:     my ($sec)=@_;
  575:     if ($perm{'mgr'}) {
  576: 	if (!defined($perm{'mgr_section'})) {
  577: 	    # can modify whole class
  578: 	    return 1;
  579: 	} else {
  580: 	    if ($sec eq $perm{'mgr_section'}) {
  581: 		#can modify the requested section
  582: 		return 1;
  583: 	    } else {
  584: 		# can't modify the request section
  585: 		return 0;
  586: 	    }
  587: 	}
  588:     }
  589:     #can't modify
  590:     return 0;
  591: }
  592: 
  593: sub canview {
  594:     my ($sec)=@_;
  595:     if ($perm{'vgr'}) {
  596: 	if (!defined($perm{'vgr_section'})) {
  597: 	    # can modify whole class
  598: 	    return 1;
  599: 	} else {
  600: 	    if ($sec eq $perm{'vgr_section'}) {
  601: 		#can modify the requested section
  602: 		return 1;
  603: 	    } else {
  604: 		# can't modify the request section
  605: 		return 0;
  606: 	    }
  607: 	}
  608:     }
  609:     #can't modify
  610:     return 0;
  611: }
  612: 
  613: #--- Retrieve the grade status of a student for all the parts
  614: sub student_gradeStatus {
  615:     my ($symb,$udom,$uname,$partlist) = @_;
  616:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  617:     my %partstatus = ();
  618:     foreach (@$partlist) {
  619: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  620: 	$status              = 'nothing' if ($status eq '');
  621: 	$partstatus{$_}      = $status;
  622: 	my $subkey           = "resource.$_.submitted_by";
  623: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  624:     }
  625:     return %partstatus;
  626: }
  627: 
  628: # hidden form and javascript that calls the form
  629: # Use by verifyscript and viewgrades
  630: # Shows a student's view of problem and submission
  631: sub jscriptNform {
  632:     my ($symb) = @_;
  633:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  634:     my $jscript= &Apache::lonhtmlcommon::scripttag(
  635: 	'    function viewOneStudent(user,domain) {'."\n".
  636: 	'	document.onestudent.student.value = user;'."\n".
  637: 	'	document.onestudent.userdom.value = domain;'."\n".
  638: 	'	document.onestudent.submit();'."\n".
  639: 	'    }'."\n".
  640: 	"\n");
  641:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  642: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  643: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  644: 	'<input type="hidden" name="command" value="submission" />'."\n".
  645: 	'<input type="hidden" name="student" value="" />'."\n".
  646: 	'<input type="hidden" name="userdom" value="" />'."\n".
  647: 	'</form>'."\n";
  648:     return $jscript;
  649: }
  650: 
  651: 
  652: 
  653: # Given the score (as a number [0-1] and the weight) what is the final
  654: # point value? This function will round to the nearest tenth, third,
  655: # or quarter if one of those is within the tolerance of .00001.
  656: sub compute_points {
  657:     my ($score, $weight) = @_;
  658:     
  659:     my $tolerance = .00001;
  660:     my $points = $score * $weight;
  661: 
  662:     # Check for nearness to 1/x.
  663:     my $check_for_nearness = sub {
  664:         my ($factor) = @_;
  665:         my $num = ($points * $factor) + $tolerance;
  666:         my $floored_num = floor($num);
  667:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  668:             return $floored_num / $factor;
  669:         }
  670:         return $points;
  671:     };
  672: 
  673:     $points = $check_for_nearness->(10);
  674:     $points = $check_for_nearness->(3);
  675:     $points = $check_for_nearness->(4);
  676:     
  677:     return $points;
  678: }
  679: 
  680: #------------------ End of general use routines --------------------
  681: 
  682: #
  683: # Find most similar essay
  684: #
  685: 
  686: sub most_similar {
  687:     my ($uname,$udom,$symb,$uessay)=@_;
  688: 
  689:     unless ($symb) { return ''; }
  690: 
  691:     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
  692: 
  693: # ignore spaces and punctuation
  694: 
  695:     $uessay=~s/\W+/ /gs;
  696: 
  697: # ignore empty submissions (occuring when only files are sent)
  698: 
  699:     unless ($uessay=~/\w+/s) { return ''; }
  700: 
  701: # these will be returned. Do not care if not at least 50 percent similar
  702:     my $limit=0.6;
  703:     my $sname='';
  704:     my $sdom='';
  705:     my $scrsid='';
  706:     my $sessay='';
  707: # go through all essays ...
  708:     foreach my $tkey (keys(%{$old_essays{$symb}})) {
  709: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  710: # ... except the same student
  711:         next if (($tname eq $uname) && ($tdom eq $udom));
  712: 	my $tessay=$old_essays{$symb}{$tkey};
  713: 	$tessay=~s/\W+/ /gs;
  714: # String similarity gives up if not even limit
  715: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  716: # Found one
  717: 	if ($tsimilar>$limit) {
  718: 	    $limit=$tsimilar;
  719: 	    $sname=$tname;
  720: 	    $sdom=$tdom;
  721: 	    $scrsid=$tcrsid;
  722: 	    $sessay=$old_essays{$symb}{$tkey};
  723: 	}
  724:     }
  725:     if ($limit>0.6) {
  726:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  727:     } else {
  728:        return ('','','','',0);
  729:     }
  730: }
  731: 
  732: #-------------------------------------------------------------------
  733: 
  734: #------------------------------------ Receipt Verification Routines
  735: #
  736: 
  737: sub initialverifyreceipt {
  738:    my ($request,$symb) = @_;
  739:    &commonJSfunctions($request);
  740:    return '<form name="gradingMenu" action=""><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
  741:         &Apache::lonnet::recprefix($env{'request.course.id'}).
  742:         '-<input type="text" name="receipt" size="4" />'.
  743:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  744:         '<input type="hidden" name="command" value="verify" />'.
  745:         "</form>\n";
  746: }
  747: 
  748: #--- Check whether a receipt number is valid.---
  749: sub verifyreceipt {
  750:     my ($request,$symb)  = @_;
  751: 
  752:     my $courseid = $env{'request.course.id'};
  753:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  754: 	$env{'form.receipt'};
  755:     $receipt     =~ s/[^\-\d]//g;
  756: 
  757:     my $title.=
  758: 	'<h3><span class="LC_info">'.
  759: 	&mt('Verifying Receipt Number [_1]',$receipt).
  760: 	'</span></h3>'."\n";
  761: 
  762:     my ($string,$contents,$matches) = ('','',0);
  763:     my (undef,undef,$fullname) = &getclasslist('all','0');
  764:     
  765:     my $receiptparts=0;
  766:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  767: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  768:     my $parts=['0'];
  769:     if ($receiptparts) {
  770:         my $res_error; 
  771:         ($parts)=&response_type($symb,\$res_error);
  772:         if ($res_error) {
  773:             return &navmap_errormsg();
  774:         } 
  775:     }
  776:     
  777:     my $header = 
  778: 	&Apache::loncommon::start_data_table().
  779: 	&Apache::loncommon::start_data_table_header_row().
  780: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  781: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  782: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  783:     if ($receiptparts) {
  784: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  785:     }
  786:     $header.=
  787: 	&Apache::loncommon::end_data_table_header_row();
  788: 
  789:     foreach (sort 
  790: 	     {
  791: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  792: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  793: 		 }
  794: 		 return $a cmp $b;
  795: 	     } (keys(%$fullname))) {
  796: 	my ($uname,$udom)=split(/\:/);
  797: 	foreach my $part (@$parts) {
  798: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  799: 		$contents.=
  800: 		    &Apache::loncommon::start_data_table_row().
  801: 		    '<td>&nbsp;'."\n".
  802: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  803: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  804: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  805: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  806: 		if ($receiptparts) {
  807: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  808: 		}
  809: 		$contents.= 
  810: 		    &Apache::loncommon::end_data_table_row()."\n";
  811: 		
  812: 		$matches++;
  813: 	    }
  814: 	}
  815:     }
  816:     if ($matches == 0) {
  817:         $string = $title
  818:                  .'<p class="LC_warning">'
  819:                  .&mt('No match found for the above receipt number.')
  820:                  .'</p>';
  821:     } else {
  822: 	$string = &jscriptNform($symb).$title.
  823: 	    '<p>'.
  824: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
  825: 	    '</p>'.
  826: 	    $header.
  827: 	    $contents.
  828: 	    &Apache::loncommon::end_data_table()."\n";
  829:     }
  830:     return $string;
  831: }
  832: 
  833: #--- This is called by a number of programs.
  834: #--- Called from the Grading Menu - View/Grade an individual student
  835: #--- Also called directly when one clicks on the subm button 
  836: #    on the problem page.
  837: sub listStudents {
  838:     my ($request,$symb,$submitonly) = @_;
  839: 
  840:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  841:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  842:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  843:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  844:     unless ($submitonly) {
  845:        $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  846:     }
  847: 
  848:     my $result='';
  849:     my $res_error;
  850:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
  851: 
  852:     my %lt = &Apache::lonlocal::texthash (
  853: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
  854: 		'single'   => 'Please select the student before clicking on the Next button.',
  855: 	     );
  856:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
  857:     function checkSelect(checkBox) {
  858: 	var ctr=0;
  859: 	var sense="";
  860: 	if (checkBox.length > 1) {
  861: 	    for (var i=0; i<checkBox.length; i++) {
  862: 		if (checkBox[i].checked) {
  863: 		    ctr++;
  864: 		}
  865: 	    }
  866: 	    sense = '$lt{'multiple'}';
  867: 	} else {
  868: 	    if (checkBox.checked) {
  869: 		ctr = 1;
  870: 	    }
  871: 	    sense = '$lt{'single'}';
  872: 	}
  873: 	if (ctr == 0) {
  874: 	    alert(sense);
  875: 	    return false;
  876: 	}
  877: 	document.gradesub.submit();
  878:     }
  879: 
  880:     function reLoadList(formname) {
  881: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  882: 	formname.command.value = 'submission';
  883: 	formname.submit();
  884:     }
  885: LISTJAVASCRIPT
  886: 
  887:     &commonJSfunctions($request);
  888:     $request->print($result);
  889: 
  890:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  891: 	"\n";
  892: 	
  893:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
  894:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
  895:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
  896:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
  897:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
  898:                   .&Apache::lonhtmlcommon::row_closure();
  899:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
  900:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
  901:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
  902:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
  903:                   .&Apache::lonhtmlcommon::row_closure();
  904: 
  905:     my $submission_options;
  906:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  907:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  908:     $env{'form.Status'} = $saveStatus;
  909:     $submission_options.=
  910:         '<span class="LC_nobreak">'.
  911:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
  912:         &mt('last submission').' </label></span>'."\n".
  913:         '<span class="LC_nobreak">'.
  914:         '<label><input type="radio" name="lastSub" value="last" /> '.
  915:         &mt('last submission with details').' </label></span>'."\n".
  916:         '<span class="LC_nobreak">'.
  917:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
  918:         &mt('all submissions').'</label></span>'."\n".
  919:         '<span class="LC_nobreak">'.
  920:         '<label><input type="radio" name="lastSub" value="all" /> '.
  921:         &mt('all submissions with details').'</label></span>';
  922:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
  923:                   .$submission_options
  924:                   .&Apache::lonhtmlcommon::row_closure();
  925: 
  926:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
  927:                   .'<select name="increment">'
  928:                   .'<option value="1">'.&mt('Whole Points').'</option>'
  929:                   .'<option value=".5">'.&mt('Half Points').'</option>'
  930:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
  931:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
  932:                   .'</select>'
  933:                   .&Apache::lonhtmlcommon::row_closure();
  934: 
  935:     $gradeTable .= 
  936:         &build_section_inputs().
  937: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
  938: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  939: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
  940: 
  941:     if (exists($env{'form.Status'})) {
  942: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
  943:     } else {
  944:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
  945:                       .&Apache::lonhtmlcommon::StatusOptions(
  946:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
  947:                       .&Apache::lonhtmlcommon::row_closure();
  948:     }
  949: 
  950:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
  951:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
  952:                   .&Apache::lonhtmlcommon::row_closure(1)
  953:                   .&Apache::lonhtmlcommon::end_pick_box();
  954: 
  955:     $gradeTable .= '<p>'
  956:                   .&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"
  957:                   .'<input type="hidden" name="command" value="processGroup" />'
  958:                   .'</p>';
  959: 
  960: # checkall buttons
  961:     $gradeTable.=&check_script('gradesub', 'stuinfo');
  962:     $gradeTable.='<input type="button" '."\n".
  963:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
  964:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
  965:     $gradeTable.=&check_buttons();
  966:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
  967:     $gradeTable.= &Apache::loncommon::start_data_table().
  968: 	&Apache::loncommon::start_data_table_header_row();
  969:     my $loop = 0;
  970:     while ($loop < 2) {
  971: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
  972: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
  973: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
  974: 	    foreach my $part (sort(@$partlist)) {
  975: 		my $display_part=
  976: 		    &get_display_part((split(/_/,$part))[0],$symb);
  977: 		$gradeTable.=
  978: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
  979: 	    }
  980: 	} elsif ($submitonly eq 'queued') {
  981: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
  982: 	}
  983: 	$loop++;
  984: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
  985:     }
  986:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
  987: 
  988:     my $ctr = 0;
  989:     foreach my $student (sort 
  990: 			 {
  991: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  992: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  993: 			     }
  994: 			     return $a cmp $b;
  995: 			 }
  996: 			 (keys(%$fullname))) {
  997: 	my ($uname,$udom) = split(/:/,$student);
  998: 
  999: 	my %status = ();
 1000: 
 1001: 	if ($submitonly eq 'queued') {
 1002: 	    my %queue_status = 
 1003: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 1004: 							$udom,$uname);
 1005: 	    next if (!defined($queue_status{'gradingqueue'}));
 1006: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
 1007: 	}
 1008: 
 1009: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1010: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
 1011: 	    my $submitted = 0;
 1012: 	    my $graded = 0;
 1013: 	    my $incorrect = 0;
 1014: 	    foreach (keys(%status)) {
 1015: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1016: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1017: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1018: 		
 1019: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1020: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1021: 		    $submitted = 0;
 1022: 		    my ($part)=split(/\./,$partid);
 1023: 		    $gradeTable.='<input type="hidden" name="'.
 1024: 			$student.':'.$part.':submitted_by" value="'.
 1025: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1026: 		}
 1027: 	    }
 1028: 	    
 1029: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1030: 				     $submitonly eq 'incorrect' ||
 1031: 				     $submitonly eq 'graded'));
 1032: 	    next if (!$graded && ($submitonly eq 'graded'));
 1033: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1034: 	}
 1035: 
 1036: 	$ctr++;
 1037: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1038:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1039: 	if ( $perm{'vgr'} eq 'F' ) {
 1040: 	    if ($ctr%2 ==1) {
 1041: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1042: 	    }
 1043: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1044:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1045:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1046: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1047: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1048: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1049: 
 1050: 	    if ($submitonly ne 'all') {
 1051: 		foreach (sort(keys(%status))) {
 1052: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1053: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1054: 		}
 1055: 	    }
 1056: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1057: 	    if ($ctr%2 ==0) {
 1058: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1059: 	    }
 1060: 	}
 1061:     }
 1062:     if ($ctr%2 ==1) {
 1063: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1064: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1065: 		foreach (@$partlist) {
 1066: 		    $gradeTable.='<td>&nbsp;</td>';
 1067: 		}
 1068: 	    } elsif ($submitonly eq 'queued') {
 1069: 		$gradeTable.='<td>&nbsp;</td>';
 1070: 	    }
 1071: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1072:     }
 1073: 
 1074:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1075:         '<input type="button" '.
 1076:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
 1077:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1078:     if ($ctr == 0) {
 1079: 	my $num_students=(scalar(keys(%$fullname)));
 1080: 	if ($num_students eq 0) {
 1081: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1082: 	} else {
 1083: 	    my $submissions='submissions';
 1084: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1085: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1086: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1087: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1088: 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
 1089: 		    $num_students).
 1090: 		'</span><br />';
 1091: 	}
 1092:     } elsif ($ctr == 1) {
 1093: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1094:     }
 1095:     $request->print($gradeTable);
 1096:     return '';
 1097: }
 1098: 
 1099: #---- Called from the listStudents routine
 1100: 
 1101: sub check_script {
 1102:     my ($form, $type)=@_;
 1103:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
 1104:     function checkall() {
 1105:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1106:             ele = document.forms.'.$form.'.elements[i];
 1107:             if (ele.name == "'.$type.'") {
 1108:             document.forms.'.$form.'.elements[i].checked=true;
 1109:                                        }
 1110:         }
 1111:     }
 1112: 
 1113:     function checksec() {
 1114:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1115:             ele = document.forms.'.$form.'.elements[i];
 1116:            string = document.forms.'.$form.'.chksec.value;
 1117:            if
 1118:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1119:               document.forms.'.$form.'.elements[i].checked=true;
 1120:             }
 1121:         }
 1122:     }
 1123: 
 1124: 
 1125:     function uncheckall() {
 1126:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1127:             ele = document.forms.'.$form.'.elements[i];
 1128:             if (ele.name == "'.$type.'") {
 1129:             document.forms.'.$form.'.elements[i].checked=false;
 1130:                                        }
 1131:         }
 1132:     }
 1133: 
 1134: '."\n");
 1135:     return $chkallscript;
 1136: }
 1137: 
 1138: sub check_buttons {
 1139:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1140:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1141:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1142:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1143:     return $buttons;
 1144: }
 1145: 
 1146: #     Displays the submissions for one student or a group of students
 1147: sub processGroup {
 1148:     my ($request,$symb)  = @_;
 1149:     my $ctr        = 0;
 1150:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1151:     my $total      = scalar(@stuchecked)-1;
 1152: 
 1153:     foreach my $student (@stuchecked) {
 1154: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1155: 	$env{'form.student'}        = $uname;
 1156: 	$env{'form.userdom'}        = $udom;
 1157: 	$env{'form.fullname'}       = $fullname;
 1158: 	&submission($request,$ctr,$total,$symb);
 1159: 	$ctr++;
 1160:     }
 1161:     return '';
 1162: }
 1163: 
 1164: #------------------------------------------------------------------------------------
 1165: #
 1166: #-------------------------- Next few routines handles grading by student, essentially
 1167: #                           handles essay response type problem/part
 1168: #
 1169: #--- Javascript to handle the submission page functionality ---
 1170: sub sub_page_js {
 1171:     my $request = shift;
 1172: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1173:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1174:     function updateRadio(formname,id,weight) {
 1175: 	var gradeBox = formname["GD_BOX"+id];
 1176: 	var radioButton = formname["RADVAL"+id];
 1177: 	var oldpts = formname["oldpts"+id].value;
 1178: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1179: 	gradeBox.value = pts;
 1180: 	var resetbox = false;
 1181: 	if (isNaN(pts) || pts < 0) {
 1182: 	    alert("$alertmsg"+pts);
 1183: 	    for (var i=0; i<radioButton.length; i++) {
 1184: 		if (radioButton[i].checked) {
 1185: 		    gradeBox.value = i;
 1186: 		    resetbox = true;
 1187: 		}
 1188: 	    }
 1189: 	    if (!resetbox) {
 1190: 		formtextbox.value = "";
 1191: 	    }
 1192: 	    return;
 1193: 	}
 1194: 
 1195: 	if (pts > weight) {
 1196: 	    var resp = confirm("You entered a value ("+pts+
 1197: 			       ") greater than the weight for the part. Accept?");
 1198: 	    if (resp == false) {
 1199: 		gradeBox.value = oldpts;
 1200: 		return;
 1201: 	    }
 1202: 	}
 1203: 
 1204: 	for (var i=0; i<radioButton.length; i++) {
 1205: 	    radioButton[i].checked=false;
 1206: 	    if (pts == i && pts != "") {
 1207: 		radioButton[i].checked=true;
 1208: 	    }
 1209: 	}
 1210: 	updateSelect(formname,id);
 1211: 	formname["stores"+id].value = "0";
 1212:     }
 1213: 
 1214:     function writeBox(formname,id,pts) {
 1215: 	var gradeBox = formname["GD_BOX"+id];
 1216: 	if (checkSolved(formname,id) == 'update') {
 1217: 	    gradeBox.value = pts;
 1218: 	} else {
 1219: 	    var oldpts = formname["oldpts"+id].value;
 1220: 	    gradeBox.value = oldpts;
 1221: 	    var radioButton = formname["RADVAL"+id];
 1222: 	    for (var i=0; i<radioButton.length; i++) {
 1223: 		radioButton[i].checked=false;
 1224: 		if (i == oldpts) {
 1225: 		    radioButton[i].checked=true;
 1226: 		}
 1227: 	    }
 1228: 	}
 1229: 	formname["stores"+id].value = "0";
 1230: 	updateSelect(formname,id);
 1231: 	return;
 1232:     }
 1233: 
 1234:     function clearRadBox(formname,id) {
 1235: 	if (checkSolved(formname,id) == 'noupdate') {
 1236: 	    updateSelect(formname,id);
 1237: 	    return;
 1238: 	}
 1239: 	gradeSelect = formname["GD_SEL"+id];
 1240: 	for (var i=0; i<gradeSelect.length; i++) {
 1241: 	    if (gradeSelect[i].selected) {
 1242: 		var selectx=i;
 1243: 	    }
 1244: 	}
 1245: 	var stores = formname["stores"+id];
 1246: 	if (selectx == stores.value) { return };
 1247: 	var gradeBox = formname["GD_BOX"+id];
 1248: 	gradeBox.value = "";
 1249: 	var radioButton = formname["RADVAL"+id];
 1250: 	for (var i=0; i<radioButton.length; i++) {
 1251: 	    radioButton[i].checked=false;
 1252: 	}
 1253: 	stores.value = selectx;
 1254:     }
 1255: 
 1256:     function checkSolved(formname,id) {
 1257: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1258: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1259: 	    if (!reply) {return "noupdate";}
 1260: 	    formname.overRideScore.value = 'yes';
 1261: 	}
 1262: 	return "update";
 1263:     }
 1264: 
 1265:     function updateSelect(formname,id) {
 1266: 	formname["GD_SEL"+id][0].selected = true;
 1267: 	return;
 1268:     }
 1269: 
 1270: //=========== Check that a point is assigned for all the parts  ============
 1271:     function checksubmit(formname,val,total,parttot) {
 1272: 	formname.gradeOpt.value = val;
 1273: 	if (val == "Save & Next") {
 1274: 	    for (i=0;i<=total;i++) {
 1275: 		for (j=0;j<parttot;j++) {
 1276: 		    var partid = formname["partid"+i+"_"+j].value;
 1277: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1278: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1279: 			if (points == "") {
 1280: 			    var name = formname["name"+i].value;
 1281: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1282: 			    var resp = confirm("You did not assign a score for "+studentID+
 1283: 					       ", part "+partid+". Continue?");
 1284: 			    if (resp == false) {
 1285: 				formname["GD_BOX"+i+"_"+partid].focus();
 1286: 				return false;
 1287: 			    }
 1288: 			}
 1289: 		    }
 1290: 		    
 1291: 		}
 1292: 	    }
 1293: 	    
 1294: 	}
 1295: 	formname.submit();
 1296:     }
 1297: 
 1298: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1299:     function checkSubmitPage(formname,total) {
 1300: 	noscore = new Array(100);
 1301: 	var ptr = 0;
 1302: 	for (i=1;i<total;i++) {
 1303: 	    var partid = formname["q_"+i].value;
 1304: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1305: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1306: 		var status = formname["solved"+i+"_"+partid].value;
 1307: 		if (points == "" && status != "correct_by_student") {
 1308: 		    noscore[ptr] = i;
 1309: 		    ptr++;
 1310: 		}
 1311: 	    }
 1312: 	}
 1313: 	if (ptr != 0) {
 1314: 	    var sense = ptr == 1 ? ": " : "s: ";
 1315: 	    var prolist = "";
 1316: 	    if (ptr == 1) {
 1317: 		prolist = noscore[0];
 1318: 	    } else {
 1319: 		var i = 0;
 1320: 		while (i < ptr-1) {
 1321: 		    prolist += noscore[i]+", ";
 1322: 		    i++;
 1323: 		}
 1324: 		prolist += "and "+noscore[i];
 1325: 	    }
 1326: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1327: 	    if (resp == false) {
 1328: 		return false;
 1329: 	    }
 1330: 	}
 1331: 
 1332: 	formname.submit();
 1333:     }
 1334: SUBJAVASCRIPT
 1335: }
 1336: 
 1337: #--- javascript for essay type problem --
 1338: sub sub_page_kw_js {
 1339:     my $request = shift;
 1340:     my $iconpath = $request->dir_config('lonIconsURL');
 1341:     &commonJSfunctions($request);
 1342: 
 1343:     my $inner_js_msg_central= (<<INNERJS);
 1344: <script type="text/javascript">
 1345:     function checkInput() {
 1346:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1347:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1348:       var usrctr = document.msgcenter.usrctr.value;
 1349:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1350:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1351: 
 1352:       var msgchk = "";
 1353:       if (document.msgcenter.subchk.checked) {
 1354:          msgchk = "msgsub,";
 1355:       }
 1356:       var includemsg = 0;
 1357:       for (var i=1; i<=nmsg; i++) {
 1358:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1359:           var frmmsg = document.msgcenter["msg"+i];
 1360:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1361:           var showflg = opener.document.SCORE["shownOnce"+i];
 1362:           showflg.value = "1";
 1363:           var chkbox = document.msgcenter["msgn"+i];
 1364:           if (chkbox.checked) {
 1365:              msgchk += "savemsg"+i+",";
 1366:              includemsg = 1;
 1367:           }
 1368:       }
 1369:       if (document.msgcenter.newmsgchk.checked) {
 1370:          msgchk += "newmsg"+usrctr;
 1371:          includemsg = 1;
 1372:       }
 1373:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1374:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1375:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1376:       includemsg.value = msgchk;
 1377: 
 1378:       self.close()
 1379: 
 1380:     }
 1381: </script>
 1382: INNERJS
 1383: 
 1384:     my $inner_js_highlight_central= (<<INNERJS);
 1385: <script type="text/javascript">
 1386:     function updateChoice(flag) {
 1387:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1388:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1389:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1390:       opener.document.SCORE.refresh.value = "on";
 1391:       if (opener.document.SCORE.keywords.value!=""){
 1392:          opener.document.SCORE.submit();
 1393:       }
 1394:       self.close()
 1395:     }
 1396: </script>
 1397: INNERJS
 1398: 
 1399:     my $start_page_msg_central = 
 1400:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1401: 				       {'js_ready'  => 1,
 1402: 					'only_body' => 1,
 1403: 					'bgcolor'   =>'#FFFFFF',});
 1404:     my $end_page_msg_central = 
 1405: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1406: 
 1407: 
 1408:     my $start_page_highlight_central = 
 1409:         &Apache::loncommon::start_page('Highlight Central',
 1410: 				       $inner_js_highlight_central,
 1411: 				       {'js_ready'  => 1,
 1412: 					'only_body' => 1,
 1413: 					'bgcolor'   =>'#FFFFFF',});
 1414:     my $end_page_highlight_central = 
 1415: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1416: 
 1417:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1418:     $docopen=~s/^document\.//;
 1419:     my %lt = &Apache::lonlocal::texthash(
 1420:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
 1421:                 plse => 'Please select a word or group of words from document and then click this link.',
 1422:                 adds => 'Add selection to keyword list? Edit if desired.',
 1423:                 comp => 'Compose Message for: ',
 1424:                 incl => 'Include',
 1425:                 type => 'Type',
 1426:                 subj => 'Subject',
 1427:                 mesa => 'Message',
 1428:                 new  => 'New',
 1429:                 save => 'Save',
 1430:                 canc => 'Cancel',
 1431:                 kehi => 'Keyword Highlight Options',
 1432:                 txtc => 'Text Color',
 1433:                 font => 'Font Size',
 1434:                 fnst => 'Font Style',
 1435:              );
 1436:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1437: 
 1438: //===================== Show list of keywords ====================
 1439:   function keywords(formname) {
 1440:     var nret = prompt("$lt{'keyw'}",formname.keywords.value);
 1441:     if (nret==null) return;
 1442:     formname.keywords.value = nret;
 1443: 
 1444:     if (formname.keywords.value != "") {
 1445: 	formname.refresh.value = "on";
 1446: 	formname.submit();
 1447:     }
 1448:     return;
 1449:   }
 1450: 
 1451: //===================== Script to view submitted by ==================
 1452:   function viewSubmitter(submitter) {
 1453:     document.SCORE.refresh.value = "on";
 1454:     document.SCORE.NCT.value = "1";
 1455:     document.SCORE.unamedom0.value = submitter;
 1456:     document.SCORE.submit();
 1457:     return;
 1458:   }
 1459: 
 1460: //===================== Script to add keyword(s) ==================
 1461:   function getSel() {
 1462:     if (document.getSelection) txt = document.getSelection();
 1463:     else if (document.selection) txt = document.selection.createRange().text;
 1464:     else return;
 1465:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1466:     if (cleantxt=="") {
 1467: 	alert("$lt{'plse'}");
 1468: 	return;
 1469:     }
 1470:     var nret = prompt("$lt{'adds'}",cleantxt);
 1471:     if (nret==null) return;
 1472:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1473:     if (document.SCORE.keywords.value != "") {
 1474: 	document.SCORE.refresh.value = "on";
 1475: 	document.SCORE.submit();
 1476:     }
 1477:     return;
 1478:   }
 1479: 
 1480: //====================== Script for composing message ==============
 1481:    // preload images
 1482:    img1 = new Image();
 1483:    img1.src = "$iconpath/mailbkgrd.gif";
 1484:    img2 = new Image();
 1485:    img2.src = "$iconpath/mailto.gif";
 1486: 
 1487:   function msgCenter(msgform,usrctr,fullname) {
 1488:     var Nmsg  = msgform.savemsgN.value;
 1489:     savedMsgHeader(Nmsg,usrctr,fullname);
 1490:     var subject = msgform.msgsub.value;
 1491:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1492:     re = /msgsub/;
 1493:     var shwsel = "";
 1494:     if (re.test(msgchk)) { shwsel = "checked" }
 1495:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1496:     displaySubject(checkEntities(subject),shwsel);
 1497:     for (var i=1; i<=Nmsg; i++) {
 1498: 	var testmsg = "savemsg"+i+",";
 1499: 	re = new RegExp(testmsg,"g");
 1500: 	shwsel = "";
 1501: 	if (re.test(msgchk)) { shwsel = "checked" }
 1502: 	var message = document.SCORE["savemsg"+i].value;
 1503: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1504: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1505: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1506:     }
 1507:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1508:     shwsel = "";
 1509:     re = /newmsg/;
 1510:     if (re.test(msgchk)) { shwsel = "checked" }
 1511:     newMsg(newmsg,shwsel);
 1512:     msgTail(); 
 1513:     return;
 1514:   }
 1515: 
 1516:   function checkEntities(strx) {
 1517:     if (strx.length == 0) return strx;
 1518:     var orgStr = ["&", "<", ">", '"']; 
 1519:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1520:     var counter = 0;
 1521:     while (counter < 4) {
 1522: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1523: 	counter++;
 1524:     }
 1525:     return strx;
 1526:   }
 1527: 
 1528:   function strReplace(strx, orgStr, newStr) {
 1529:     return strx.split(orgStr).join(newStr);
 1530:   }
 1531: 
 1532:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1533:     var height = 70*Nmsg+250;
 1534:     if (height > 600) {
 1535: 	height = 600;
 1536:     }
 1537:     var xpos = (screen.width-600)/2;
 1538:     xpos = (xpos < 0) ? '0' : xpos;
 1539:     var ypos = (screen.height-height)/2-30;
 1540:     ypos = (ypos < 0) ? '0' : ypos;
 1541: 
 1542:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
 1543:     pWin.focus();
 1544:     pDoc = pWin.document;
 1545:     pDoc.$docopen;
 1546:     pDoc.write('$start_page_msg_central');
 1547: 
 1548:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1549:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1550:     pDoc.write("<h1>&nbsp;$lt{'comp'}\"+fullname+\"<\\/h1>");
 1551: 
 1552:     pDoc.write('<table style="border:1px solid black;"><tr>');
 1553:     pDoc.write("<td><b>$lt{'incl'}<\\/b><\\/td><td><b>$lt{'type'}<\\/b><\\/td><td><b>$lt{'mesa'}<\\/td><\\/tr>");
 1554: }
 1555:     function displaySubject(msg,shwsel) {
 1556:     pDoc = pWin.document;
 1557:     pDoc.write("<tr>");
 1558:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1559:     pDoc.write("<td>$lt{'subj'}<\\/td>");
 1560:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1561: }
 1562: 
 1563:   function displaySavedMsg(ctr,msg,shwsel) {
 1564:     pDoc = pWin.document;
 1565:     pDoc.write("<tr>");
 1566:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1567:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1568:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1569: }
 1570: 
 1571:   function newMsg(newmsg,shwsel) {
 1572:     pDoc = pWin.document;
 1573:     pDoc.write("<tr>");
 1574:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1575:     pDoc.write("<td align=\\"center\\">$lt{'new'}<\\/td>");
 1576:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1577: }
 1578: 
 1579:   function msgTail() {
 1580:     pDoc = pWin.document;
 1581:     //pDoc.write("<\\/table>");
 1582:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1583:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1584:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
 1585:     pDoc.write("<\\/form>");
 1586:     pDoc.write('$end_page_msg_central');
 1587:     pDoc.close();
 1588: }
 1589: 
 1590: //====================== Script for keyword highlight options ==============
 1591:   function kwhighlight() {
 1592:     var kwclr    = document.SCORE.kwclr.value;
 1593:     var kwsize   = document.SCORE.kwsize.value;
 1594:     var kwstyle  = document.SCORE.kwstyle.value;
 1595:     var redsel = "";
 1596:     var grnsel = "";
 1597:     var blusel = "";
 1598:     if (kwclr=="red")   {var redsel="checked"};
 1599:     if (kwclr=="green") {var grnsel="checked"};
 1600:     if (kwclr=="blue")  {var blusel="checked"};
 1601:     var sznsel = "";
 1602:     var sz1sel = "";
 1603:     var sz2sel = "";
 1604:     if (kwsize=="0")  {var sznsel="checked"};
 1605:     if (kwsize=="+1") {var sz1sel="checked"};
 1606:     if (kwsize=="+2") {var sz2sel="checked"};
 1607:     var synsel = "";
 1608:     var syisel = "";
 1609:     var sybsel = "";
 1610:     if (kwstyle=="")    {var synsel="checked"};
 1611:     if (kwstyle=="<i>") {var syisel="checked"};
 1612:     if (kwstyle=="<b>") {var sybsel="checked"};
 1613:     highlightCentral();
 1614:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
 1615:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
 1616:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
 1617:     highlightend();
 1618:     return;
 1619:   }
 1620: 
 1621:   function highlightCentral() {
 1622: //    if (window.hwdWin) window.hwdWin.close();
 1623:     var xpos = (screen.width-400)/2;
 1624:     xpos = (xpos < 0) ? '0' : xpos;
 1625:     var ypos = (screen.height-330)/2-30;
 1626:     ypos = (ypos < 0) ? '0' : ypos;
 1627: 
 1628:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1629:     hwdWin.focus();
 1630:     var hDoc = hwdWin.document;
 1631:     hDoc.$docopen;
 1632:     hDoc.write('$start_page_highlight_central');
 1633:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1634:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;$lt{'kehi'}<\\/span><\\/h3><br /><br />");
 1635: 
 1636:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1637:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1638:     hDoc.write("<td><b>$lt{'txtc'}<\\/b><\\/td><td><b>$lt{'font'}<\\/b><\\/td><td><b>$lt{'fnst'}<\\/td><\\/tr>");
 1639:   }
 1640: 
 1641:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1642:     var hDoc = hwdWin.document;
 1643:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1644:     hDoc.write("<td align=\\"left\\">");
 1645:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
 1646:     hDoc.write("<td align=\\"left\\">");
 1647:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
 1648:     hDoc.write("<td align=\\"left\\">");
 1649:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
 1650:     hDoc.write("<\\/tr>");
 1651:   }
 1652: 
 1653:   function highlightend() { 
 1654:     var hDoc = hwdWin.document;
 1655:     hDoc.write("<\\/table>");
 1656:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1657:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
 1658:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
 1659:     hDoc.write("<\\/form>");
 1660:     hDoc.write('$end_page_highlight_central');
 1661:     hDoc.close();
 1662:   }
 1663: 
 1664: SUBJAVASCRIPT
 1665: }
 1666: 
 1667: sub get_increment {
 1668:     my $increment = $env{'form.increment'};
 1669:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1670:         $increment != .1) {
 1671:         $increment = 1;
 1672:     }
 1673:     return $increment;
 1674: }
 1675: 
 1676: sub gradeBox_start {
 1677:     return (
 1678:         &Apache::loncommon::start_data_table()
 1679:        .&Apache::loncommon::start_data_table_header_row()
 1680:        .'<th>'.&mt('Part').'</th>'
 1681:        .'<th>'.&mt('Points').'</th>'
 1682:        .'<th>&nbsp;</th>'
 1683:        .'<th>'.&mt('Assign Grade').'</th>'
 1684:        .'<th>'.&mt('Weight').'</th>'
 1685:        .'<th>'.&mt('Grade Status').'</th>'
 1686:        .&Apache::loncommon::end_data_table_header_row()
 1687:     );
 1688: }
 1689: 
 1690: sub gradeBox_end {
 1691:     return (
 1692:         &Apache::loncommon::end_data_table()
 1693:     );
 1694: }
 1695: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1696: sub gradeBox {
 1697:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1698:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1699: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1700:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1701:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1702:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1703:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1704:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1705: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1706:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1707:     my $display_part= &get_display_part($partid,$symb);
 1708:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1709: 				       [$partid]);
 1710:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1711:     if ($last_resets{$partid}) {
 1712:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1713:     }
 1714:     my $result=&Apache::loncommon::start_data_table_row();
 1715:     my $ctr = 0;
 1716:     my $thisweight = 0;
 1717:     my $increment = &get_increment();
 1718: 
 1719:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1720:     while ($thisweight<=$wgt) {
 1721: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1722:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1723: 	    $thisweight.')" value="'.$thisweight.'" '.
 1724: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1725: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1726:         $thisweight += $increment;
 1727: 	$ctr++;
 1728:     }
 1729:     $radio.='</tr></table>';
 1730: 
 1731:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1732: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1733: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1734: 	$wgt.')" /></td>'."\n";
 1735:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1736: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1737: 	' </td>'."\n";
 1738:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1739: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1740:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1741: 	$line.='<option></option>'.
 1742: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1743:     } else {
 1744: 	$line.='<option selected="selected"></option>'.
 1745: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1746:     }
 1747:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1748: 
 1749: 
 1750:     $result .= 
 1751: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 1752:     $result.=&Apache::loncommon::end_data_table_row();
 1753:     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
 1754:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1755: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1756: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1757: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1758:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1759:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1760:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1761:         $aggtries.'" />'."\n";
 1762:     my $res_error;
 1763:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 1764:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
 1765:     if ($res_error) {
 1766:         return &navmap_errormsg();
 1767:     }
 1768:     return $result;
 1769: }
 1770: 
 1771: sub handback_box {
 1772:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
 1773:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
 1774:     my (@respids);
 1775:     my @part_response_id = &flatten_responseType($responseType);
 1776:     foreach my $part_response_id (@part_response_id) {
 1777:     	my ($part,$resp) = @{ $part_response_id };
 1778:         if ($part eq $partid) {
 1779:             push(@respids,$resp);
 1780:         }
 1781:     }
 1782:     my $result;
 1783:     foreach my $respid (@respids) {
 1784: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1785: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1786: 	next if (!@$files);
 1787: 	my $file_counter = 0;
 1788: 	foreach my $file (@$files) {
 1789: 	    if ($file =~ /\/portfolio\//) {
 1790:                 $file_counter++;
 1791:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1792:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1793:     	        $file_disp = "$name.$ext";
 1794:     	        $file = $file_path.$file_disp;
 1795:     	        $result.=&mt('Return commented version of [_1] to student.',
 1796:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1797:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1798:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
 1799: 	    }
 1800: 	}
 1801:         if ($file_counter) {
 1802:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
 1803:                        '<span class="LC_info">'.
 1804:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
 1805:         }
 1806:     }
 1807:     return $result;    
 1808: }
 1809: 
 1810: sub show_problem {
 1811:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1812:     my $rendered;
 1813:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1814:     &Apache::lonxml::remember_problem_counter();
 1815:     if ($mode eq 'both' or $mode eq 'text') {
 1816: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1817: 						       $env{'request.course.id'},
 1818: 						       undef,\%form);
 1819:     }
 1820:     if ($removeform) {
 1821: 	$rendered=~s|<form(.*?)>||g;
 1822: 	$rendered=~s|</form>||g;
 1823: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1824:     }
 1825:     my $companswer;
 1826:     if ($mode eq 'both' or $mode eq 'answer') {
 1827: 	&Apache::lonxml::restore_problem_counter();
 1828: 	$companswer=
 1829: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1830: 						    $env{'request.course.id'},
 1831: 						    %form);
 1832:     }
 1833:     if ($removeform) {
 1834: 	$companswer=~s|<form(.*?)>||g;
 1835: 	$companswer=~s|</form>||g;
 1836: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1837:     }
 1838:     my $renderheading = &mt('View of the problem');
 1839:     my $answerheading = &mt('Correct answer');
 1840:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 1841:         my $stu_fullname = $env{'form.fullname'};
 1842:         if ($stu_fullname eq '') {
 1843:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
 1844:         }
 1845:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
 1846:         if ($forwhom ne '') {
 1847:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
 1848:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
 1849:         }
 1850:     }
 1851:     $rendered=
 1852:         '<div class="LC_Box">'
 1853:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
 1854:        .$rendered
 1855:        .'</div>';
 1856:     $companswer=
 1857:         '<div class="LC_Box">'
 1858:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
 1859:        .$companswer
 1860:        .'</div>';
 1861:     my $result;
 1862:     if ($mode eq 'both') {
 1863:         $result=$rendered.$companswer;
 1864:     } elsif ($mode eq 'text') {
 1865:         $result=$rendered;
 1866:     } elsif ($mode eq 'answer') {
 1867:         $result=$companswer;
 1868:     }
 1869:     return $result;
 1870: }
 1871: 
 1872: sub files_exist {
 1873:     my ($r, $symb) = @_;
 1874:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1875: 
 1876:     foreach my $student (@students) {
 1877:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1878:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1879: 					      $udom,$uname);
 1880:         my ($string,$timestamp)= &get_last_submission(\%record);
 1881:         foreach my $submission (@$string) {
 1882:             my ($partid,$respid) =
 1883: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1884:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1885: 					   \%record);
 1886:             return 1 if (@$files);
 1887:         }
 1888:     }
 1889:     return 0;
 1890: }
 1891: 
 1892: sub download_all_link {
 1893:     my ($r,$symb) = @_;
 1894:     unless (&files_exist($r, $symb)) {
 1895:        $r->print(&mt('There are currently no submitted documents.'));
 1896:        return;
 1897:     }
 1898: 
 1899:     my $all_students = 
 1900: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1901: 
 1902:     my $parts =
 1903: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1904: 
 1905:     my $identifier = &Apache::loncommon::get_cgi_id();
 1906:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 1907:                              'cgi.'.$identifier.'.symb' => $symb,
 1908:                              'cgi.'.$identifier.'.parts' => $parts,});
 1909:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1910: 	      &mt('Download All Submitted Documents').'</a>');
 1911:     return;
 1912: }
 1913: 
 1914: sub submit_download_link {
 1915:     my ($request,$symb) = @_;
 1916:     if (!$symb) { return ''; }
 1917: #FIXME: Figure out which type of problem this is and provide appropriate download
 1918:     &download_all_link($request,$symb);
 1919: }
 1920: 
 1921: sub build_section_inputs {
 1922:     my $section_inputs;
 1923:     if ($env{'form.section'} eq '') {
 1924:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 1925:     } else {
 1926:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 1927:         foreach my $section (@sections) {
 1928:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 1929:         }
 1930:     }
 1931:     return $section_inputs;
 1932: }
 1933: 
 1934: # --------------------------- show submissions of a student, option to grade 
 1935: sub submission {
 1936:     my ($request,$counter,$total,$symb) = @_;
 1937:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 1938:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 1939:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 1940:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 1941: 
 1942:     my $probtitle=&Apache::lonnet::gettitle($symb); 
 1943:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 1944: 
 1945:     if (!&canview($usec)) {
 1946:         $request->print(
 1947:             '<span class="LC_warning">'.
 1948:             &mt('Unable to view requested student.').
 1949:             ' '.&mt('([_1] in section [_2] in course id [_3])',
 1950:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
 1951:             '</span>');
 1952: 	return;
 1953:     }
 1954: 
 1955:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 1956:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 1957:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 1958:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 1959:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1960: 	'" src="'.$request->dir_config('lonIconsURL').
 1961: 	'/check.gif" height="16" border="0" />';
 1962: 
 1963:     # header info
 1964:     if ($counter == 0) {
 1965: 	&sub_page_js($request);
 1966: 	&sub_page_kw_js($request);
 1967: 
 1968: 	# option to display problem, only once else it cause problems 
 1969:         # with the form later since the problem has a form.
 1970: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 1971: 	    my $mode;
 1972: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 1973: 		$mode='both';
 1974: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 1975: 		$mode='text';
 1976: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 1977: 		$mode='answer';
 1978: 	    }
 1979: 	    &Apache::lonxml::clear_problem_counter();
 1980: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 1981: 	}
 1982: 
 1983: 	# kwclr is the only variable that is guaranteed not to be blank 
 1984:         # if this subroutine has been called once.
 1985: 	my %keyhash = ();
 1986: #	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 1987:         if (1) {
 1988: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 1989: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 1990: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 1991: 
 1992: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 1993: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 1994: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 1995: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 1996: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 1997: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 1998: 		$keyhash{$symb.'_subject'} : $probtitle;
 1999: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 2000: 	}
 2001: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 2002: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 2003: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 2004: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 2005: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 2006: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 2007: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 2008: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 2009: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 2010: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 2011: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 2012: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 2013: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 2014: 			&build_section_inputs().
 2015: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 2016: 			'<input type="hidden" name="NCT"'.
 2017: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 2018: #	if ($env{'form.handgrade'} eq 'yes') {
 2019:         if (1) {
 2020: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 2021: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 2022: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 2023: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 2024: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2025: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2026: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2027: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 2028: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 2029: 	    }
 2030: 	}
 2031: 	
 2032: 	my ($cts,$prnmsg) = (1,'');
 2033: 	while ($cts <= $env{'form.savemsgN'}) {
 2034: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2035: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2036: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2037: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2038: 		'" />'."\n".
 2039: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2040: 	    $cts++;
 2041: 	}
 2042: 	$request->print($prnmsg);
 2043: 
 2044: #	if ($env{'form.handgrade'} eq 'yes') {
 2045:         if (1) {
 2046: 
 2047:             my %lt = &Apache::lonlocal::texthash(
 2048:                           keyw => 'Keyword Options',
 2049:                           list => 'List',
 2050:                           past => 'Paste Selection to List',
 2051:                           high => 'Highlight Attribute',
 2052:                      );    
 2053: #
 2054: # Print out the keyword options line
 2055: #
 2056: 	    $request->print(<<KEYWORDS);
 2057: <br /><b>$lt{'keyw'}:</b>&nbsp;
 2058: <a href="javascript:keywords(document.SCORE);" target="_self">$lt{'list'}</a>&nbsp; &nbsp;
 2059: <a href="#" onmousedown="javascript:getSel(); return false"
 2060:  class="page">$lt{'past'}</a>&nbsp; &nbsp;
 2061: <a href="javascript:kwhighlight();" target="_self">$lt{'high'}</a><br /><br />
 2062: KEYWORDS
 2063: #
 2064: # Load the other essays for similarity check
 2065: #
 2066:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2067: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2068: 	    $apath=&escape($apath);
 2069: 	    $apath=~s/\W/\_/gs;
 2070:             &init_old_essays($symb,$apath,$adom,$aname);
 2071:         }
 2072:     }
 2073: 
 2074: # This is where output for one specific student would start
 2075:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2076:     $request->print(
 2077:         "\n\n"
 2078:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2079:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2080:        ."\n"
 2081:     );
 2082: 
 2083:     # Show additional functions if allowed
 2084:     if ($perm{'vgr'}) {
 2085:         $request->print(
 2086:             &Apache::loncommon::track_student_link(
 2087:                 'View recent activity',
 2088:                 $uname,$udom,'check')
 2089:            .' '
 2090:         );
 2091:     }
 2092:     if ($perm{'opa'}) {
 2093:         $request->print(
 2094:             &Apache::loncommon::pprmlink(
 2095:                 &mt('Set/Change parameters'),
 2096:                 $uname,$udom,$symb,'check'));
 2097:     }
 2098: 
 2099:     # Show Problem
 2100:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2101: 	my $mode;
 2102: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2103: 	    $mode='both';
 2104: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2105: 	    $mode='text';
 2106: 	} elsif ($env{'form.vAns'} eq 'all') {
 2107: 	    $mode='answer';
 2108: 	}
 2109: 	&Apache::lonxml::clear_problem_counter();
 2110: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2111:     }
 2112: 
 2113:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2114:     my $res_error;
 2115:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2116:     if ($res_error) {
 2117:         $request->print(&navmap_errormsg());
 2118:         return;
 2119:     }
 2120: 
 2121:     # Display student info
 2122:     $request->print(($counter == 0 ? '' : '<br />'));
 2123: 
 2124:     my $result='<div class="LC_Box">'
 2125:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
 2126:     $result.='<input type="hidden" name="name'.$counter.
 2127:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2128: #    if ($env{'form.handgrade'} eq 'no') {
 2129:     if (1) {
 2130:         $result.='<p class="LC_info">'
 2131:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2132:                 ."</p>\n";
 2133:     }
 2134: 
 2135:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2136:     my $fullname;
 2137:     my $col_fullnames = [];
 2138: #    if ($env{'form.handgrade'} eq 'yes') {
 2139:     if (1) {
 2140: 	(my $sub_result,$fullname,$col_fullnames)=
 2141: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2142: 				 $counter);
 2143: 	$result.=$sub_result;
 2144:     }
 2145:     $request->print($result."\n");
 2146:     
 2147:     # print student answer/submission
 2148:     # Options are (1) Handgraded submission only
 2149:     #             (2) Last submission, includes submission that is not handgraded 
 2150:     #                  (for multi-response type part)
 2151:     #             (3) Last submission plus the parts info
 2152:     #             (4) The whole record for this student
 2153:     
 2154:     my ($string,$timestamp)= &get_last_submission(\%record);
 2155: 	
 2156:     my $lastsubonly;
 2157: 
 2158:     if ($$timestamp eq '') {
 2159:         $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2160:     } else {
 2161:         $lastsubonly =
 2162:             '<div class="LC_grade_submissions_body">'
 2163:            .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
 2164: 
 2165: 	my %seenparts;
 2166: 	my @part_response_id = &flatten_responseType($responseType);
 2167: 	foreach my $part (@part_response_id) {
 2168: 	    next if ($env{'form.lastSub'} eq 'hdgrade' 
 2169: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2170: 
 2171: 	    my ($partid,$respid) = @{ $part };
 2172: 	    my $display_part=&get_display_part($partid,$symb);
 2173: 	    if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2174: 		if (exists($seenparts{$partid})) { next; }
 2175: 		$seenparts{$partid}=1;
 2176:                 $request->print(
 2177:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2178:                     ' <b>'.&mt('Collaborative submission by: [_1]',
 2179:                                '<a href="javascript:viewSubmitter(\''.
 2180:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
 2181:                                '\');" target="_self">'.
 2182:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
 2183:                     '<br />');
 2184: 		next;
 2185: 		}
 2186: 	    my $responsetype = $responseType->{$partid}->{$respid};
 2187: 	    if (!exists($record{"resource.$partid.$respid.submission"})) {
 2188:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2189:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2190:                     ' <span class="LC_internal_info">'.
 2191:                     '('.&mt('Response ID: [_1]',$respid).')'.
 2192:                     '</span>&nbsp; &nbsp;'.
 2193: 	       	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2194: 		next;
 2195: 	    }
 2196: 	    foreach my $submission (@$string) {
 2197: 		my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2198: 		if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2199: 		my ($ressub,$hide,$subval) = split(/:/,$submission,3);
 2200: 		# Similarity check
 2201:                 my $similar='';
 2202:                 my ($type,$trial,$rndseed);
 2203:                 if ($hide eq 'rand') {
 2204:                     $type = 'randomizetry';
 2205:                     $trial = $record{"resource.$partid.tries"};
 2206:                     $rndseed = $record{"resource.$partid.rndseed"};
 2207:                 }
 2208: 	        if ($env{'form.checkPlag'}) {
 2209:     		    my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2210: 		        &most_similar($uname,$udom,$symb,$subval);
 2211: 		    if ($osim) {
 2212: 			$osim=int($osim*100.0);
 2213: 			my %old_course_desc = 
 2214: 			    &Apache::lonnet::coursedescription($ocrsid,
 2215: 							{'one_time' => 1});
 2216: 
 2217:                         if ($hide eq 'anon') {
 2218:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2219:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2220:                         } else {
 2221: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
 2222: 				&mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2223: 				    $osim,
 2224: 				    &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2225: 				        $old_course_desc{'description'},
 2226: 				        $old_course_desc{'num'},
 2227: 				        $old_course_desc{'domain'}).
 2228: 				    '</span></h3><blockquote><i>'.
 2229: 				    &keywords_highlight($oessay).
 2230: 				    '</i></blockquote><hr />';
 2231:                         }
 2232: 	            }
 2233: 		}
 2234: 		my $order=&get_order($partid,$respid,$symb,$uname,$udom,
 2235:                                      undef,$type,$trial,$rndseed);
 2236:                 if ($env{'form.lastSub'} eq 'lastonly' || $env{'form.lastSub'} eq 'datesub' || $env{'form.lastSub'} =~ /^(last|all)$/ || ($env{'form.lastSub'} eq 'hdgrade' && 
 2237: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2238: 		    my $display_part=&get_display_part($partid,$symb);
 2239:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
 2240:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2241:                         ' <span class="LC_internal_info">'.
 2242:                         '('.&mt('Response ID: [_1]',$respid).')'.
 2243:                         '</span>&nbsp; &nbsp;';
 2244: 		    my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2245:                         
 2246: 		    if (@$files) {
 2247:                         if ($hide eq 'anon') {
 2248:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2249:                         } else {
 2250:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
 2251:                                         .'<br /><span class="LC_warning">';
 2252:                             if(@$files == 1) {
 2253:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
 2254:                             } else {
 2255:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
 2256:                             }
 2257:                             $lastsubonly .= '</span>';                         
 2258:                             foreach my $file (@$files) {
 2259:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2260:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
 2261:                             }
 2262:                         }
 2263: 			$lastsubonly.='<br />';
 2264:                     }
 2265:                     if ($hide eq 'anon') {
 2266:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
 2267:                     } else {
 2268:              	        $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>'.
 2269: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
 2270: 					 $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
 2271:                     }
 2272: 	            if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2273: 		    $lastsubonly.='</div>';
 2274: 		}
 2275:             }
 2276: 	}
 2277: 	$lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2278:     }
 2279:     $request->print($lastsubonly);
 2280:     if ($env{'form.lastSub'} eq 'datesub') {
 2281:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2282: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2283:     } 
 2284:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2285:         $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2286: 								 $env{'request.course.id'},
 2287: 								 $last,'.submission',
 2288: 								 'Apache::grades::keywords_highlight'));
 2289:     }
 2290:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2291: 	.$udom.'" />'."\n");
 2292:     # return if view submission with no grading option
 2293:     if (!&canmodify($usec)) {
 2294: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
 2295: 	return;
 2296:     } else {
 2297: 	$request->print('</div>'."\n");
 2298:     }
 2299: 
 2300:     # essay grading message center
 2301: #    if ($env{'form.handgrade'} eq 'yes') {
 2302:     if (1) {
 2303: 	my $result='<div class="LC_grade_message_center">';
 2304:     
 2305: 	$result.='<div class="LC_grade_message_center_header">'.
 2306: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2307: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2308: 	my $msgfor = $givenn.' '.$lastname;
 2309: 	if (scalar(@$col_fullnames) > 0) {
 2310: 	    my $lastone = pop(@$col_fullnames);
 2311: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2312: 	}
 2313: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2314: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2315: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2316: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2317: 	    ',\''.$msgfor.'\');" target="_self">'.
 2318: 	    &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
 2319: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2320: 	    ' <img src="'.$request->dir_config('lonIconsURL').
 2321: 	    '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
 2322: 	    '<br />&nbsp;('.
 2323: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2324: 	$result.='</div></div>';
 2325: 	$request->print($result);
 2326:     }
 2327: 
 2328:     my %seen = ();
 2329:     my @partlist;
 2330:     my @gradePartRespid;
 2331:     my @part_response_id = &flatten_responseType($responseType);
 2332:     $request->print(
 2333:         '<div class="LC_Box">'
 2334:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2335:     );
 2336:     $request->print(&gradeBox_start());
 2337:     foreach my $part_response_id (@part_response_id) {
 2338:     	my ($partid,$respid) = @{ $part_response_id };
 2339: 	my $part_resp = join('_',@{ $part_response_id });
 2340: 	next if ($seen{$partid} > 0);
 2341: 	$seen{$partid}++;
 2342: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2343: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2344: 	push(@partlist,$partid);
 2345: 	push(@gradePartRespid,$partid.'.'.$respid);
 2346: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2347:     }
 2348:     $request->print(&gradeBox_end()); # </div>
 2349:     $request->print('</div>');
 2350: 
 2351:     $request->print('<div class="LC_grade_info_links">');
 2352:     $request->print('</div>');
 2353: 
 2354:     $result='<input type="hidden" name="partlist'.$counter.
 2355: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2356:     $result.='<input type="hidden" name="gradePartRespid'.
 2357: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2358:     my $ctr = 0;
 2359:     while ($ctr < scalar(@partlist)) {
 2360: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2361: 	    $partlist[$ctr].'" />'."\n";
 2362: 	$ctr++;
 2363:     }
 2364:     $request->print($result.''."\n");
 2365: 
 2366: # Done with printing info for one student
 2367: 
 2368:     $request->print('</div>');#LC_grade_show_user
 2369: 
 2370: 
 2371:     # print end of form
 2372:     if ($counter == $total) {
 2373:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2374: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2375: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2376: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2377: 	my $ntstu ='<select name="NTSTU">'.
 2378: 	    '<option>1</option><option>2</option>'.
 2379: 	    '<option>3</option><option>5</option>'.
 2380: 	    '<option>7</option><option>10</option></select>'."\n";
 2381: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2382: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2383:         $endform.=&mt('[_1]student(s)',$ntstu);
 2384: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2385: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2386: 	    '<input type="button" value="'.&mt('Next').'" '.
 2387: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2388:         $endform.='<span class="LC_warning">'.
 2389:                   &mt('(Next and Previous (student) do not save the scores.)').
 2390:                   '</span>'."\n" ;
 2391:         $endform.="<input type='hidden' value='".&get_increment().
 2392:             "' name='increment' />";
 2393: 	$endform.='</td></tr></table></form>';
 2394: 	$request->print($endform);
 2395:     }
 2396:     return '';
 2397: }
 2398: 
 2399: sub check_collaborators {
 2400:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2401:     my ($result,@col_fullnames);
 2402:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2403:     foreach my $part (keys(%$handgrade)) {
 2404: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2405: 					'.maxcollaborators',
 2406: 					$symb,$udom,$uname);
 2407: 	next if ($ncol <= 0);
 2408: 	$part =~ s/\_/\./g;
 2409: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2410: 	my (@good_collaborators, @bad_collaborators);
 2411: 	foreach my $possible_collaborator
 2412: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2413: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2414: 	    next if ($possible_collaborator eq '');
 2415: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
 2416: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2417: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2418: 	    # Doing this grep allows 'fuzzy' specification
 2419: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2420: 			       keys(%$classlist));
 2421: 	    if (! scalar(@matches)) {
 2422: 		push(@bad_collaborators, $possible_collaborator);
 2423: 	    } else {
 2424: 		push(@good_collaborators, @matches);
 2425: 	    }
 2426: 	}
 2427: 	if (scalar(@good_collaborators) != 0) {
 2428: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
 2429: 	    foreach my $name (@good_collaborators) {
 2430: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2431: 		push(@col_fullnames, $givenn.' '.$lastname);
 2432: 		$result.='<li>'.$fullname->{$name}.'</li>';
 2433: 	    }
 2434: 	    $result.='</ol><br />'."\n";
 2435: 	    my ($part)=split(/\./,$part);
 2436: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2437: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2438: 		"\n";
 2439: 	}
 2440: 	if (scalar(@bad_collaborators) > 0) {
 2441: 	    $result.='<div class="LC_warning">';
 2442: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2443: 	    $result .= '</div>';
 2444: 	}         
 2445: 	if (scalar(@bad_collaborators > $ncol)) {
 2446: 	    $result .= '<div class="LC_warning">';
 2447: 	    $result .= &mt('This student has submitted too many '.
 2448: 		'collaborators.  Maximum is [_1].',$ncol);
 2449: 	    $result .= '</div>';
 2450: 	}
 2451:     }
 2452:     return ($result,$fullname,\@col_fullnames);
 2453: }
 2454: 
 2455: #--- Retrieve the last submission for all the parts
 2456: sub get_last_submission {
 2457:     my ($returnhash)=@_;
 2458:     my (@string,$timestamp,%lasthidden);
 2459:     if ($$returnhash{'version'}) {
 2460: 	my %lasthash=();
 2461: 	my ($version);
 2462: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2463: 	    foreach my $key (sort(split(/\:/,
 2464: 					$$returnhash{$version.':keys'}))) {
 2465: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2466: 		$timestamp = 
 2467: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2468: 	    }
 2469: 	}
 2470:         my (%typeparts,%randombytry);
 2471:         my $showsurv = 
 2472:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2473:         foreach my $key (sort(keys(%lasthash))) {
 2474:             if ($key =~ /\.type$/) {
 2475:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2476:                     ($lasthash{$key} eq 'anonsurveycred') ||
 2477:                     ($lasthash{$key} eq 'randomizetry')) {
 2478:                     my ($ign,@parts) = split(/\./,$key);
 2479:                     pop(@parts);
 2480:                     my $id = join('.',@parts);
 2481:                     if ($lasthash{$key} eq 'randomizetry') {
 2482:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
 2483:                     } else {
 2484:                         unless ($showsurv) {
 2485:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2486:                         }
 2487:                     }
 2488:                     delete($lasthash{$key});
 2489:                 }
 2490:             }
 2491:         }
 2492:         my @hidden = keys(%typeparts);
 2493:         my @randomize = keys(%randombytry);
 2494: 	foreach my $key (keys(%lasthash)) {
 2495: 	    next if ($key !~ /\.submission$/);
 2496:             my $hide;
 2497:             if (@hidden) {
 2498:                 foreach my $id (@hidden) {
 2499:                     if ($key =~ /^\Q$id\E/) {
 2500:                         $hide = 'anon';
 2501:                         last;
 2502:                     }
 2503:                 }
 2504:             }
 2505:             unless ($hide) {
 2506:                 if (@randomize) {
 2507:                     foreach my $id (@hidden) {
 2508:                         if ($key =~ /^\Q$id\E/) {
 2509:                             $hide = 'rand';
 2510:                             last;
 2511:                         }
 2512:                     }
 2513:                 }
 2514:             }
 2515: 	    my ($partid,$foo) = split(/submission$/,$key);
 2516: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 2517: 		'<span class="LC_warning">'.&mt('Draft Copy').'</span> ' : '';
 2518: 	    #push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
 2519:             push(@string, join(':', $key, $hide, $draft.(
 2520:                 ref($lasthash{$key}) eq 'ARRAY' ?
 2521:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
 2522: 	}
 2523:     }
 2524:     if (!@string) {
 2525: 	$string[0] =
 2526: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2527:     }
 2528:     return (\@string,\$timestamp);
 2529: }
 2530: 
 2531: #--- High light keywords, with style choosen by user.
 2532: sub keywords_highlight {
 2533:     my $string    = shift;
 2534:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2535:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2536:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2537:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2538:     foreach my $keyword (@keylist) {
 2539: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2540:     }
 2541:     return $string;
 2542: }
 2543: 
 2544: # For Tasks provide a mechanism to display previous version for one specific student
 2545: 
 2546: sub show_previous_task_version {
 2547:     my ($request,$symb) = @_;
 2548:     if ($symb eq '') {
 2549:         $request->print(
 2550:             '<span class="LC_error">'.
 2551:             &mt('Unable to handle ambiguous references.').
 2552:             '</span>');
 2553:         return '';
 2554:     }
 2555:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
 2556:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2557:     if (!&canview($usec)) {
 2558:         $request->print(
 2559:             '<span class="LC_warning">'.
 2560:             &mt('Unable to view previous version for requested student.').
 2561:             ' '.&mt('([_1] in section [_2] in course id [_3])',
 2562:                     $uname.':'.$udom,$usec,$env{'request.course.id'}).
 2563:             '</span>');
 2564:         return;
 2565:     }
 2566:     my $mode = 'both';
 2567:     my $isTask = ($symb =~/\.task$/);
 2568:     if ($isTask) {
 2569:         if ($env{'form.previousversion'} =~ /^\d+$/) {
 2570:             if ($env{'form.fullname'} eq '') {
 2571:                 $env{'form.fullname'} =
 2572:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
 2573:             }
 2574:             my $probtitle=&Apache::lonnet::gettitle($symb);
 2575:             $request->print("\n\n".
 2576:                             '<div class="LC_grade_show_user">'.
 2577:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 2578:                             '</h2>'."\n");
 2579:             &Apache::lonxml::clear_problem_counter();
 2580:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
 2581:                             {'previousversion' => $env{'form.previousversion'} }));
 2582:             $request->print("\n</div>");
 2583:         }
 2584:     }
 2585:     return;
 2586: }
 2587: 
 2588: sub choose_task_version_form {
 2589:     my ($symb,$uname,$udom,$nomenu) = @_;
 2590:     my $isTask = ($symb =~/\.task$/);
 2591:     my ($current,$version,$result,$js,$displayed,$rowtitle);
 2592:     if ($isTask) {
 2593:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 2594:                                               $udom,$uname);
 2595:         if (($record{'resource.0.version'} eq '') ||
 2596:             ($record{'resource.0.version'} < 2)) {
 2597:             return ($record{'resource.0.version'},
 2598:                     $record{'resource.0.version'},$result,$js);
 2599:         } else {
 2600:             $current = $record{'resource.0.version'};
 2601:         }
 2602:         if ($env{'form.previousversion'}) {
 2603:             $displayed = $env{'form.previousversion'};
 2604:             $rowtitle = &mt('Choose another version:')
 2605:         } else {
 2606:             $displayed = $current;
 2607:             $rowtitle = &mt('Show earlier version:');
 2608:         }
 2609:         $result = '<div class="LC_left_float">';
 2610:         my $list;
 2611:         my $numversions = 0;
 2612:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
 2613:             if ($i == $current) {
 2614:                 if (!$env{'form.previousversion'} || $nomenu) {
 2615:                     next;
 2616:                 } else {
 2617:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
 2618:                     $numversions ++;
 2619:                 }
 2620:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
 2621:                 unless ($i == $env{'form.previousversion'}) {
 2622:                     $numversions ++;
 2623:                 }
 2624:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
 2625:             }
 2626:         }
 2627:         if ($numversions) {
 2628:             $symb = &HTML::Entities::encode($symb,'<>"&');
 2629:             $result .=
 2630:                 '<form name="getprev" method="post" action=""'.
 2631:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
 2632:                 &Apache::loncommon::start_data_table().
 2633:                 &Apache::loncommon::start_data_table_row().
 2634:                 '<th align="left">'.$rowtitle.'</th>'.
 2635:                 '<td><select name="version">'.
 2636:                 '<option>'.&mt('Select').'</option>'.
 2637:                 $list.
 2638:                 '</select></td>'.
 2639:                 &Apache::loncommon::end_data_table_row();
 2640:             unless ($nomenu) {
 2641:                 $result .= &Apache::loncommon::start_data_table_row().
 2642:                 '<th align="left">'.&mt('Open in new window').'</th>'.
 2643:                 '<td><span class="LC_nobreak">'.
 2644:                 '<label><input type="radio" name="prevwin" value="1" />'.
 2645:                 &mt('Yes').'</label>'.
 2646:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
 2647:                 '</span></td>'.
 2648:                 &Apache::loncommon::end_data_table_row();
 2649:             }
 2650:             $result .=
 2651:                 &Apache::loncommon::start_data_table_row().
 2652:                 '<th align="left">&nbsp;</th>'.
 2653:                 '<td>'.
 2654:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
 2655:                 '</td>'.
 2656:                 &Apache::loncommon::end_data_table_row().
 2657:                 &Apache::loncommon::end_data_table().
 2658:                 '</form>';
 2659:             $js = &previous_display_javascript($nomenu,$current);
 2660:         } elsif ($displayed && $nomenu) {
 2661:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
 2662:         } else {
 2663:             $result .= &mt('No previous versions to show for this student');
 2664:         }
 2665:         $result .= '</div>';
 2666:     }
 2667:     return ($current,$displayed,$result,$js);
 2668: }
 2669: 
 2670: sub previous_display_javascript {
 2671:     my ($nomenu,$current) = @_;
 2672:     my $js = <<"JSONE";
 2673: <script type="text/javascript">
 2674: // <![CDATA[
 2675: function previousVersion(uname,udom,symb) {
 2676:     var current = '$current';
 2677:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
 2678:     var prevstr = new RegExp("^\\\\d+\$");
 2679:     if (!prevstr.test(version)) {
 2680:         return false;
 2681:     }
 2682:     var url = '';
 2683:     if (version == current) {
 2684:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
 2685:     } else {
 2686:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
 2687:     }
 2688: JSONE
 2689:     if ($nomenu) {
 2690:         $js .= <<"JSTWO";
 2691:     document.location.href = url;
 2692: JSTWO
 2693:     } else {
 2694:         $js .= <<"JSTHREE";
 2695:     var newwin = 0;
 2696:     for (var i=0; i<document.getprev.prevwin.length; i++) {
 2697:         if (document.getprev.prevwin[i].checked == true) {
 2698:             newwin = document.getprev.prevwin[i].value;
 2699:         }
 2700:     }
 2701:     if (newwin == 1) {
 2702:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
 2703:         url = url+'&inhibitmenu=yes';
 2704:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
 2705:             previousWin = window.open(url,'',options,1);
 2706:         } else {
 2707:             previousWin.location.href = url;
 2708:         }
 2709:         previousWin.focus();
 2710:         return false;
 2711:     } else {
 2712:         document.location.href = url;
 2713:         return false;
 2714:     }
 2715: JSTHREE
 2716:     }
 2717:     $js .= <<"ENDJS";
 2718:     return false;
 2719: }
 2720: // ]]>
 2721: </script>
 2722: ENDJS
 2723: 
 2724: }
 2725: 
 2726: #--- Called from submission routine
 2727: sub processHandGrade {
 2728:     my ($request,$symb) = @_;
 2729:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2730:     my $button = $env{'form.gradeOpt'};
 2731:     my $ngrade = $env{'form.NCT'};
 2732:     my $ntstu  = $env{'form.NTSTU'};
 2733:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2734:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2735: 
 2736:     if ($button eq 'Save & Next') {
 2737: 	my $ctr = 0;
 2738: 	while ($ctr < $ngrade) {
 2739: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2740: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2741: 	    if ($errorflag eq 'no_score') {
 2742: 		$ctr++;
 2743: 		next;
 2744: 	    }
 2745: 	    if ($errorflag eq 'not_allowed') {
 2746: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
 2747: 		$ctr++;
 2748: 		next;
 2749: 	    }
 2750: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2751: 	    my ($subject,$message,$msgstatus) = ('','','');
 2752: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2753:             my ($feedurl,$showsymb) =
 2754: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2755: 	    my $messagetail;
 2756: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2757: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2758: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2759: 		$subject.=' ['.$restitle.']';
 2760: 		my (@msgnum) = split(/,/,$includemsg);
 2761: 		foreach (@msgnum) {
 2762: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2763: 		}
 2764: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2765: 		if ($env{'form.withgrades'.$ctr}) {
 2766: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2767: 		    $messagetail = " for <a href=\"".
 2768: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
 2769: 		}
 2770: 		$msgstatus = 
 2771:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2772: 						     $message.$messagetail,
 2773:                                                      undef,$feedurl,undef,
 2774:                                                      undef,undef,$showsymb,
 2775:                                                      $restitle);
 2776: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 2777: 				$msgstatus.'<br />');
 2778: 	    }
 2779: 	    if ($env{'form.collaborator'.$ctr}) {
 2780: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2781: 		foreach my $collabstr (@collabstrs) {
 2782: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2783: 		    foreach my $collaborator (@collaborators) {
 2784: 			my ($errorflag,$pts,$wgt) = 
 2785: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2786: 					   $env{'form.unamedom'.$ctr},$part);
 2787: 			if ($errorflag eq 'not_allowed') {
 2788: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2789: 			    next;
 2790: 			} elsif ($message ne '') {
 2791: 			    my ($baseurl,$showsymb) = 
 2792: 				&get_feedurl_and_symb($symb,$collaborator,
 2793: 						      $udom);
 2794: 			    if ($env{'form.withgrades'.$ctr}) {
 2795: 				$messagetail = " for <a href=\"".
 2796:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
 2797: 			    }
 2798: 			    $msgstatus = 
 2799: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2800: 			}
 2801: 		    }
 2802: 		}
 2803: 	    }
 2804: 	    $ctr++;
 2805: 	}
 2806:     }
 2807: 
 2808: #    if ($env{'form.handgrade'} eq 'yes') {
 2809:     if (1) {
 2810: 	# Keywords sorted in alphabatical order
 2811: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2812: 	my %keyhash = ();
 2813: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2814: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2815: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2816: 	$env{'form.keywords'} = join(' ',@keywords);
 2817: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2818: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2819: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2820: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2821: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2822: 
 2823: 	# message center - Order of message gets changed. Blank line is eliminated.
 2824: 	# New messages are saved in env for the next student.
 2825: 	# All messages are saved in nohist_handgrade.db
 2826: 	my ($ctr,$idx) = (1,1);
 2827: 	while ($ctr <= $env{'form.savemsgN'}) {
 2828: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2829: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2830: 		$idx++;
 2831: 	    }
 2832: 	    $ctr++;
 2833: 	}
 2834: 	$ctr = 0;
 2835: 	while ($ctr < $ngrade) {
 2836: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2837: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2838: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2839: 		$idx++;
 2840: 	    }
 2841: 	    $ctr++;
 2842: 	}
 2843: 	$env{'form.savemsgN'} = --$idx;
 2844: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2845: 	my $putresult = &Apache::lonnet::put
 2846: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2847:     }
 2848:     # Called by Save & Refresh from Highlight Attribute Window
 2849:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2850:     if ($env{'form.refresh'} eq 'on') {
 2851: 	my ($ctr,$total) = (0,0);
 2852: 	while ($ctr < $ngrade) {
 2853: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2854: 	    $ctr++;
 2855: 	}
 2856: 	$env{'form.NTSTU'}=$ngrade;
 2857: 	$ctr = 0;
 2858: 	while ($ctr < $total) {
 2859: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2860: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2861: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2862: 	    &submission($request,$ctr,$total-1,$symb);
 2863: 	    $ctr++;
 2864: 	}
 2865: 	return '';
 2866:     }
 2867: 
 2868:     # Get the next/previous one or group of students
 2869:     my $firststu = $env{'form.unamedom0'};
 2870:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2871:     my $ctr = 2;
 2872:     while ($laststu eq '') {
 2873: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2874: 	$ctr++;
 2875: 	$laststu = $firststu if ($ctr > $ngrade);
 2876:     }
 2877: 
 2878:     my (@parsedlist,@nextlist);
 2879:     my ($nextflg) = 0;
 2880:     foreach my $item (sort 
 2881: 	     {
 2882: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2883: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2884: 		 }
 2885: 		 return $a cmp $b;
 2886: 	     } (keys(%$fullname))) {
 2887: # FIXME: this is fishy, looks like the button label
 2888: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2889: 	    push(@parsedlist,$item);
 2890: 	}
 2891: 	$nextflg = 1 if ($item eq $laststu);
 2892: 	if ($button eq 'Previous') {
 2893: 	    last if ($item eq $firststu);
 2894: 	    push(@parsedlist,$item);
 2895: 	}
 2896:     }
 2897:     $ctr = 0;
 2898: # FIXME: this is fishy, looks like the button label
 2899:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2900:     my $res_error;
 2901:     my ($partlist) = &response_type($symb,\$res_error);
 2902:     if ($res_error) {
 2903:         $request->print(&navmap_errormsg());
 2904:         return;
 2905:     }
 2906:     foreach my $student (@parsedlist) {
 2907: 	my $submitonly=$env{'form.submitonly'};
 2908: 	my ($uname,$udom) = split(/:/,$student);
 2909: 	
 2910: 	if ($submitonly eq 'queued') {
 2911: 	    my %queue_status = 
 2912: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2913: 							$udom,$uname);
 2914: 	    next if (!defined($queue_status{'gradingqueue'}));
 2915: 	}
 2916: 
 2917: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2918: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2919: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2920: 	    my $submitted = 0;
 2921: 	    my $ungraded = 0;
 2922: 	    my $incorrect = 0;
 2923: 	    foreach my $item (keys(%status)) {
 2924: 		$submitted = 1 if ($status{$item} ne 'nothing');
 2925: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 2926: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 2927: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 2928: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2929: 		    $submitted = 0;
 2930: 		}
 2931: 	    }
 2932: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2933: 				     $submitonly eq 'incorrect' ||
 2934: 				     $submitonly eq 'graded'));
 2935: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2936: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2937: 	}
 2938: 	push(@nextlist,$student) if ($ctr < $ntstu);
 2939: 	last if ($ctr == $ntstu);
 2940: 	$ctr++;
 2941:     }
 2942: 
 2943:     $ctr = 0;
 2944:     my $total = scalar(@nextlist)-1;
 2945: 
 2946:     foreach (sort(@nextlist)) {
 2947: 	my ($uname,$udom,$submitter) = split(/:/);
 2948: 	$env{'form.student'}  = $uname;
 2949: 	$env{'form.userdom'}  = $udom;
 2950: 	$env{'form.fullname'} = $$fullname{$_};
 2951: 	&submission($request,$ctr,$total,$symb);
 2952: 	$ctr++;
 2953:     }
 2954:     if ($total < 0) {
 2955: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
 2956: 	$request->print($the_end);
 2957:     }
 2958:     return '';
 2959: }
 2960: 
 2961: #---- Save the score and award for each student, if changed
 2962: sub saveHandGrade {
 2963:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 2964:     my @version_parts;
 2965:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 2966: 					   $env{'request.course.id'});
 2967:     if (!&canmodify($usec)) { return('not_allowed'); }
 2968:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 2969:     my @parts_graded;
 2970:     my %newrecord  = ();
 2971:     my ($pts,$wgt) = ('','');
 2972:     my %aggregate = ();
 2973:     my $aggregateflag = 0;
 2974:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 2975:     foreach my $new_part (@parts) {
 2976: 	#collaborator ($submi may vary for different parts
 2977: 	if ($submitter && $new_part ne $part) { next; }
 2978: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 2979: 	if ($dropMenu eq 'excused') {
 2980: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 2981: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 2982: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 2983: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 2984: 		}
 2985: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 2986: 	    }
 2987: 	} elsif ($dropMenu eq 'reset status'
 2988: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 2989: 	    foreach my $key (keys(%record)) {
 2990: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 2991: 	    }
 2992: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2993: 		"$env{'user.name'}:$env{'user.domain'}";
 2994:             my $totaltries = $record{'resource.'.$part.'.tries'};
 2995: 
 2996:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2997: 					       [$new_part]);
 2998:             my $aggtries =$totaltries;
 2999:             if ($last_resets{$new_part}) {
 3000:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 3001: 					   $new_part);
 3002:             }
 3003: 
 3004:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 3005:             if ($aggtries > 0) {
 3006:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3007:                 $aggregateflag = 1;
 3008:             }
 3009: 	} elsif ($dropMenu eq '') {
 3010: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 3011: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 3012: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 3013: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 3014: 		next;
 3015: 	    }
 3016: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 3017: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 3018: 	    my $partial= $pts/$wgt;
 3019: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 3020: 		#do not update score for part if not changed.
 3021:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 3022: 		next;
 3023: 	    } else {
 3024: 	        push(@parts_graded,$new_part);
 3025: 	    }
 3026: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 3027: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 3028: 	    }
 3029: 	    my $reckey = 'resource.'.$new_part.'.solved';
 3030: 	    if ($partial == 0) {
 3031: 		if ($record{$reckey} ne 'incorrect_by_override') {
 3032: 		    $newrecord{$reckey} = 'incorrect_by_override';
 3033: 		}
 3034: 	    } else {
 3035: 		if ($record{$reckey} ne 'correct_by_override') {
 3036: 		    $newrecord{$reckey} = 'correct_by_override';
 3037: 		}
 3038: 	    }	    
 3039: 	    if ($submitter && 
 3040: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 3041: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 3042: 	    }
 3043: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3044: 		"$env{'user.name'}:$env{'user.domain'}";
 3045: 	}
 3046: 	# unless problem has been graded, set flag to version the submitted files
 3047: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 3048: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 3049: 	        $dropMenu eq 'reset status')
 3050: 	   {
 3051: 	    push(@version_parts,$new_part);
 3052: 	}
 3053:     }
 3054:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3055:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3056: 
 3057:     if (%newrecord) {
 3058:         if (@version_parts) {
 3059:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 3060:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 3061: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 3062: 	    foreach my $new_part (@version_parts) {
 3063: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 3064: 				$new_part,\%newrecord);
 3065: 	    }
 3066:         }
 3067: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 3068: 				$env{'request.course.id'},$domain,$stuname);
 3069: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 3070: 				     $cdom,$cnum,$domain,$stuname);
 3071:     }
 3072:     if ($aggregateflag) {
 3073:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3074: 			      $cdom,$cnum);
 3075:     }
 3076:     return ('',$pts,$wgt);
 3077: }
 3078: 
 3079: sub check_and_remove_from_queue {
 3080:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 3081:     my @ungraded_parts;
 3082:     foreach my $part (@{$parts}) {
 3083: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 3084: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 3085: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 3086: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 3087: 		) {
 3088: 	    push(@ungraded_parts, $part);
 3089: 	}
 3090:     }
 3091:     if ( !@ungraded_parts ) {
 3092: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 3093: 					       $cnum,$domain,$stuname);
 3094:     }
 3095: }
 3096: 
 3097: sub handback_files {
 3098:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 3099:     my $portfolio_root = '/userfiles/portfolio';
 3100:     my $res_error;
 3101:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3102:     if ($res_error) {
 3103:         $request->print('<br />'.&navmap_errormsg().'<br />');
 3104:         return;
 3105:     }
 3106:     my @handedback;
 3107:     my $file_msg;
 3108:     my @part_response_id = &flatten_responseType($responseType);
 3109:     foreach my $part_response_id (@part_response_id) {
 3110:     	my ($part_id,$resp_id) = @{ $part_response_id };
 3111: 	my $part_resp = join('_',@{ $part_response_id });
 3112:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
 3113:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
 3114:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
 3115:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
 3116:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
 3117:                     my ($directory,$answer_file) = 
 3118:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
 3119:                     my ($answer_name,$answer_ver,$answer_ext) =
 3120: 		        &file_name_version_ext($answer_file);
 3121: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 3122:                     my $getpropath = 1;
 3123:                     my ($dir_list,$listerror) = 
 3124:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
 3125:                                                  $domain,$stuname,$getpropath);
 3126: 		    my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 3127:                     # fix filename
 3128:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 3129:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 3130:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
 3131:             	                                $save_file_name);
 3132:                     if ($result !~ m|^/uploaded/|) {
 3133:                         $request->print('<br /><span class="LC_error">'.
 3134:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 3135:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
 3136:                                         '</span>');
 3137:                     } else {
 3138:                         # mark the file as read only
 3139:                         push(@handedback,$save_file_name);
 3140: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 3141: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 3142: 			}
 3143:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 3144: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
 3145:                     }
 3146:                     $request->print('<br />'.&mt('[_1] will be the uploaded filename [_2]','<span class="LC_info">'.$fname.'</span>','<span class="LC_filename">'.$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter}.'</span>'));
 3147:                 }
 3148:             }
 3149:         }
 3150:     }
 3151:     if (@handedback > 0) {
 3152:         $request->print('<br />');
 3153:         my @what = ($symb,$env{'request.course.id'},'handback');
 3154:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
 3155:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
 3156:         my ($subject,$message);
 3157:         if (scalar(@handedback) == 1) {
 3158:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
 3159:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
 3160:         } else {
 3161:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
 3162:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
 3163:         }
 3164:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
 3165:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
 3166:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
 3167:         my ($feedurl,$showsymb) =
 3168:             &get_feedurl_and_symb($symb,$domain,$stuname);
 3169:         my $restitle = &Apache::lonnet::gettitle($symb);
 3170:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
 3171:         my $msgstatus =
 3172:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
 3173:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
 3174:                  $restitle);
 3175:         if ($msgstatus) {
 3176:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
 3177:         }
 3178:     }
 3179:     return;
 3180: }
 3181: 
 3182: sub get_feedurl_and_symb {
 3183:     my ($symb,$uname,$udom) = @_;
 3184:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3185:     $url = &Apache::lonnet::clutter($url);
 3186:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 3187: 					$symb,$udom,$uname);
 3188:     if ($encrypturl =~ /^yes$/i) {
 3189: 	&Apache::lonenc::encrypted(\$url,1);
 3190: 	&Apache::lonenc::encrypted(\$symb,1);
 3191:     }
 3192:     return ($url,$symb);
 3193: }
 3194: 
 3195: sub get_submitted_files {
 3196:     my ($udom,$uname,$partid,$respid,$record) = @_;
 3197:     my @files;
 3198:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 3199:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 3200:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 3201:     	    push(@files,$file_url.$file);
 3202:         }
 3203:     }
 3204:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 3205:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 3206:     }
 3207:     return (\@files);
 3208: }
 3209: 
 3210: # ----------- Provides number of tries since last reset.
 3211: sub get_num_tries {
 3212:     my ($record,$last_reset,$part) = @_;
 3213:     my $timestamp = '';
 3214:     my $num_tries = 0;
 3215:     if ($$record{'version'}) {
 3216:         for (my $version=$$record{'version'};$version>=1;$version--) {
 3217:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 3218:                 $timestamp = $$record{$version.':timestamp'};
 3219:                 if ($timestamp > $last_reset) {
 3220:                     $num_tries ++;
 3221:                 } else {
 3222:                     last;
 3223:                 }
 3224:             }
 3225:         }
 3226:     }
 3227:     return $num_tries;
 3228: }
 3229: 
 3230: # ----------- Determine decrements required in aggregate totals 
 3231: sub decrement_aggs {
 3232:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 3233:     my %decrement = (
 3234:                         attempts => 0,
 3235:                         users => 0,
 3236:                         correct => 0
 3237:                     );
 3238:     $decrement{'attempts'} = $aggtries;
 3239:     if ($solvedstatus =~ /^correct/) {
 3240:         $decrement{'correct'} = 1;
 3241:     }
 3242:     if ($aggtries == $totaltries) {
 3243:         $decrement{'users'} = 1;
 3244:     }
 3245:     foreach my $type (keys(%decrement)) {
 3246:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 3247:     }
 3248:     return;
 3249: }
 3250: 
 3251: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3252: sub get_last_resets {
 3253:     my ($symb,$courseid,$partids) =@_;
 3254:     my %last_resets;
 3255:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3256:     my $cname = $env{'course.'.$courseid.'.num'};
 3257:     my @keys;
 3258:     foreach my $part (@{$partids}) {
 3259: 	push(@keys,"$symb\0$part\0resettime");
 3260:     }
 3261:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3262: 				     $cdom,$cname);
 3263:     foreach my $part (@{$partids}) {
 3264: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3265:     }
 3266:     return %last_resets;
 3267: }
 3268: 
 3269: # ----------- Handles creating versions for portfolio files as answers
 3270: sub version_portfiles {
 3271:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3272:     my $version_parts = join('|',@$v_flag);
 3273:     my @returned_keys;
 3274:     my $parts = join('|', @$parts_graded);
 3275:     my $portfolio_root = '/userfiles/portfolio';
 3276:     foreach my $key (keys(%$record)) {
 3277:         my $new_portfiles;
 3278:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3279:             my @versioned_portfiles;
 3280:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3281:             foreach my $file (@portfiles) {
 3282:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 3283:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 3284: 		my ($answer_name,$answer_ver,$answer_ext) =
 3285: 		    &file_name_version_ext($answer_file);
 3286:                 my $getpropath = 1;    
 3287:                 my ($dir_list,$listerror) = 
 3288:                     &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
 3289:                                              $stu_name,$getpropath);
 3290:                 my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 3291:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 3292:                 if ($new_answer ne 'problem getting file') {
 3293:                     push(@versioned_portfiles, $directory.$new_answer);
 3294:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 3295:                         [$directory.$new_answer],
 3296:                         [$symb,$env{'request.course.id'},'graded']);
 3297:                 }
 3298:             }
 3299:             $$record{$key} = join(',',@versioned_portfiles);
 3300:             push(@returned_keys,$key);
 3301:         }
 3302:     } 
 3303:     return (@returned_keys);   
 3304: }
 3305: 
 3306: sub get_next_version {
 3307:     my ($answer_name, $answer_ext, $dir_list) = @_;
 3308:     my $version;
 3309:     if (ref($dir_list) eq 'ARRAY') {
 3310:         foreach my $row (@{$dir_list}) {
 3311:             my ($file) = split(/\&/,$row,2);
 3312:             my ($file_name,$file_version,$file_ext) =
 3313: 	        &file_name_version_ext($file);
 3314:             if (($file_name eq $answer_name) && 
 3315: 	        ($file_ext eq $answer_ext)) {
 3316:                      # gets here if filename and extension match, 
 3317:                      # regardless of version
 3318:                 if ($file_version ne '') {
 3319:                     # a versioned file is found  so save it for later
 3320:                     if ($file_version > $version) {
 3321: 		        $version = $file_version;
 3322: 	            }
 3323:                 }
 3324:             }
 3325:         }
 3326:     }
 3327:     $version ++;
 3328:     return($version);
 3329: }
 3330: 
 3331: sub version_selected_portfile {
 3332:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3333:     my ($answer_name,$answer_ver,$answer_ext) =
 3334:         &file_name_version_ext($file_name);
 3335:     my $new_answer;
 3336:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3337:     if($env{'form.copy'} eq '-1') {
 3338:         $new_answer = 'problem getting file';
 3339:     } else {
 3340:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3341:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3342:                             $stu_name,$domain,'copy',
 3343: 		        '/portfolio'.$directory.$new_answer);
 3344:     }    
 3345:     return ($new_answer);
 3346: }
 3347: 
 3348: sub file_name_version_ext {
 3349:     my ($file)=@_;
 3350:     my @file_parts = split(/\./, $file);
 3351:     my ($name,$version,$ext);
 3352:     if (@file_parts > 1) {
 3353: 	$ext=pop(@file_parts);
 3354: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3355: 	    $version=pop(@file_parts);
 3356: 	}
 3357: 	$name=join('.',@file_parts);
 3358:     } else {
 3359: 	$name=join('.',@file_parts);
 3360:     }
 3361:     return($name,$version,$ext);
 3362: }
 3363: 
 3364: #--------------------------------------------------------------------------------------
 3365: #
 3366: #-------------------------- Next few routines handles grading by section or whole class
 3367: #
 3368: #--- Javascript to handle grading by section or whole class
 3369: sub viewgrades_js {
 3370:     my ($request) = shift;
 3371: 
 3372:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3373:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
 3374:    function writePoint(partid,weight,point) {
 3375: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3376: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3377: 	if (point == "textval") {
 3378: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3379: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3380: 		alert("$alertmsg"+parseFloat(point));
 3381: 		var resetbox = false;
 3382: 		for (var i=0; i<radioButton.length; i++) {
 3383: 		    if (radioButton[i].checked) {
 3384: 			textbox.value = i;
 3385: 			resetbox = true;
 3386: 		    }
 3387: 		}
 3388: 		if (!resetbox) {
 3389: 		    textbox.value = "";
 3390: 		}
 3391: 		return;
 3392: 	    }
 3393: 	    if (parseFloat(point) > parseFloat(weight)) {
 3394: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3395: 				   ") greater than the weight for the part. Accept?");
 3396: 		if (resp == false) {
 3397: 		    textbox.value = "";
 3398: 		    return;
 3399: 		}
 3400: 	    }
 3401: 	    for (var i=0; i<radioButton.length; i++) {
 3402: 		radioButton[i].checked=false;
 3403: 		if (parseFloat(point) == i) {
 3404: 		    radioButton[i].checked=true;
 3405: 		}
 3406: 	    }
 3407: 
 3408: 	} else {
 3409: 	    textbox.value = parseFloat(point);
 3410: 	}
 3411: 	for (i=0;i<document.classgrade.total.value;i++) {
 3412: 	    var user = document.classgrade["ctr"+i].value;
 3413: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3414: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3415: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3416: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3417: 	    if (saveval != "correct") {
 3418: 		scorename.value = point;
 3419: 		if (selname[0].selected != true) {
 3420: 		    selname[0].selected = true;
 3421: 		}
 3422: 	    }
 3423: 	}
 3424: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3425:     }
 3426: 
 3427:     function writeRadText(partid,weight) {
 3428: 	var selval   = document.classgrade["SELVAL_"+partid];
 3429: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3430:         var override = document.classgrade["FORCE_"+partid].checked;
 3431: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3432: 	if (selval[1].selected || selval[2].selected) {
 3433: 	    for (var i=0; i<radioButton.length; i++) {
 3434: 		radioButton[i].checked=false;
 3435: 
 3436: 	    }
 3437: 	    textbox.value = "";
 3438: 
 3439: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3440: 		var user = document.classgrade["ctr"+i].value;
 3441: 		user = user.replace(new RegExp(':', 'g'),"_");
 3442: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3443: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3444: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3445: 		if ((saveval != "correct") || override) {
 3446: 		    scorename.value = "";
 3447: 		    if (selval[1].selected) {
 3448: 			selname[1].selected = true;
 3449: 		    } else {
 3450: 			selname[2].selected = true;
 3451: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3452: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3453: 		    }
 3454: 		}
 3455: 	    }
 3456: 	} else {
 3457: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3458: 		var user = document.classgrade["ctr"+i].value;
 3459: 		user = user.replace(new RegExp(':', 'g'),"_");
 3460: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3461: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3462: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3463: 		if ((saveval != "correct") || override) {
 3464: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3465: 		    selname[0].selected = true;
 3466: 		}
 3467: 	    }
 3468: 	}	    
 3469:     }
 3470: 
 3471:     function changeSelect(partid,user) {
 3472: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3473: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3474: 	var point  = textbox.value;
 3475: 	var weight = document.classgrade["weight_"+partid].value;
 3476: 
 3477: 	if (isNaN(point) || parseFloat(point) < 0) {
 3478: 	    alert("$alertmsg"+parseFloat(point));
 3479: 	    textbox.value = "";
 3480: 	    return;
 3481: 	}
 3482: 	if (parseFloat(point) > parseFloat(weight)) {
 3483: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3484: 			       ") greater than the weight of the part. Accept?");
 3485: 	    if (resp == false) {
 3486: 		textbox.value = "";
 3487: 		return;
 3488: 	    }
 3489: 	}
 3490: 	selval[0].selected = true;
 3491:     }
 3492: 
 3493:     function changeOneScore(partid,user) {
 3494: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3495: 	if (selval[1].selected || selval[2].selected) {
 3496: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3497: 	    if (selval[2].selected) {
 3498: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3499: 	    }
 3500:         }
 3501:     }
 3502: 
 3503:     function resetEntry(numpart) {
 3504: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3505: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3506: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3507: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3508: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3509: 	    for (var i=0; i<radioButton.length; i++) {
 3510: 		radioButton[i].checked=false;
 3511: 
 3512: 	    }
 3513: 	    textbox.value = "";
 3514: 	    selval[0].selected = true;
 3515: 
 3516: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3517: 		var user = document.classgrade["ctr"+i].value;
 3518: 		user = user.replace(new RegExp(':', 'g'),"_");
 3519: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3520: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3521: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3522: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3523: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3524: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3525: 		if (saveselval == "excused") {
 3526: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3527: 		} else {
 3528: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3529: 		}
 3530: 	    }
 3531: 	}
 3532:     }
 3533: 
 3534: VIEWJAVASCRIPT
 3535: }
 3536: 
 3537: #--- show scores for a section or whole class w/ option to change/update a score
 3538: sub viewgrades {
 3539:     my ($request,$symb) = @_;
 3540:     &viewgrades_js($request);
 3541: 
 3542:     #need to make sure we have the correct data for later EXT calls, 
 3543:     #thus invalidate the cache
 3544:     &Apache::lonnet::devalidatecourseresdata(
 3545:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3546:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3547:     &Apache::lonnet::clear_EXT_cache_status();
 3548: 
 3549:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3550: 
 3551:     #view individual student submission form - called using Javascript viewOneStudent
 3552:     $result.=&jscriptNform($symb);
 3553: 
 3554:     #beginning of class grading form
 3555:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3556:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3557: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3558: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3559: 	&build_section_inputs().
 3560: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3561: 
 3562:     my ($common_header,$specific_header);
 3563:     if ($env{'form.section'} eq 'all') {
 3564: 	$common_header = &mt('Assign Common Grade to Class');
 3565:         $specific_header = &mt('Assign Grade to Specific Students in Class');
 3566:     } elsif ($env{'form.section'} eq 'none') {
 3567:         $common_header = &mt('Assign Common Grade to Students in no Section');
 3568: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
 3569:     } else {
 3570:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3571:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3572: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3573:     }
 3574:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
 3575:     #radio buttons/text box for assigning points for a section or class.
 3576:     #handles different parts of a problem
 3577:     my $res_error;
 3578:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3579:     if ($res_error) {
 3580:         return &navmap_errormsg();
 3581:     }
 3582:     my %weight = ();
 3583:     my $ctsparts = 0;
 3584:     my %seen = ();
 3585:     my @part_response_id = &flatten_responseType($responseType);
 3586:     foreach my $part_response_id (@part_response_id) {
 3587:     	my ($partid,$respid) = @{ $part_response_id };
 3588: 	my $part_resp = join('_',@{ $part_response_id });
 3589: 	next if $seen{$partid};
 3590: 	$seen{$partid}++;
 3591: 	my $handgrade=$$handgrade{$part_resp};
 3592: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3593: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3594: 
 3595: 	my $display_part=&get_display_part($partid,$symb);
 3596: 	my $radio.='<table border="0"><tr>';  
 3597: 	my $ctr = 0;
 3598: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3599: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3600: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3601: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3602: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3603: 	    $ctr++;
 3604: 	}
 3605: 	$radio.='</tr></table>';
 3606: 	my $line = '<input type="text" name="TEXTVAL_'.
 3607: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 3608: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3609: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3610:         $line.= '<td><b>'.&mt('Grade Status').':</b>'.
 3611:             '<select name="SELVAL_'.$partid.'" '.
 3612:             'onchange="javascript:writeRadText(\''.$partid.'\','.
 3613:                 $weight{$partid}.')"> '.
 3614: 	    '<option selected="selected"> </option>'.
 3615: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3616: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3617: 	    '</select></td>'.
 3618:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3619: 	$line.='<input type="hidden" name="partid_'.
 3620: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3621: 	$line.='<input type="hidden" name="weight_'.
 3622: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3623: 
 3624: 	$result.=
 3625: 	    &Apache::loncommon::start_data_table_row()."\n".
 3626: 	    '<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>'.
 3627: 	    &Apache::loncommon::end_data_table_row()."\n";
 3628: 	$ctsparts++;
 3629:     }
 3630:     $result.=&Apache::loncommon::end_data_table()."\n".
 3631: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3632:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3633: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 3634: 
 3635:     #table listing all the students in a section/class
 3636:     #header of table
 3637:     $result.= '<h3>'.$specific_header.'</h3>'.
 3638:               &Apache::loncommon::start_data_table().
 3639: 	      &Apache::loncommon::start_data_table_header_row().
 3640: 	      '<th>'.&mt('No.').'</th>'.
 3641: 	      '<th>'.&nameUserString('header')."</th>\n";
 3642:     my $partserror;
 3643:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3644:     if ($partserror) {
 3645:         return &navmap_errormsg();
 3646:     }
 3647:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3648:     my @partids = ();
 3649:     foreach my $part (@parts) {
 3650: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3651:         my $narrowtext = &mt('Tries');
 3652: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3653: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3654: 	my ($partid) = &split_part_type($part);
 3655:         push(@partids,$partid);
 3656: #
 3657: # FIXME: Looks like $display looks at English text
 3658: #
 3659: 	my $display_part=&get_display_part($partid,$symb);
 3660: 	if ($display =~ /^Partial Credit Factor/) {
 3661: 	    $result.='<th>'.
 3662: 		&mt('Score Part: [_1][_2](weight = [_3])',
 3663: 		    $display_part,'<br />',$weight{$partid}).'</th>'."\n";
 3664: 	    next;
 3665: 	    
 3666: 	} else {
 3667: 	    if ($display =~ /Problem Status/) {
 3668: 		my $grade_status_mt = &mt('Grade Status');
 3669: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3670: 	    }
 3671: 	    my $part_mt = &mt('Part:');
 3672: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3673: 	}
 3674: 
 3675: 	$result.='<th>'.$display.'</th>'."\n";
 3676:     }
 3677:     $result.=&Apache::loncommon::end_data_table_header_row();
 3678: 
 3679:     my %last_resets = 
 3680: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3681: 
 3682:     #get info for each student
 3683:     #list all the students - with points and grade status
 3684:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3685:     my $ctr = 0;
 3686:     foreach (sort 
 3687: 	     {
 3688: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3689: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3690: 		 }
 3691: 		 return $a cmp $b;
 3692: 	     } (keys(%$fullname))) {
 3693: 	$ctr++;
 3694: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3695: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3696:     }
 3697:     $result.=&Apache::loncommon::end_data_table();
 3698:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3699:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3700: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 3701:     if (scalar(%$fullname) eq 0) {
 3702: 	my $colspan=3+scalar(@parts);
 3703: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3704:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3705: 	$result='<span class="LC_warning">'.
 3706: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3707: 	        $section_display, $stu_status).
 3708: 	    '</span>';
 3709:     }
 3710:     return $result;
 3711: }
 3712: 
 3713: #--- call by previous routine to display each student
 3714: sub viewstudentgrade {
 3715:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3716:     my ($uname,$udom) = split(/:/,$student);
 3717:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3718:     my %aggregates = (); 
 3719:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3720: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3721: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3722: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3723: 	'\');" target="_self">'.$fullname.'</a> '.
 3724: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3725:     $student=~s/:/_/; # colon doen't work in javascript for names
 3726:     foreach my $apart (@$parts) {
 3727: 	my ($part,$type) = &split_part_type($apart);
 3728: 	my $score=$record{"resource.$part.$type"};
 3729:         $result.='<td align="center">';
 3730:         my ($aggtries,$totaltries);
 3731:         unless (exists($aggregates{$part})) {
 3732: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3733: 
 3734: 	    $aggtries = $totaltries;
 3735:             if ($$last_resets{$part}) {  
 3736:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3737: 					   $part);
 3738:             }
 3739:             $result.='<input type="hidden" name="'.
 3740:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3741:             $result.='<input type="hidden" name="'.
 3742:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3743:             $aggregates{$part} = 1;
 3744:         }
 3745: 	if ($type eq 'awarded') {
 3746: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3747: 	    $result.='<input type="hidden" name="'.
 3748: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3749: 	    $result.='<input type="text" name="'.
 3750: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3751:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3752: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3753: 	} elsif ($type eq 'solved') {
 3754: 	    my ($status,$foo)=split(/_/,$score,2);
 3755: 	    $status = 'nothing' if ($status eq '');
 3756: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3757: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3758: 	    $result.='&nbsp;<select name="'.
 3759: 		'GD_'.$student.'_'.$part.'_solved" '.
 3760:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3761: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3762: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3763: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3764: 	    $result.="</select>&nbsp;</td>\n";
 3765: 	} else {
 3766: 	    $result.='<input type="hidden" name="'.
 3767: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3768: 		    "\n";
 3769: 	    $result.='<input type="text" name="'.
 3770: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3771: 		'value="'.$score.'" size="4" /></td>'."\n";
 3772: 	}
 3773:     }
 3774:     $result.=&Apache::loncommon::end_data_table_row();
 3775:     return $result;
 3776: }
 3777: 
 3778: #--- change scores for all the students in a section/class
 3779: #    record does not get update if unchanged
 3780: sub editgrades {
 3781:     my ($request,$symb) = @_;
 3782: 
 3783:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3784:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3785:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3786: 
 3787:     my $result= &Apache::loncommon::start_data_table().
 3788: 	&Apache::loncommon::start_data_table_header_row().
 3789: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3790: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3791:     my %scoreptr = (
 3792: 		    'correct'  =>'correct_by_override',
 3793: 		    'incorrect'=>'incorrect_by_override',
 3794: 		    'excused'  =>'excused',
 3795: 		    'ungraded' =>'ungraded_attempted',
 3796:                     'credited' =>'credit_attempted',
 3797: 		    'nothing'  => '',
 3798: 		    );
 3799:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3800: 
 3801:     my (@partid);
 3802:     my %weight = ();
 3803:     my %columns = ();
 3804:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3805: 
 3806:     my $partserror;
 3807:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3808:     if ($partserror) {
 3809:         return &navmap_errormsg();
 3810:     }
 3811:     my $header;
 3812:     while ($ctr < $env{'form.totalparts'}) {
 3813: 	my $partid = $env{'form.partid_'.$ctr};
 3814: 	push(@partid,$partid);
 3815: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3816: 	$ctr++;
 3817:     }
 3818:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3819:     foreach my $partid (@partid) {
 3820: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3821: 	    '<th align="center">'.&mt('New Score').'</th>';
 3822: 	$columns{$partid}=2;
 3823: 	foreach my $stores (@parts) {
 3824: 	    my ($part,$type) = &split_part_type($stores);
 3825: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3826: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3827: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3828: 	    $display =~ s/\[Part: \Q$part\E\]//;
 3829:             my $narrowtext = &mt('Tries');
 3830: 	    $display =~ s/Number of Attempts/$narrowtext/;
 3831: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 3832: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 3833: 	    $columns{$partid}+=2;
 3834: 	}
 3835:     }
 3836:     foreach my $partid (@partid) {
 3837: 	my $display_part=&get_display_part($partid,$symb);
 3838: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3839: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3840: 	    '</th>';
 3841: 
 3842:     }
 3843:     $result .= &Apache::loncommon::end_data_table_header_row().
 3844: 	&Apache::loncommon::start_data_table_header_row().
 3845: 	$header.
 3846: 	&Apache::loncommon::end_data_table_header_row();
 3847:     my @noupdate;
 3848:     my ($updateCtr,$noupdateCtr) = (1,1);
 3849:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3850: 	my $line;
 3851: 	my $user = $env{'form.ctr'.$i};
 3852: 	my ($uname,$udom)=split(/:/,$user);
 3853: 	my %newrecord;
 3854: 	my $updateflag = 0;
 3855: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3856: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3857: 	if (!&canmodify($usec)) {
 3858: 	    my $numcols=scalar(@partid)*4+2;
 3859: 	    push(@noupdate,
 3860: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 3861: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 3862: 	    next;
 3863: 	}
 3864:         my %aggregate = ();
 3865:         my $aggregateflag = 0;
 3866: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3867: 	foreach (@partid) {
 3868: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3869: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3870: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3871: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3872: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3873: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3874: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3875: 	    my $score;
 3876: 	    if ($partial eq '') {
 3877: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3878: 	    } elsif ($partial > 0) {
 3879: 		$score = 'correct_by_override';
 3880: 	    } elsif ($partial == 0) {
 3881: 		$score = 'incorrect_by_override';
 3882: 	    }
 3883: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3884: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3885: 
 3886: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3887: 		"$env{'user.name'}:$env{'user.domain'}";
 3888: 	    if ($dropMenu eq 'reset status' &&
 3889: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3890: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3891: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3892: 		$newrecord{'resource.'.$_.'.award'} = '';
 3893: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3894: 		$updateflag = 1;
 3895:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3896:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3897:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3898:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3899:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3900:                     $aggregateflag = 1;
 3901:                 }
 3902: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3903: 		$updateflag = 1;
 3904: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3905: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3906: 		$rec_update++;
 3907: 	    }
 3908: 
 3909: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3910: 		'<td align="center">'.$awarded.
 3911: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3912: 
 3913: 
 3914: 	    my $partid=$_;
 3915: 	    foreach my $stores (@parts) {
 3916: 		my ($part,$type) = &split_part_type($stores);
 3917: 		if ($part !~ m/^\Q$partid\E/) { next;}
 3918: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 3919: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 3920: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 3921: 		if ($awarded ne '' && $awarded ne $old_aw) {
 3922: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 3923: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3924: 		    $updateflag=1;
 3925: 		}
 3926: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3927: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 3928: 	    }
 3929: 	}
 3930: 	$line.="\n";
 3931: 
 3932: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3933: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3934: 
 3935: 	if ($updateflag) {
 3936: 	    $count++;
 3937: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 3938: 				    $udom,$uname);
 3939: 
 3940: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 3941: 					      $cnum,$udom,$uname)) {
 3942: 		# need to figure out if should be in queue.
 3943: 		my %record =  
 3944: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3945: 					     $udom,$uname);
 3946: 		my $all_graded = 1;
 3947: 		my $none_graded = 1;
 3948: 		foreach my $part (@parts) {
 3949: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 3950: 			$all_graded = 0;
 3951: 		    } else {
 3952: 			$none_graded = 0;
 3953: 		    }
 3954: 		}
 3955: 
 3956: 		if ($all_graded || $none_graded) {
 3957: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 3958: 							   $symb,$cdom,$cnum,
 3959: 							   $udom,$uname);
 3960: 		}
 3961: 	    }
 3962: 
 3963: 	    $result.=&Apache::loncommon::start_data_table_row().
 3964: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 3965: 		&Apache::loncommon::end_data_table_row();
 3966: 	    $updateCtr++;
 3967: 	} else {
 3968: 	    push(@noupdate,
 3969: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 3970: 	    $noupdateCtr++;
 3971: 	}
 3972:         if ($aggregateflag) {
 3973:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3974: 				  $cdom,$cnum);
 3975:         }
 3976:     }
 3977:     if (@noupdate) {
 3978: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 3979: 	my $numcols=scalar(@partid)*4+2;
 3980: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 3981: 	    '<td align="center" colspan="'.$numcols.'">'.
 3982: 	    &mt('No Changes Occurred For the Students Below').
 3983: 	    '</td>'.
 3984: 	    &Apache::loncommon::end_data_table_row();
 3985: 	foreach my $line (@noupdate) {
 3986: 	    $result.=
 3987: 		&Apache::loncommon::start_data_table_row().
 3988: 		$line.
 3989: 		&Apache::loncommon::end_data_table_row();
 3990: 	}
 3991:     }
 3992:     $result .= &Apache::loncommon::end_data_table();
 3993:     my $msg = '<p><b>'.
 3994: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 3995: 	    $rec_update,$count).'</b><br />'.
 3996: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 3997: 	'</b></p>';
 3998:     return $title.$msg.$result;
 3999: }
 4000: 
 4001: sub split_part_type {
 4002:     my ($partstr) = @_;
 4003:     my ($temp,@allparts)=split(/_/,$partstr);
 4004:     my $type=pop(@allparts);
 4005:     my $part=join('_',@allparts);
 4006:     return ($part,$type);
 4007: }
 4008: 
 4009: #------------- end of section for handling grading by section/class ---------
 4010: #
 4011: #----------------------------------------------------------------------------
 4012: 
 4013: 
 4014: #----------------------------------------------------------------------------
 4015: #
 4016: #-------------------------- Next few routines handles grading by csv upload
 4017: #
 4018: #--- Javascript to handle csv upload
 4019: sub csvupload_javascript_reverse_associate {
 4020:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4021:     my $error2=&mt('You need to specify at least one grading field');
 4022:   return(<<ENDPICK);
 4023:   function verify(vf) {
 4024:     var foundsomething=0;
 4025:     var founduname=0;
 4026:     var foundID=0;
 4027:     for (i=0;i<=vf.nfields.value;i++) {
 4028:       tw=eval('vf.f'+i+'.selectedIndex');
 4029:       if (i==0 && tw!=0) { foundID=1; }
 4030:       if (i==1 && tw!=0) { founduname=1; }
 4031:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 4032:     }
 4033:     if (founduname==0 && foundID==0) {
 4034: 	alert('$error1');
 4035: 	return;
 4036:     }
 4037:     if (foundsomething==0) {
 4038: 	alert('$error2');
 4039: 	return;
 4040:     }
 4041:     vf.submit();
 4042:   }
 4043:   function flip(vf,tf) {
 4044:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4045:     var i;
 4046:     for (i=0;i<=vf.nfields.value;i++) {
 4047:       //can not pick the same destination field for both name and domain
 4048:       if (((i ==0)||(i ==1)) && 
 4049:           ((tf==0)||(tf==1)) && 
 4050:           (i!=tf) &&
 4051:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4052:         eval('vf.f'+i+'.selectedIndex=0;')
 4053:       }
 4054:     }
 4055:   }
 4056: ENDPICK
 4057: }
 4058: 
 4059: sub csvupload_javascript_forward_associate {
 4060:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4061:     my $error2=&mt('You need to specify at least one grading field');
 4062:   return(<<ENDPICK);
 4063:   function verify(vf) {
 4064:     var foundsomething=0;
 4065:     var founduname=0;
 4066:     var foundID=0;
 4067:     for (i=0;i<=vf.nfields.value;i++) {
 4068:       tw=eval('vf.f'+i+'.selectedIndex');
 4069:       if (tw==1) { foundID=1; }
 4070:       if (tw==2) { founduname=1; }
 4071:       if (tw>3) { foundsomething=1; }
 4072:     }
 4073:     if (founduname==0 && foundID==0) {
 4074: 	alert('$error1');
 4075: 	return;
 4076:     }
 4077:     if (foundsomething==0) {
 4078: 	alert('$error2');
 4079: 	return;
 4080:     }
 4081:     vf.submit();
 4082:   }
 4083:   function flip(vf,tf) {
 4084:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4085:     var i;
 4086:     //can not pick the same destination field twice
 4087:     for (i=0;i<=vf.nfields.value;i++) {
 4088:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4089:         eval('vf.f'+i+'.selectedIndex=0;')
 4090:       }
 4091:     }
 4092:   }
 4093: ENDPICK
 4094: }
 4095: 
 4096: sub csvuploadmap_header {
 4097:     my ($request,$symb,$datatoken,$distotal)= @_;
 4098:     my $javascript;
 4099:     if ($env{'form.upfile_associate'} eq 'reverse') {
 4100: 	$javascript=&csvupload_javascript_reverse_associate();
 4101:     } else {
 4102: 	$javascript=&csvupload_javascript_forward_associate();
 4103:     }
 4104: 
 4105:     $symb = &Apache::lonenc::check_encrypt($symb);
 4106:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
 4107:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
 4108:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
 4109:     my $reverse=&mt("Reverse Association");
 4110:     $request->print(<<ENDPICK);
 4111: <br />
 4112: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 4113: <input type="hidden" name="associate"  value="" />
 4114: <input type="hidden" name="phase"      value="three" />
 4115: <input type="hidden" name="datatoken"  value="$datatoken" />
 4116: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 4117: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 4118: <input type="hidden" name="upfile_associate" 
 4119:                                        value="$env{'form.upfile_associate'}" />
 4120: <input type="hidden" name="symb"       value="$symb" />
 4121: <input type="hidden" name="command"    value="csvuploadoptions" />
 4122: <hr />
 4123: ENDPICK
 4124:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
 4125:     return '';
 4126: 
 4127: }
 4128: 
 4129: sub csvupload_fields {
 4130:     my ($symb,$errorref) = @_;
 4131:     my (@parts) = &getpartlist($symb,$errorref);
 4132:     if (ref($errorref)) {
 4133:         if ($$errorref) {
 4134:             return;
 4135:         }
 4136:     }
 4137: 
 4138:     my @fields=(['ID','Student/Employee ID'],
 4139: 		['username','Student Username'],
 4140: 		['domain','Student Domain']);
 4141:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4142:     foreach my $part (sort(@parts)) {
 4143: 	my @datum;
 4144: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 4145: 	my $name=$part;
 4146: 	if  (!$display) { $display = $name; }
 4147: 	@datum=($name,$display);
 4148: 	if ($name=~/^stores_(.*)_awarded/) {
 4149: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 4150: 	}
 4151: 	push(@fields,\@datum);
 4152:     }
 4153:     return (@fields);
 4154: }
 4155: 
 4156: sub csvuploadmap_footer {
 4157:     my ($request,$i,$keyfields) =@_;
 4158:     my $buttontext = &mt('Assign Grades');
 4159:     $request->print(<<ENDPICK);
 4160: </table>
 4161: <input type="hidden" name="nfields" value="$i" />
 4162: <input type="hidden" name="keyfields" value="$keyfields" />
 4163: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
 4164: </form>
 4165: ENDPICK
 4166: }
 4167: 
 4168: sub checkforfile_js {
 4169:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 4170:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
 4171:     function checkUpload(formname) {
 4172: 	if (formname.upfile.value == "") {
 4173: 	    alert("$alertmsg");
 4174: 	    return false;
 4175: 	}
 4176: 	formname.submit();
 4177:     }
 4178: CSVFORMJS
 4179:     return $result;
 4180: }
 4181: 
 4182: sub upcsvScores_form {
 4183:     my ($request,$symb) = @_;
 4184:     if (!$symb) {return '';}
 4185:     my $result=&checkforfile_js();
 4186:     $result.=&Apache::loncommon::start_data_table().
 4187:              &Apache::loncommon::start_data_table_header_row().
 4188:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
 4189:              &Apache::loncommon::end_data_table_header_row().
 4190:              &Apache::loncommon::start_data_table_row().'<td>';
 4191:     my $upload=&mt("Upload Scores");
 4192:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 4193:     my $ignore=&mt('Ignore First Line');
 4194:     $symb = &Apache::lonenc::check_encrypt($symb);
 4195:     $result.=<<ENDUPFORM;
 4196: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4197: <input type="hidden" name="symb" value="$symb" />
 4198: <input type="hidden" name="command" value="csvuploadmap" />
 4199: $upfile_select
 4200: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 4201: </form>
 4202: ENDUPFORM
 4203:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 4204:                            &mt("How do I create a CSV file from a spreadsheet")).
 4205:              '</td>'.
 4206:             &Apache::loncommon::end_data_table_row().
 4207:             &Apache::loncommon::end_data_table();
 4208:     return $result;
 4209: }
 4210: 
 4211: 
 4212: sub csvuploadmap {
 4213:     my ($request,$symb)= @_;
 4214:     if (!$symb) {return '';}
 4215: 
 4216:     my $datatoken;
 4217:     if (!$env{'form.datatoken'}) {
 4218: 	$datatoken=&Apache::loncommon::upfile_store($request);
 4219:     } else {
 4220: 	$datatoken=$env{'form.datatoken'};
 4221: 	&Apache::loncommon::load_tmp_file($request);
 4222:     }
 4223:     my @records=&Apache::loncommon::upfile_record_sep();
 4224:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 4225:     my ($i,$keyfields);
 4226:     if (@records) {
 4227:         my $fieldserror;
 4228: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 4229:         if ($fieldserror) {
 4230:             $request->print(&navmap_errormsg());
 4231:             return;
 4232:         }
 4233: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 4234: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 4235: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 4236: 							  \@fields);
 4237: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 4238: 	    chop($keyfields);
 4239: 	} else {
 4240: 	    unshift(@fields,['none','']);
 4241: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 4242: 							    \@fields);
 4243:             foreach my $rec (@records) {
 4244:                 my %temp = &Apache::loncommon::record_sep($rec);
 4245:                 if (%temp) {
 4246:                     $keyfields=join(',',sort(keys(%temp)));
 4247:                     last;
 4248:                 }
 4249:             }
 4250: 	}
 4251:     }
 4252:     &csvuploadmap_footer($request,$i,$keyfields);
 4253: 
 4254:     return '';
 4255: }
 4256: 
 4257: sub csvuploadoptions {
 4258:     my ($request,$symb)= @_;
 4259:     my $overwrite=&mt('Overwrite any existing score');
 4260:     $request->print(<<ENDPICK);
 4261: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4262: <input type="hidden" name="command"    value="csvuploadassign" />
 4263: <p>
 4264: <label>
 4265:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4266:    $overwrite
 4267: </label>
 4268: </p>
 4269: ENDPICK
 4270:     my %fields=&get_fields();
 4271:     if (!defined($fields{'domain'})) {
 4272: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4273: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
 4274:     }
 4275:     foreach my $key (sort(keys(%env))) {
 4276: 	if ($key !~ /^form\.(.*)$/) { next; }
 4277: 	my $cleankey=$1;
 4278: 	if ($cleankey eq 'command') { next; }
 4279: 	$request->print('<input type="hidden" name="'.$cleankey.
 4280: 			'"  value="'.$env{$key}.'" />'."\n");
 4281:     }
 4282:     # FIXME do a check for any duplicated user ids...
 4283:     # FIXME do a check for any invalid user ids?...
 4284:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
 4285: <hr /></form>'."\n");
 4286:     return '';
 4287: }
 4288: 
 4289: sub get_fields {
 4290:     my %fields;
 4291:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4292:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4293: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4294: 	    if ($env{'form.f'.$i} ne 'none') {
 4295: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4296: 	    }
 4297: 	} else {
 4298: 	    if ($env{'form.f'.$i} ne 'none') {
 4299: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4300: 	    }
 4301: 	}
 4302:     }
 4303:     return %fields;
 4304: }
 4305: 
 4306: sub csvuploadassign {
 4307:     my ($request,$symb)= @_;
 4308:     if (!$symb) {return '';}
 4309:     my $error_msg = '';
 4310:     &Apache::loncommon::load_tmp_file($request);
 4311:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4312:     my %fields=&get_fields();
 4313:     my $courseid=$env{'request.course.id'};
 4314:     my ($classlist) = &getclasslist('all',0);
 4315:     my @notallowed;
 4316:     my @skipped;
 4317:     my @warnings;
 4318:     my $countdone=0;
 4319:     foreach my $grade (@gradedata) {
 4320: 	my %entries=&Apache::loncommon::record_sep($grade);
 4321: 	my $domain;
 4322: 	if ($entries{$fields{'domain'}}) {
 4323: 	    $domain=$entries{$fields{'domain'}};
 4324: 	} else {
 4325: 	    $domain=$env{'form.default_domain'};
 4326: 	}
 4327: 	$domain=~s/\s//g;
 4328: 	my $username=$entries{$fields{'username'}};
 4329: 	$username=~s/\s//g;
 4330: 	if (!$username) {
 4331: 	    my $id=$entries{$fields{'ID'}};
 4332: 	    $id=~s/\s//g;
 4333: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4334: 	    $username=$ids{$id};
 4335: 	}
 4336: 	if (!exists($$classlist{"$username:$domain"})) {
 4337: 	    my $id=$entries{$fields{'ID'}};
 4338: 	    $id=~s/\s//g;
 4339: 	    if ($id) {
 4340: 		push(@skipped,"$id:$domain");
 4341: 	    } else {
 4342: 		push(@skipped,"$username:$domain");
 4343: 	    }
 4344: 	    next;
 4345: 	}
 4346: 	my $usec=$classlist->{"$username:$domain"}[5];
 4347: 	if (!&canmodify($usec)) {
 4348: 	    push(@notallowed,"$username:$domain");
 4349: 	    next;
 4350: 	}
 4351: 	my %points;
 4352: 	my %grades;
 4353: 	foreach my $dest (keys(%fields)) {
 4354: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4355: 		$dest eq 'domain') { next; }
 4356: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4357: 	    if ($dest=~/stores_(.*)_points/) {
 4358: 		my $part=$1;
 4359: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4360: 					      $symb,$domain,$username);
 4361:                 if ($wgt) {
 4362:                     $entries{$fields{$dest}}=~s/\s//g;
 4363:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4364:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4365:                                           : 'correct_by_override';
 4366:                     if ($pcr>1) {
 4367:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
 4368:                     }
 4369:                     $grades{"resource.$part.awarded"}=$pcr;
 4370:                     $grades{"resource.$part.solved"}=$award;
 4371:                     $points{$part}=1;
 4372:                 } else {
 4373:                     $error_msg = "<br />" .
 4374:                         &mt("Some point values were assigned"
 4375:                             ." for problems with a weight "
 4376:                             ."of zero. These values were "
 4377:                             ."ignored.");
 4378:                 }
 4379: 	    } else {
 4380: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4381: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4382: 		my $store_key=$dest;
 4383: 		$store_key=~s/^stores/resource/;
 4384: 		$store_key=~s/_/\./g;
 4385: 		$grades{$store_key}=$entries{$fields{$dest}};
 4386: 	    }
 4387: 	}
 4388: 	if (! %grades) { 
 4389:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4390:         } else {
 4391: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4392: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4393: 					   $env{'request.course.id'},
 4394: 					   $domain,$username);
 4395: 	   if ($result eq 'ok') {
 4396: # Successfully stored
 4397: 	      $request->print('.');
 4398: # Remove from grading queue
 4399:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
 4400:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
 4401:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
 4402:                                              $domain,$username);
 4403:               $countdone++;
 4404:            } else {
 4405: 	      $request->print("<p><span class=\"LC_error\">".
 4406:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4407:                                   "$username:$domain",$result)."</span></p>");
 4408: 	   }
 4409: 	   $request->rflush();
 4410:         }
 4411:     }
 4412:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 4413:     if (@warnings) {
 4414:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
 4415:         $request->print(join(', ',@warnings));
 4416:     }
 4417:     if (@skipped) {
 4418: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 4419:         $request->print(join(', ',@skipped));
 4420:     }
 4421:     if (@notallowed) {
 4422: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 4423: 	$request->print(join(', ',@notallowed));
 4424:     }
 4425:     $request->print("<br />\n");
 4426:     return $error_msg;
 4427: }
 4428: #------------- end of section for handling csv file upload ---------
 4429: #
 4430: #-------------------------------------------------------------------
 4431: #
 4432: #-------------- Next few routines handle grading by page/sequence
 4433: #
 4434: #--- Select a page/sequence and a student to grade
 4435: sub pickStudentPage {
 4436:     my ($request,$symb) = @_;
 4437: 
 4438:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4439:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
 4440: 
 4441: function checkPickOne(formname) {
 4442:     if (radioSelection(formname.student) == null) {
 4443: 	alert("$alertmsg");
 4444: 	return;
 4445:     }
 4446:     ptr = pullDownSelection(formname.selectpage);
 4447:     formname.page.value = formname["page"+ptr].value;
 4448:     formname.title.value = formname["title"+ptr].value;
 4449:     formname.submit();
 4450: }
 4451: 
 4452: LISTJAVASCRIPT
 4453:     &commonJSfunctions($request);
 4454: 
 4455:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4456:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4457:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4458: 
 4459:     my $result='<h3><span class="LC_info">&nbsp;'.
 4460: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4461: 
 4462:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4463:     my $map_error;
 4464:     my ($titles,$symbx) = &getSymbMap($map_error);
 4465:     if ($map_error) {
 4466:         $request->print(&navmap_errormsg());
 4467:         return; 
 4468:     }
 4469:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4470: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4471: #    my $type=($curpage =~ /\.(page|sequence)/);
 4472: 
 4473:     # Collection of hidden fields
 4474:     my $ctr=0;
 4475:     foreach (@$titles) {
 4476:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4477:         $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4478:         $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4479:         $ctr++;
 4480:     }
 4481:     $result.='<input type="hidden" name="page" />'."\n".
 4482:         '<input type="hidden" name="title" />'."\n";
 4483: 
 4484:     $result.=&build_section_inputs();
 4485:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4486:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4487: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4488: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 4489: 
 4490:     # Show grading options
 4491:     $result.=&Apache::lonhtmlcommon::start_pick_box();
 4492:     my $select = '<select name="selectpage">'."\n";
 4493:     $ctr=0;
 4494:     foreach (@$titles) {
 4495: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4496: 	$select.='<option value="'.$ctr.'"'.
 4497: 	    ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
 4498: 	    '>'.$showtitle.'</option>'."\n";
 4499: 	$ctr++;
 4500:     }
 4501:     $select.= '</select>';
 4502: 
 4503:     $result.=
 4504:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
 4505:        .$select
 4506:        .&Apache::lonhtmlcommon::row_closure();
 4507: 
 4508:     $result.=
 4509:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
 4510:        .'<label><input type="radio" name="vProb" value="no"'
 4511:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
 4512:        .'<label><input type="radio" name="vProb" value="yes" />'
 4513:            .&mt('yes').'</label>'."\n"
 4514:        .&Apache::lonhtmlcommon::row_closure();
 4515: 
 4516:     $result.=
 4517:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
 4518:        .'<label><input type="radio" name="lastSub" value="none" /> '
 4519:            .&mt('none').' </label>'."\n"
 4520:        .'<label><input type="radio" name="lastSub" value="datesub"'
 4521:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
 4522:        .'<label><input type="radio" name="lastSub" value="all" /> '
 4523:            .&mt('all submissions with details').' </label>'
 4524:        .&Apache::lonhtmlcommon::row_closure();
 4525:     
 4526:     $result.=
 4527:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
 4528:        .'<input type="text" name="CODE" value="" />'
 4529:        .&Apache::lonhtmlcommon::row_closure(1)
 4530:        .&Apache::lonhtmlcommon::end_pick_box();
 4531: 
 4532:     # Show list of students to select for grading
 4533:     $result.='<br /><input type="button" '.
 4534:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4535: 
 4536:     $request->print($result);
 4537: 
 4538:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4539: 	&Apache::loncommon::start_data_table().
 4540: 	&Apache::loncommon::start_data_table_header_row().
 4541: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4542: 	'<th>'.&nameUserString('header').'</th>'.
 4543: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4544: 	'<th>'.&nameUserString('header').'</th>'.
 4545: 	&Apache::loncommon::end_data_table_header_row();
 4546:  
 4547:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4548:     my $ptr = 1;
 4549:     foreach my $student (sort 
 4550: 			 {
 4551: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4552: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4553: 			     }
 4554: 			     return $a cmp $b;
 4555: 			 } (keys(%$fullname))) {
 4556: 	my ($uname,$udom) = split(/:/,$student);
 4557: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4558:                                   : '</td>');
 4559: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4560: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4561: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4562: 	$studentTable.=
 4563: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4564:                          : '');
 4565: 	$ptr++;
 4566:     }
 4567:     if ($ptr%2 == 0) {
 4568: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4569: 	    &Apache::loncommon::end_data_table_row();
 4570:     }
 4571:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4572:     $studentTable.='<input type="button" '.
 4573:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4574: 
 4575:     $request->print($studentTable);
 4576: 
 4577:     return '';
 4578: }
 4579: 
 4580: sub getSymbMap {
 4581:     my ($map_error) = @_;
 4582:     my $navmap = Apache::lonnavmaps::navmap->new();
 4583:     unless (ref($navmap)) {
 4584:         if (ref($map_error)) {
 4585:             $$map_error = 'navmap';
 4586:         }
 4587:         return;
 4588:     }
 4589:     my %symbx = ();
 4590:     my @titles = ();
 4591:     my $minder = 0;
 4592: 
 4593:     # Gather every sequence that has problems.
 4594:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4595: 					       1,0,1);
 4596:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4597: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4598: 	    my $title = $minder.'.'.
 4599: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4600: 	    push(@titles, $title); # minder in case two titles are identical
 4601: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4602: 	    $minder++;
 4603: 	}
 4604:     }
 4605:     return \@titles,\%symbx;
 4606: }
 4607: 
 4608: #
 4609: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4610: sub displayPage {
 4611:     my ($request,$symb) = @_;
 4612:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4613:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4614:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4615:     my $pageTitle = $env{'form.page'};
 4616:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4617:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4618:     my $usec=$classlist->{$env{'form.student'}}[5];
 4619: 
 4620:     #need to make sure we have the correct data for later EXT calls, 
 4621:     #thus invalidate the cache
 4622:     &Apache::lonnet::devalidatecourseresdata(
 4623:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4624:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4625:     &Apache::lonnet::clear_EXT_cache_status();
 4626: 
 4627:     if (!&canview($usec)) {
 4628:         $request->print(
 4629:             '<span class="LC_warning">'.
 4630:             &mt('Unable to view requested student. ([_1])',
 4631:                     $env{'form.student'}).
 4632:             '</span>');
 4633:         return;
 4634:     }
 4635:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4636:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4637: 	'</h3>'."\n";
 4638:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4639:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4640: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4641:     } else {
 4642: 	delete($env{'form.CODE'});
 4643:     }
 4644:     &sub_page_js($request);
 4645:     $request->print($result);
 4646: 
 4647:     my $navmap = Apache::lonnavmaps::navmap->new();
 4648:     unless (ref($navmap)) {
 4649:         $request->print(&navmap_errormsg());
 4650:         return;
 4651:     }
 4652:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4653:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4654:     if (!$map) {
 4655: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4656: 	return; 
 4657:     }
 4658:     my $iterator = $navmap->getIterator($map->map_start(),
 4659: 					$map->map_finish());
 4660: 
 4661:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4662: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4663: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4664: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4665: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4666: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4667: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4668: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
 4669: 
 4670:     if (defined($env{'form.CODE'})) {
 4671: 	$studentTable.=
 4672: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4673:     }
 4674:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4675: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4676: 
 4677:     $studentTable.='&nbsp;<span class="LC_info">'.
 4678:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 4679:         '</span>'."\n".
 4680: 	&Apache::loncommon::start_data_table().
 4681: 	&Apache::loncommon::start_data_table_header_row().
 4682: 	'<th>'.&mt('Prob.').'</th>'.
 4683: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4684: 	&Apache::loncommon::end_data_table_header_row();
 4685: 
 4686:     &Apache::lonxml::clear_problem_counter();
 4687:     my ($depth,$question,$prob) = (1,1,1);
 4688:     $iterator->next(); # skip the first BEGIN_MAP
 4689:     my $curRes = $iterator->next(); # for "current resource"
 4690:     while ($depth > 0) {
 4691:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4692:         if($curRes == $iterator->END_MAP) { $depth--; }
 4693: 
 4694:         if (ref($curRes) && $curRes->is_problem()) {
 4695: 	    my $parts = $curRes->parts();
 4696:             my $title = $curRes->compTitle();
 4697: 	    my $symbx = $curRes->symb();
 4698: 	    $studentTable.=
 4699: 		&Apache::loncommon::start_data_table_row().
 4700: 		'<td align="center" valign="top" >'.$prob.
 4701: 		(scalar(@{$parts}) == 1 ? '' 
 4702: 		                        : '<br />('.&mt('[_1]parts',
 4703: 							scalar(@{$parts}).'&nbsp;').')'
 4704: 		 ).
 4705: 		 '</td>';
 4706: 	    $studentTable.='<td valign="top">';
 4707: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4708: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4709: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4710: 					     undef,'both',\%form);
 4711: 	    } else {
 4712: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4713: 		$companswer =~ s|<form(.*?)>||g;
 4714: 		$companswer =~ s|</form>||g;
 4715: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4716: #		    $companswer =~ s/$1/ /ms;
 4717: #		    $request->print('match='.$1."<br />\n");
 4718: #		}
 4719: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4720: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 4721: 	    }
 4722: 
 4723: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4724: 
 4725: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4726: 		if ($record{'version'} eq '') {
 4727: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4728: 		} else {
 4729: 		    my %responseType = ();
 4730: 		    foreach my $partid (@{$parts}) {
 4731: 			my @responseIds =$curRes->responseIds($partid);
 4732: 			my @responseType =$curRes->responseType($partid);
 4733: 			my %responseIds;
 4734: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4735: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4736: 			}
 4737: 			$responseType{$partid} = \%responseIds;
 4738: 		    }
 4739: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4740: 
 4741: 		}
 4742: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4743: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4744: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4745: 									$env{'request.course.id'},
 4746: 									'','.submission');
 4747:  
 4748: 	    }
 4749: 	    if (&canmodify($usec)) {
 4750:             $studentTable.=&gradeBox_start();
 4751: 		foreach my $partid (@{$parts}) {
 4752: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4753: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4754: 		    $question++;
 4755: 		}
 4756:             $studentTable.=&gradeBox_end();
 4757: 		$prob++;
 4758: 	    }
 4759: 	    $studentTable.='</td></tr>';
 4760: 
 4761: 	}
 4762:         $curRes = $iterator->next();
 4763:     }
 4764: 
 4765:     $studentTable.=
 4766:         '</table>'."\n".
 4767:         '<input type="button" value="'.&mt('Save').'" '.
 4768:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4769:         '</form>'."\n";
 4770:     $request->print($studentTable);
 4771: 
 4772:     return '';
 4773: }
 4774: 
 4775: sub displaySubByDates {
 4776:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4777:     my $isCODE=0;
 4778:     my $isTask = ($symb =~/\.task$/);
 4779:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4780:     my $studentTable=&Apache::loncommon::start_data_table().
 4781: 	&Apache::loncommon::start_data_table_header_row().
 4782: 	'<th>'.&mt('Date/Time').'</th>'.
 4783: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4784:         ($isTask?'<th>'.&mt('Version').'</th>':'').
 4785: 	'<th>'.&mt('Submission').'</th>'.
 4786: 	'<th>'.&mt('Status').'</th>'.
 4787: 	&Apache::loncommon::end_data_table_header_row();
 4788:     my ($version);
 4789:     my %mark;
 4790:     my %orders;
 4791:     $mark{'correct_by_student'} = $checkIcon;
 4792:     if (!exists($$record{'1:timestamp'})) {
 4793: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 4794:     }
 4795: 
 4796:     my $interaction;
 4797:     my $no_increment = 1;
 4798:     my %lastrndseed;
 4799:     for ($version=1;$version<=$$record{'version'};$version++) {
 4800: 	my $timestamp = 
 4801: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4802: 	if (exists($$record{$version.':resource.0.version'})) {
 4803: 	    $interaction = $$record{$version.':resource.0.version'};
 4804: 	}
 4805:         if ($isTask && $env{'form.previousversion'}) {
 4806:             next unless ($interaction == $env{'form.previousversion'});
 4807:         }
 4808: 	my $where = ($isTask ? "$version:resource.$interaction"
 4809: 		             : "$version:resource");
 4810: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4811: 	    '<td>'.$timestamp.'</td>';
 4812: 	if ($isCODE) {
 4813: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4814: 	}
 4815:         if ($isTask) {
 4816:             $studentTable.='<td>'.$interaction.'</td>';
 4817:         }
 4818: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4819: 	my @displaySub = ();
 4820: 	foreach my $partid (@{$parts}) {
 4821:             my ($hidden,$type);
 4822:             $type = $$record{$version.':resource.'.$partid.'.type'};
 4823:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
 4824:                 $hidden = 1;
 4825:             }
 4826: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4827: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4828: 	    
 4829: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4830: 	    my $display_part=&get_display_part($partid,$symb);
 4831: 	    foreach my $matchKey (@matchKey) {
 4832: 		if (exists($$record{$version.':'.$matchKey}) &&
 4833: 		    $$record{$version.':'.$matchKey} ne '') {
 4834:                     
 4835: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4836: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4837:                     $displaySub[0].='<span class="LC_nobreak">';
 4838:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 4839:                                    .' <span class="LC_internal_info">'
 4840:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
 4841:                                    .'</span>'
 4842:                                    .' <b>';
 4843:                     if ($hidden) {
 4844:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
 4845:                     } else {
 4846:                         my ($trial,$rndseed,$newvariation);
 4847:                         if ($type eq 'randomizetry') {
 4848:                             $trial = $$record{"$where.$partid.tries"};
 4849:                             $rndseed = $$record{"$where.$partid.rndseed"};
 4850:                         }
 4851: 		        if ($$record{"$where.$partid.tries"} eq '') {
 4852: 			    $displaySub[0].=&mt('Trial not counted');
 4853: 		        } else {
 4854: 			    $displaySub[0].=&mt('Trial: [_1]',
 4855: 					    $$record{"$where.$partid.tries"});
 4856:                             if ($rndseed || $lastrndseed{$partid}) {
 4857:                                 if ($rndseed ne $lastrndseed{$partid}) {
 4858:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
 4859:                                 }
 4860:                             }
 4861:                             $lastrndseed{$partid} = $rndseed;
 4862: 		        }
 4863: 		        my $responseType=($isTask ? 'Task'
 4864:                                               : $responseType->{$partid}->{$responseId});
 4865: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4866: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
 4867: 			    $orders{$partid}->{$responseId}=
 4868: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
 4869:                                            $no_increment,$type,$trial,$rndseed);
 4870: 		        }
 4871: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
 4872: 		        $displaySub[0].='&nbsp; '.
 4873: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
 4874:                     }
 4875: 		}
 4876: 	    }
 4877: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4878: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 4879: 				    $$record{"$where.$partid.checkedin"},
 4880: 				    $$record{"$where.$partid.checkedin.slot"}).
 4881: 					'<br />';
 4882: 	    }
 4883: 	    if (exists $$record{"$where.$partid.award"}) {
 4884: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 4885: 		    lc($$record{"$where.$partid.award"}).' '.
 4886: 		    $mark{$$record{"$where.$partid.solved"}}.
 4887: 		    '<br />';
 4888: 	    }
 4889: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4890: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4891: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4892: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4893: 		$displaySub[2].=
 4894: 		    $$record{"$version:resource.$partid.regrader"}.
 4895: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4896: 	    }
 4897: 	}
 4898: 	# needed because old essay regrader has not parts info
 4899: 	if (exists $$record{"$version:resource.regrader"}) {
 4900: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 4901: 	}
 4902: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 4903: 	if ($displaySub[2]) {
 4904: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 4905: 	}
 4906: 	$studentTable.='&nbsp;</td>'.
 4907: 	    &Apache::loncommon::end_data_table_row();
 4908:     }
 4909:     $studentTable.=&Apache::loncommon::end_data_table();
 4910:     return $studentTable;
 4911: }
 4912: 
 4913: sub updateGradeByPage {
 4914:     my ($request,$symb) = @_;
 4915: 
 4916:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4917:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4918:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4919:     my $pageTitle = $env{'form.page'};
 4920:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4921:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4922:     my $usec=$classlist->{$env{'form.student'}}[5];
 4923:     if (!&canmodify($usec)) {
 4924: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 4925: 	return;
 4926:     }
 4927:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4928:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 4929: 	'</h3>'."\n";
 4930: 
 4931:     $request->print($result);
 4932: 
 4933: 
 4934:     my $navmap = Apache::lonnavmaps::navmap->new();
 4935:     unless (ref($navmap)) {
 4936:         $request->print(&navmap_errormsg());
 4937:         return;
 4938:     }
 4939:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 4940:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4941:     if (!$map) {
 4942: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 4943: 	return; 
 4944:     }
 4945:     my $iterator = $navmap->getIterator($map->map_start(),
 4946: 					$map->map_finish());
 4947: 
 4948:     my $studentTable=
 4949: 	&Apache::loncommon::start_data_table().
 4950: 	&Apache::loncommon::start_data_table_header_row().
 4951: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 4952: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 4953: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 4954: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 4955: 	&Apache::loncommon::end_data_table_header_row();
 4956: 
 4957:     $iterator->next(); # skip the first BEGIN_MAP
 4958:     my $curRes = $iterator->next(); # for "current resource"
 4959:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 4960:     while ($depth > 0) {
 4961:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4962:         if($curRes == $iterator->END_MAP) { $depth--; }
 4963: 
 4964:         if (ref($curRes) && $curRes->is_problem()) {
 4965: 	    my $parts = $curRes->parts();
 4966:             my $title = $curRes->compTitle();
 4967: 	    my $symbx = $curRes->symb();
 4968: 	    $studentTable.=
 4969: 		&Apache::loncommon::start_data_table_row().
 4970: 		'<td align="center" valign="top" >'.$prob.
 4971: 		(scalar(@{$parts}) == 1 ? '' 
 4972:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
 4973: 		.')').'</td>';
 4974: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 4975: 
 4976: 	    my %newrecord=();
 4977: 	    my @displayPts=();
 4978:             my %aggregate = ();
 4979:             my $aggregateflag = 0;
 4980: 	    foreach my $partid (@{$parts}) {
 4981: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 4982: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 4983: 
 4984: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 4985: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 4986: 		my $partial = $newpts/$wgt;
 4987: 		my $score;
 4988: 		if ($partial > 0) {
 4989: 		    $score = 'correct_by_override';
 4990: 		} elsif ($newpts ne '') { #empty is taken as 0
 4991: 		    $score = 'incorrect_by_override';
 4992: 		}
 4993: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 4994: 		if ($dropMenu eq 'excused') {
 4995: 		    $partial = '';
 4996: 		    $score = 'excused';
 4997: 		} elsif ($dropMenu eq 'reset status'
 4998: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 4999: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 5000: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 5001: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 5002: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 5003: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 5004: 		    $changeflag++;
 5005: 		    $newpts = '';
 5006:                     
 5007:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 5008:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 5009:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 5010:                     if ($aggtries > 0) {
 5011:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 5012:                         $aggregateflag = 1;
 5013:                     }
 5014: 		}
 5015: 		my $display_part=&get_display_part($partid,$curRes->symb());
 5016: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 5017: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5018: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 5019: 		    '&nbsp;<br />';
 5020: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5021: 		     (($score eq 'excused') ? 'excused' : $newpts).
 5022: 		    '&nbsp;<br />';
 5023: 		$question++;
 5024: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 5025: 
 5026: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 5027: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 5028: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 5029: 		    if (scalar(keys(%newrecord)) > 0);
 5030: 
 5031: 		$changeflag++;
 5032: 	    }
 5033: 	    if (scalar(keys(%newrecord)) > 0) {
 5034: 		my %record = 
 5035: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 5036: 					     $udom,$uname);
 5037: 
 5038: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 5039: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 5040: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 5041: 		    $newrecord{'resource.CODE'} = '';
 5042: 		}
 5043: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 5044: 					$udom,$uname);
 5045: 		%record = &Apache::lonnet::restore($symbx,
 5046: 						   $env{'request.course.id'},
 5047: 						   $udom,$uname);
 5048: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 5049: 					     $cdom,$cnum,$udom,$uname);
 5050: 	    }
 5051: 	    
 5052:             if ($aggregateflag) {
 5053:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 5054:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 5055:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 5056:             }
 5057: 
 5058: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 5059: 		'<td valign="top">'.$displayPts[1].'</td>'.
 5060: 		&Apache::loncommon::end_data_table_row();
 5061: 
 5062: 	    $prob++;
 5063: 	}
 5064:         $curRes = $iterator->next();
 5065:     }
 5066: 
 5067:     $studentTable.=&Apache::loncommon::end_data_table();
 5068:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 5069: 		  &mt('The scores were changed for [quant,_1,problem].',
 5070: 		  $changeflag));
 5071:     $request->print($grademsg.$studentTable);
 5072: 
 5073:     return '';
 5074: }
 5075: 
 5076: #-------- end of section for handling grading by page/sequence ---------
 5077: #
 5078: #-------------------------------------------------------------------
 5079: 
 5080: #-------------------- Bubblesheet (Scantron) Grading -------------------
 5081: #
 5082: #------ start of section for handling grading by page/sequence ---------
 5083: 
 5084: =pod
 5085: 
 5086: =head1 Bubble sheet grading routines
 5087: 
 5088:   For this documentation:
 5089: 
 5090:    'scanline' refers to the full line of characters
 5091:    from the file that we are parsing that represents one entire sheet
 5092: 
 5093:    'bubble line' refers to the data
 5094:    representing the line of bubbles that are on the physical bubblesheet
 5095: 
 5096: 
 5097: The overall process is that a scanned in bubblesheet data is uploaded
 5098: into a course. When a user wants to grade, they select a
 5099: sequence/folder of resources, a file of bubblesheet info, and pick
 5100: one of the predefined configurations for what each scanline looks
 5101: like.
 5102: 
 5103: Next each scanline is checked for any errors of either 'missing
 5104: bubbles' (it's an error because it may have been mis-scanned
 5105: because too light bubbling), 'double bubble' (each bubble line should
 5106: have no more than one letter picked), invalid or duplicated CODE,
 5107: invalid student/employee ID
 5108: 
 5109: If the CODE option is used that determines the randomization of the
 5110: homework problems, either way the student/employee ID is looked up into a
 5111: username:domain.
 5112: 
 5113: During the validation phase the instructor can choose to skip scanlines. 
 5114: 
 5115: After the validation phase, there are now 3 bubblesheet files
 5116: 
 5117:   scantron_original_filename (unmodified original file)
 5118:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 5119:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 5120: 
 5121: Also there is a separate hash nohist_scantrondata that contains extra
 5122: correction information that isn't representable in the bubblesheet
 5123: file (see &scantron_getfile() for more information)
 5124: 
 5125: After all scanlines are either valid, marked as valid or skipped, then
 5126: foreach line foreach problem in the picked sequence, an ssi request is
 5127: made that simulates a user submitting their selected letter(s) against
 5128: the homework problem.
 5129: 
 5130: =over 4
 5131: 
 5132: 
 5133: 
 5134: =item defaultFormData
 5135: 
 5136:   Returns html hidden inputs used to hold context/default values.
 5137: 
 5138:  Arguments:
 5139:   $symb - $symb of the current resource 
 5140: 
 5141: =cut
 5142: 
 5143: sub defaultFormData {
 5144:     my ($symb)=@_;
 5145:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
 5146: }
 5147: 
 5148: 
 5149: =pod 
 5150: 
 5151: =item getSequenceDropDown
 5152: 
 5153:    Return html dropdown of possible sequences to grade
 5154:  
 5155:  Arguments:
 5156:    $symb - $symb of the current resource
 5157:    $map_error - ref to scalar which will container error if
 5158:                 $navmap object is unavailable in &getSymbMap().
 5159: 
 5160: =cut
 5161: 
 5162: sub getSequenceDropDown {
 5163:     my ($symb,$map_error)=@_;
 5164:     my $result='<select name="selectpage">'."\n";
 5165:     my ($titles,$symbx) = &getSymbMap($map_error);
 5166:     if (ref($map_error)) {
 5167:         return if ($$map_error);
 5168:     }
 5169:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 5170:     my $ctr=0;
 5171:     foreach (@$titles) {
 5172: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5173: 	$result.='<option value="'.$$symbx{$_}.'" '.
 5174: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 5175: 	    '>'.$showtitle.'</option>'."\n";
 5176: 	$ctr++;
 5177:     }
 5178:     $result.= '</select>';
 5179:     return $result;
 5180: }
 5181: 
 5182: my %bubble_lines_per_response;     # no. bubble lines for each response.
 5183:                                    # key is zero-based index - 0, 1, 2 ...
 5184: 
 5185: my %first_bubble_line;             # First bubble line no. for each bubble.
 5186: 
 5187: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 5188:                                    # matchresponse or rankresponse, where 
 5189:                                    # an individual response can have multiple 
 5190:                                    # lines
 5191: 
 5192: my %responsetype_per_response;     # responsetype for each response
 5193: 
 5194: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
 5195:                                    # numbered response. Needed when randomorder
 5196:                                    # or randompick are in use. Key is ID, value 
 5197:                                    # is response number.
 5198: 
 5199: # Save and restore the bubble lines array to the form env.
 5200: 
 5201: 
 5202: sub save_bubble_lines {
 5203:     foreach my $line (keys(%bubble_lines_per_response)) {
 5204: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 5205: 	$env{"form.scantron.first_bubble_line.$line"} =
 5206: 	    $first_bubble_line{$line};
 5207:         $env{"form.scantron.sub_bubblelines.$line"} = 
 5208:             $subdivided_bubble_lines{$line};
 5209:         $env{"form.scantron.responsetype.$line"} =
 5210:             $responsetype_per_response{$line};
 5211:     }
 5212:     foreach my $resid (keys(%masterseq_id_responsenum)) {
 5213:         my $line = $masterseq_id_responsenum{$resid};
 5214:         $env{"form.scantron.residpart.$line"} = $resid;
 5215:     }
 5216: }
 5217: 
 5218: 
 5219: sub restore_bubble_lines {
 5220:     my $line = 0;
 5221:     %bubble_lines_per_response = ();
 5222:     %masterseq_id_responsenum = ();
 5223:     while ($env{"form.scantron.bubblelines.$line"}) {
 5224: 	my $value = $env{"form.scantron.bubblelines.$line"};
 5225: 	$bubble_lines_per_response{$line} = $value;
 5226: 	$first_bubble_line{$line}  =
 5227: 	    $env{"form.scantron.first_bubble_line.$line"};
 5228:         $subdivided_bubble_lines{$line} =
 5229:             $env{"form.scantron.sub_bubblelines.$line"};
 5230:         $responsetype_per_response{$line} =
 5231:             $env{"form.scantron.responsetype.$line"};
 5232:         my $id = $env{"form.scantron.residpart.$line"};
 5233:         $masterseq_id_responsenum{$id} = $line;
 5234: 	$line++;
 5235:     }
 5236: }
 5237: 
 5238: =pod 
 5239: 
 5240: =item scantron_filenames
 5241: 
 5242:    Returns a list of the scantron files in the current course 
 5243: 
 5244: =cut
 5245: 
 5246: sub scantron_filenames {
 5247:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5248:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5249:     my $getpropath = 1;
 5250:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
 5251:                                                         $cname,$getpropath);
 5252:     my @possiblenames;
 5253:     if (ref($dirlist) eq 'ARRAY') {
 5254:         foreach my $filename (sort(@{$dirlist})) {
 5255: 	    ($filename)=split(/&/,$filename);
 5256: 	    if ($filename!~/^scantron_orig_/) { next ; }
 5257: 	    $filename=~s/^scantron_orig_//;
 5258: 	    push(@possiblenames,$filename);
 5259:         }
 5260:     }
 5261:     return @possiblenames;
 5262: }
 5263: 
 5264: =pod 
 5265: 
 5266: =item scantron_uploads
 5267: 
 5268:    Returns  html drop-down list of scantron files in current course.
 5269: 
 5270:  Arguments:
 5271:    $file2grade - filename to set as selected in the dropdown
 5272: 
 5273: =cut
 5274: 
 5275: sub scantron_uploads {
 5276:     my ($file2grade) = @_;
 5277:     my $result=	'<select name="scantron_selectfile">';
 5278:     $result.="<option></option>";
 5279:     foreach my $filename (sort(&scantron_filenames())) {
 5280: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 5281:     }
 5282:     $result.="</select>";
 5283:     return $result;
 5284: }
 5285: 
 5286: =pod 
 5287: 
 5288: =item scantron_scantab
 5289: 
 5290:   Returns html drop down of the scantron formats in the scantronformat.tab
 5291:   file.
 5292: 
 5293: =cut
 5294: 
 5295: sub scantron_scantab {
 5296:     my $result='<select name="scantron_format">'."\n";
 5297:     $result.='<option></option>'."\n";
 5298:     my @lines = &get_scantronformat_file();
 5299:     if (@lines > 0) {
 5300:         foreach my $line (@lines) {
 5301:             next if (($line =~ /^\#/) || ($line eq ''));
 5302: 	    my ($name,$descrip)=split(/:/,$line);
 5303: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 5304:         }
 5305:     }
 5306:     $result.='</select>'."\n";
 5307:     return $result;
 5308: }
 5309: 
 5310: =pod
 5311: 
 5312: =item get_scantronformat_file
 5313: 
 5314:   Returns an array containing lines from the scantron format file for
 5315:   the domain of the course.
 5316: 
 5317:   If a url for a custom.tab file is listed in domain's configuration.db, 
 5318:   lines are from this file.
 5319: 
 5320:   Otherwise, if a default.tab has been published in RES space by the 
 5321:   domainconfig user, lines are from this file.
 5322: 
 5323:   Otherwise, fall back to getting lines from the legacy file on the
 5324:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 5325: 
 5326: =cut
 5327: 
 5328: sub get_scantronformat_file {
 5329:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5330:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 5331:     my $gottab = 0;
 5332:     my @lines;
 5333:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5334:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5335:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5336:             if ($formatfile ne '-1') {
 5337:                 @lines = split("\n",$formatfile,-1);
 5338:                 $gottab = 1;
 5339:             }
 5340:         }
 5341:     }
 5342:     if (!$gottab) {
 5343:         my $confname = $cdom.'-domainconfig';
 5344:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5345:         my $formatfile =  &Apache::lonnet::getfile($default);
 5346:         if ($formatfile ne '-1') {
 5347:             @lines = split("\n",$formatfile,-1);
 5348:             $gottab = 1;
 5349:         }
 5350:     }
 5351:     if (!$gottab) {
 5352:         my @domains = &Apache::lonnet::current_machine_domains();
 5353:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5354:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5355:             @lines = <$fh>;
 5356:             close($fh);
 5357:         } else {
 5358:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 5359:             @lines = <$fh>;
 5360:             close($fh);
 5361:         }
 5362:     }
 5363:     return @lines;
 5364: }
 5365: 
 5366: =pod 
 5367: 
 5368: =item scantron_CODElist
 5369: 
 5370:   Returns html drop down of the saved CODE lists from current course,
 5371:   generated from earlier printings.
 5372: 
 5373: =cut
 5374: 
 5375: sub scantron_CODElist {
 5376:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5377:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5378:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5379:     my $namechoice='<option></option>';
 5380:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5381: 	if ($name =~ /^error: 2 /) { next; }
 5382: 	if ($name =~ /^type\0/) { next; }
 5383: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5384:     }
 5385:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5386:     return $namechoice;
 5387: }
 5388: 
 5389: =pod 
 5390: 
 5391: =item scantron_CODEunique
 5392: 
 5393:   Returns the html for "Each CODE to be used once" radio.
 5394: 
 5395: =cut
 5396: 
 5397: sub scantron_CODEunique {
 5398:     my $result='<span class="LC_nobreak">
 5399:                  <label><input type="radio" name="scantron_CODEunique"
 5400:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5401:                 </span>
 5402:                 <span class="LC_nobreak">
 5403:                  <label><input type="radio" name="scantron_CODEunique"
 5404:                         value="no" />'.&mt('No').' </label>
 5405:                 </span>';
 5406:     return $result;
 5407: }
 5408: 
 5409: =pod 
 5410: 
 5411: =item scantron_selectphase
 5412: 
 5413:   Generates the initial screen to start the bubblesheet process.
 5414:   Allows for - starting a grading run.
 5415:              - downloading existing scan data (original, corrected
 5416:                                                 or skipped info)
 5417: 
 5418:              - uploading new scan data
 5419: 
 5420:  Arguments:
 5421:   $r          - The Apache request object
 5422:   $file2grade - name of the file that contain the scanned data to score
 5423: 
 5424: =cut
 5425: 
 5426: sub scantron_selectphase {
 5427:     my ($r,$file2grade,$symb) = @_;
 5428:     if (!$symb) {return '';}
 5429:     my $map_error;
 5430:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 5431:     if ($map_error) {
 5432:         $r->print('<br />'.&navmap_errormsg().'<br />');
 5433:         return;
 5434:     }
 5435:     my $default_form_data=&defaultFormData($symb);
 5436:     my $file_selector=&scantron_uploads($file2grade);
 5437:     my $format_selector=&scantron_scantab();
 5438:     my $CODE_selector=&scantron_CODElist();
 5439:     my $CODE_unique=&scantron_CODEunique();
 5440:     my $result;
 5441: 
 5442:     $ssi_error = 0;
 5443: 
 5444:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5445:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5446: 
 5447: 	# Chunk of form to prompt for a scantron file upload.
 5448: 
 5449:         $r->print('
 5450:     <br />
 5451:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5452:        '.&Apache::loncommon::start_data_table_header_row().'
 5453:             <th>
 5454:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 5455:             </th>
 5456:        '.&Apache::loncommon::end_data_table_header_row().'
 5457:        '.&Apache::loncommon::start_data_table_row().'
 5458:             <td>
 5459: ');
 5460:     my $default_form_data=&defaultFormData($symb);
 5461:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5462:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5463:     $r->print(&Apache::lonhtmlcommon::scripttag('
 5464:     function checkUpload(formname) {
 5465: 	if (formname.upfile.value == "") {
 5466: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 5467: 	    return false;
 5468: 	}
 5469: 	formname.submit();
 5470:     }'));
 5471:     $r->print('
 5472:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5473:                 '.$default_form_data.'
 5474:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5475:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5476:                 <input name="command" value="scantronupload_save" type="hidden" />
 5477:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5478:                 <br />
 5479:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 5480:               </form>
 5481: ');
 5482: 
 5483:         $r->print('
 5484:             </td>
 5485:        '.&Apache::loncommon::end_data_table_row().'
 5486:        '.&Apache::loncommon::end_data_table().'
 5487: ');
 5488:     }
 5489: 
 5490:     # Chunk of form to prompt for a file to grade and how:
 5491: 
 5492:     $result.= '
 5493:     <br />
 5494:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5495:     <input type="hidden" name="command" value="scantron_warning" />
 5496:     '.$default_form_data.'
 5497:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5498:        '.&Apache::loncommon::start_data_table_header_row().'
 5499:             <th colspan="2">
 5500:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5501:             </th>
 5502:        '.&Apache::loncommon::end_data_table_header_row().'
 5503:        '.&Apache::loncommon::start_data_table_row().'
 5504:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5505:        '.&Apache::loncommon::end_data_table_row().'
 5506:        '.&Apache::loncommon::start_data_table_row().'
 5507:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 5508:        '.&Apache::loncommon::end_data_table_row().'
 5509:        '.&Apache::loncommon::start_data_table_row().'
 5510:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 5511:        '.&Apache::loncommon::end_data_table_row().'
 5512:        '.&Apache::loncommon::start_data_table_row().'
 5513:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5514:        '.&Apache::loncommon::end_data_table_row().'
 5515:        '.&Apache::loncommon::start_data_table_row().'
 5516:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5517:        '.&Apache::loncommon::end_data_table_row().'
 5518:        '.&Apache::loncommon::start_data_table_row().'
 5519: 	    <td> '.&mt('Options:').' </td>
 5520:             <td>
 5521: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5522:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5523:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5524: 	    </td>
 5525:        '.&Apache::loncommon::end_data_table_row().'
 5526:        '.&Apache::loncommon::start_data_table_row().'
 5527:             <td colspan="2">
 5528:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 5529:             </td>
 5530:        '.&Apache::loncommon::end_data_table_row().'
 5531:     '.&Apache::loncommon::end_data_table().'
 5532:     </form>
 5533: ';
 5534:    
 5535:     $r->print($result);
 5536: 
 5537: 
 5538: 
 5539:     # Chunk of the form that prompts to view a scoring office file,
 5540:     # corrected file, skipped records in a file.
 5541: 
 5542:     $r->print('
 5543:    <br />
 5544:    <form action="/adm/grades" name="scantron_download">
 5545:      '.$default_form_data.'
 5546:      <input type="hidden" name="command" value="scantron_download" />
 5547:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5548:        '.&Apache::loncommon::start_data_table_header_row().'
 5549:               <th>
 5550:                 &nbsp;'.&mt('Download a scoring office file').'
 5551:               </th>
 5552:        '.&Apache::loncommon::end_data_table_header_row().'
 5553:        '.&Apache::loncommon::start_data_table_row().'
 5554:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5555:                 <br />
 5556:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5557:        '.&Apache::loncommon::end_data_table_row().'
 5558:      '.&Apache::loncommon::end_data_table().'
 5559:    </form>
 5560:    <br />
 5561: ');
 5562: 
 5563:     &Apache::lonpickcode::code_list($r,2);
 5564: 
 5565:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
 5566:              $default_form_data."\n".
 5567:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5568:              &Apache::loncommon::start_data_table_header_row()."\n".
 5569:              '<th colspan="2">
 5570:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 5571:              '</th>'."\n".
 5572:               &Apache::loncommon::end_data_table_header_row()."\n".
 5573:               &Apache::loncommon::start_data_table_row()."\n".
 5574:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5575:               '<td> '.$sequence_selector.' </td>'.
 5576:               &Apache::loncommon::end_data_table_row()."\n".
 5577:               &Apache::loncommon::start_data_table_row()."\n".
 5578:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5579:               '<td> '.$file_selector.' </td>'."\n".
 5580:               &Apache::loncommon::end_data_table_row()."\n".
 5581:               &Apache::loncommon::start_data_table_row()."\n".
 5582:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5583:               '<td> '.$format_selector.' </td>'."\n".
 5584:               &Apache::loncommon::end_data_table_row()."\n".
 5585:               &Apache::loncommon::start_data_table_row()."\n".
 5586:               '<td> '.&mt('Options').' </td>'."\n".
 5587:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 5588:               &Apache::loncommon::end_data_table_row()."\n".
 5589:               &Apache::loncommon::start_data_table_row()."\n".
 5590:               '<td colspan="2">'."\n".
 5591:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5592:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 5593:               '</td>'."\n".
 5594:               &Apache::loncommon::end_data_table_row()."\n".
 5595:               &Apache::loncommon::end_data_table()."\n".
 5596:               '</form><br />');
 5597:     return;
 5598: }
 5599: 
 5600: =pod
 5601: 
 5602: =item get_scantron_config
 5603: 
 5604:    Parse and return the bubblesheet configuration line selected as a
 5605:    hash of configuration file fields.
 5606: 
 5607:  Arguments:
 5608:     which - the name of the configuration to parse from the file.
 5609: 
 5610: 
 5611:  Returns:
 5612:             If the named configuration is not in the file, an empty
 5613:             hash is returned.
 5614:     a hash with the fields
 5615:       name         - internal name for the this configuration setup
 5616:       description  - text to display to operator that describes this config
 5617:       CODElocation - if 0 or the string 'none'
 5618:                           - no CODE exists for this config
 5619:                      if -1 || the string 'letter'
 5620:                           - a CODE exists for this config and is
 5621:                             a string of letters
 5622:                      Unsupported value (but planned for future support)
 5623:                           if a positive integer
 5624:                                - The CODE exists as the first n items from
 5625:                                  the question section of the form
 5626:                           if the string 'number'
 5627:                                - The CODE exists for this config and is
 5628:                                  a string of numbers
 5629:       CODEstart   - (only matter if a CODE exists) column in the line where
 5630:                      the CODE starts
 5631:       CODElength  - length of the CODE
 5632:       IDstart     - column where the student/employee ID starts
 5633:       IDlength    - length of the student/employee ID info
 5634:       Qstart      - column where the information from the bubbled
 5635:                     'questions' start
 5636:       Qlength     - number of columns comprising a single bubble line from
 5637:                     the sheet. (usually either 1 or 10)
 5638:       Qon         - either a single character representing the character used
 5639:                     to signal a bubble was chosen in the positional setup, or
 5640:                     the string 'letter' if the letter of the chosen bubble is
 5641:                     in the final, or 'number' if a number representing the
 5642:                     chosen bubble is in the file (1->A 0->J)
 5643:       Qoff        - the character used to represent that a bubble was
 5644:                     left blank
 5645:       PaperID     - if the scanning process generates a unique number for each
 5646:                     sheet scanned the column that this ID number starts in
 5647:       PaperIDlength - number of columns that comprise the unique ID number
 5648:                       for the sheet of paper
 5649:       FirstName   - column that the first name starts in
 5650:       FirstNameLength - number of columns that the first name spans
 5651:  
 5652:       LastName    - column that the last name starts in
 5653:       LastNameLength - number of columns that the last name spans
 5654:       BubblesPerRow - number of bubbles available in each row used to 
 5655:                       bubble an answer. (If not specified, 10 assumed).
 5656: 
 5657: =cut
 5658: 
 5659: sub get_scantron_config {
 5660:     my ($which) = @_;
 5661:     my @lines = &get_scantronformat_file();
 5662:     my %config;
 5663:     #FIXME probably should move to XML it has already gotten a bit much now
 5664:     foreach my $line (@lines) {
 5665: 	my ($name,$descrip)=split(/:/,$line);
 5666: 	if ($name ne $which ) { next; }
 5667: 	chomp($line);
 5668: 	my @config=split(/:/,$line);
 5669: 	$config{'name'}=$config[0];
 5670: 	$config{'description'}=$config[1];
 5671: 	$config{'CODElocation'}=$config[2];
 5672: 	$config{'CODEstart'}=$config[3];
 5673: 	$config{'CODElength'}=$config[4];
 5674: 	$config{'IDstart'}=$config[5];
 5675: 	$config{'IDlength'}=$config[6];
 5676: 	$config{'Qstart'}=$config[7];
 5677:  	$config{'Qlength'}=$config[8];
 5678: 	$config{'Qoff'}=$config[9];
 5679: 	$config{'Qon'}=$config[10];
 5680: 	$config{'PaperID'}=$config[11];
 5681: 	$config{'PaperIDlength'}=$config[12];
 5682: 	$config{'FirstName'}=$config[13];
 5683: 	$config{'FirstNamelength'}=$config[14];
 5684: 	$config{'LastName'}=$config[15];
 5685: 	$config{'LastNamelength'}=$config[16];
 5686:         $config{'BubblesPerRow'}=$config[17];
 5687: 	last;
 5688:     }
 5689:     return %config;
 5690: }
 5691: 
 5692: =pod 
 5693: 
 5694: =item username_to_idmap
 5695: 
 5696:     creates a hash keyed by student/employee ID with values of the corresponding
 5697:     student username:domain.
 5698: 
 5699:   Arguments:
 5700: 
 5701:     $classlist - reference to the class list hash. This is a hash
 5702:                  keyed by student name:domain  whose elements are references
 5703:                  to arrays containing various chunks of information
 5704:                  about the student. (See loncoursedata for more info).
 5705: 
 5706:   Returns
 5707:     %idmap - the constructed hash
 5708: 
 5709: =cut
 5710: 
 5711: sub username_to_idmap {
 5712:     my ($classlist)= @_;
 5713:     my %idmap;
 5714:     foreach my $student (keys(%$classlist)) {
 5715: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5716: 	    $student;
 5717:     }
 5718:     return %idmap;
 5719: }
 5720: 
 5721: =pod
 5722: 
 5723: =item scantron_fixup_scanline
 5724: 
 5725:    Process a requested correction to a scanline.
 5726: 
 5727:   Arguments:
 5728:     $scantron_config   - hash from &get_scantron_config()
 5729:     $scan_data         - hash of correction information 
 5730:                           (see &scantron_getfile())
 5731:     $line              - existing scanline
 5732:     $whichline         - line number of the passed in scanline
 5733:     $field             - type of change to process 
 5734:                          (either 
 5735:                           'ID'     -> correct the student/employee ID
 5736:                           'CODE'   -> correct the CODE
 5737:                           'answer' -> fixup the submitted answers)
 5738:     
 5739:    $args               - hash of additional info,
 5740:                           - 'ID' 
 5741:                                'newid' -> studentID to use in replacement
 5742:                                           of existing one
 5743:                           - 'CODE' 
 5744:                                'CODE_ignore_dup' - set to true if duplicates
 5745:                                                    should be ignored.
 5746: 	                       'CODE' - is new code or 'use_unfound'
 5747:                                         if the existing unfound code should
 5748:                                         be used as is
 5749:                           - 'answer'
 5750:                                'response' - new answer or 'none' if blank
 5751:                                'question' - the bubble line to change
 5752:                                'questionnum' - the question identifier,
 5753:                                                may include subquestion. 
 5754: 
 5755:   Returns:
 5756:     $line - the modified scanline
 5757: 
 5758:   Side effects: 
 5759:     $scan_data - may be updated
 5760: 
 5761: =cut
 5762: 
 5763: 
 5764: sub scantron_fixup_scanline {
 5765:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5766:     if ($field eq 'ID') {
 5767: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5768: 	    return ($line,1,'New value too large');
 5769: 	}
 5770: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5771: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5772: 				     $args->{'newid'});
 5773: 	}
 5774: 	substr($line,$$scantron_config{'IDstart'}-1,
 5775: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5776: 	if ($args->{'newid'}=~/^\s*$/) {
 5777: 	    &scan_data($scan_data,"$whichline.user",
 5778: 		       $args->{'username'}.':'.$args->{'domain'});
 5779: 	}
 5780:     } elsif ($field eq 'CODE') {
 5781: 	if ($args->{'CODE_ignore_dup'}) {
 5782: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5783: 	}
 5784: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5785: 	if ($args->{'CODE'} ne 'use_unfound') {
 5786: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5787: 		return ($line,1,'New CODE value too large');
 5788: 	    }
 5789: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5790: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5791: 	    }
 5792: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5793: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5794: 	}
 5795:     } elsif ($field eq 'answer') {
 5796: 	my $length=$scantron_config->{'Qlength'};
 5797: 	my $off=$scantron_config->{'Qoff'};
 5798: 	my $on=$scantron_config->{'Qon'};
 5799: 	my $answer=${off}x$length;
 5800: 	if ($args->{'response'} eq 'none') {
 5801: 	    &scan_data($scan_data,
 5802: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5803: 	} else {
 5804: 	    if ($on eq 'letter') {
 5805: 		my @alphabet=('A'..'Z');
 5806: 		$answer=$alphabet[$args->{'response'}];
 5807: 	    } elsif ($on eq 'number') {
 5808: 		$answer=$args->{'response'}+1;
 5809: 		if ($answer == 10) { $answer = '0'; }
 5810: 	    } else {
 5811: 		substr($answer,$args->{'response'},1)=$on;
 5812: 	    }
 5813: 	    &scan_data($scan_data,
 5814: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5815: 	}
 5816: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5817: 	substr($line,$where-1,$length)=$answer;
 5818:     }
 5819:     return $line;
 5820: }
 5821: 
 5822: =pod
 5823: 
 5824: =item scan_data
 5825: 
 5826:     Edit or look up  an item in the scan_data hash.
 5827: 
 5828:   Arguments:
 5829:     $scan_data  - The hash (see scantron_getfile)
 5830:     $key        - shorthand of the key to edit (actual key is
 5831:                   scantronfilename_key).
 5832:     $data        - New value of the hash entry.
 5833:     $delete      - If true, the entry is removed from the hash.
 5834: 
 5835:   Returns:
 5836:     The new value of the hash table field (undefined if deleted).
 5837: 
 5838: =cut
 5839: 
 5840: 
 5841: sub scan_data {
 5842:     my ($scan_data,$key,$value,$delete)=@_;
 5843:     my $filename=$env{'form.scantron_selectfile'};
 5844:     if (defined($value)) {
 5845: 	$scan_data->{$filename.'_'.$key} = $value;
 5846:     }
 5847:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5848:     return $scan_data->{$filename.'_'.$key};
 5849: }
 5850: 
 5851: # ----- These first few routines are general use routines.----
 5852: 
 5853: # Return the number of occurences of a pattern in a string.
 5854: 
 5855: sub occurence_count {
 5856:     my ($string, $pattern) = @_;
 5857: 
 5858:     my @matches = ($string =~ /$pattern/g);
 5859: 
 5860:     return scalar(@matches);
 5861: }
 5862: 
 5863: 
 5864: # Take a string known to have digits and convert all the
 5865: # digits into letters in the range J,A..I.
 5866: 
 5867: sub digits_to_letters {
 5868:     my ($input) = @_;
 5869: 
 5870:     my @alphabet = ('J', 'A'..'I');
 5871: 
 5872:     my @input    = split(//, $input);
 5873:     my $output ='';
 5874:     for (my $i = 0; $i < scalar(@input); $i++) {
 5875: 	if ($input[$i] =~ /\d/) {
 5876: 	    $output .= $alphabet[$input[$i]];
 5877: 	} else {
 5878: 	    $output .= $input[$i];
 5879: 	}
 5880:     }
 5881:     return $output;
 5882: }
 5883: 
 5884: =pod 
 5885: 
 5886: =item scantron_parse_scanline
 5887: 
 5888:   Decodes a scanline from the selected bubblesheet file
 5889: 
 5890:  Arguments:
 5891:     line             - The text of the bubblesheet file line to process
 5892:     whichline        - Line number
 5893:     scantron_config  - Hash describing the format of the bubblesheet lines.
 5894:     scan_data        - Hash of extra information about the scanline
 5895:                        (see scantron_getfile for more information)
 5896:     just_header      - True if should not process question answers but only
 5897:                        the stuff to the left of the answers.
 5898:     randomorder      - True if randomorder in use
 5899:     randompick       - True if randompick in use
 5900:     sequence         - Exam folder URL
 5901:     master_seq       - Ref to array containing symbs in exam folder
 5902:     symb_to_resource - Ref to hash of symbs for resources in exam folder
 5903:                        (corresponding values are resource objects)
 5904:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
 5905:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
 5906:                        are refs to an array of resource objects, ordered
 5907:                        according to order used for CODE, when randomorder
 5908:                        and or randompick are in use.
 5909:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
 5910:                        for current line to question number used for same question
 5911:                         in "Master Sequence" (as seen by Course Coordinator).
 5912:     startline        - Ref to hash where key is question number (0 is first)
 5913:                        and value is number of first bubble line for current 
 5914:                        student or code-based randompick and/or randomorder.
 5915:     totalref         - Ref of scalar used to score total number of bubble
 5916:                        lines needed for responses in a scan line (used when
 5917:                        randompick in use. 
 5918:     
 5919:  Returns:
 5920:    Hash containing the result of parsing the scanline
 5921: 
 5922:    Keys are all proceeded by the string 'scantron.'
 5923: 
 5924:        CODE    - the CODE in use for this scanline
 5925:        useCODE - 1 if the CODE is invalid but it usage has been forced
 5926:                  by the operator
 5927:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 5928:                             CODEs were selected, but the usage has been
 5929:                             forced by the operator
 5930:        ID  - student/employee ID
 5931:        PaperID - if used, the ID number printed on the sheet when the 
 5932:                  paper was scanned
 5933:        FirstName - first name from the sheet
 5934:        LastName  - last name from the sheet
 5935: 
 5936:      if just_header was not true these key may also exist
 5937: 
 5938:        missingerror - a list of bubble ranges that are considered to be answers
 5939:                       to a single question that don't have any bubbles filled in.
 5940:                       Of the form questionnumber:firstbubblenumber:count.
 5941:        doubleerror  - a list of bubble ranges that are considered to be answers
 5942:                       to a single question that have more than one bubble filled in.
 5943:                       Of the form questionnumber::firstbubblenumber:count
 5944:    
 5945:                 In the above, count is the number of bubble responses in the
 5946:                 input line needed to represent the possible answers to the question.
 5947:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 5948:                 per line would have count = 2.
 5949: 
 5950:        maxquest     - the number of the last bubble line that was parsed
 5951: 
 5952:        (<number> starts at 1)
 5953:        <number>.answer - zero or more letters representing the selected
 5954:                          letters from the scanline for the bubble line 
 5955:                          <number>.
 5956:                          if blank there was either no bubble or there where
 5957:                          multiple bubbles, (consult the keys missingerror and
 5958:                          doubleerror if this is an error condition)
 5959: 
 5960: =cut
 5961: 
 5962: sub scantron_parse_scanline {
 5963:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
 5964:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
 5965:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
 5966: 
 5967:     my %record;
 5968:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
 5969:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 5970: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 5971: 	if ($$scantron_config{'CODElocation'} < 0 ||
 5972: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 5973: 	    $$scantron_config{'CODElocation'} eq 'number') {
 5974: 	    $record{'scantron.CODE'}=substr($data,
 5975: 					    $$scantron_config{'CODEstart'}-1,
 5976: 					    $$scantron_config{'CODElength'});
 5977: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 5978: 		$record{'scantron.useCODE'}=1;
 5979: 	    }
 5980: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 5981: 		$record{'scantron.CODE_ignore_dup'}=1;
 5982: 	    }
 5983: 	} else {
 5984: 	    #FIXME interpret first N questions
 5985: 	}
 5986:     }
 5987:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 5988: 				  $$scantron_config{'IDlength'});
 5989:     $record{'scantron.PaperID'}=
 5990: 	substr($data,$$scantron_config{'PaperID'}-1,
 5991: 	       $$scantron_config{'PaperIDlength'});
 5992:     $record{'scantron.FirstName'}=
 5993: 	substr($data,$$scantron_config{'FirstName'}-1,
 5994: 	       $$scantron_config{'FirstNamelength'});
 5995:     $record{'scantron.LastName'}=
 5996: 	substr($data,$$scantron_config{'LastName'}-1,
 5997: 	       $$scantron_config{'LastNamelength'});
 5998:     if ($just_header) { return \%record; }
 5999: 
 6000:     my @alphabet=('A'..'Z');
 6001:     my $questnum=0;
 6002:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 6003: 
 6004:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 6005:     if ($randompick || $randomorder) {
 6006:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
 6007:                                          $master_seq,$symb_to_resource,
 6008:                                          $partids_by_symb,$orderedforcode,
 6009:                                          $respnumlookup,$startline);
 6010:         if ($total) {
 6011:             $lastpos = $total*$$scantron_config{'Qlength'}; 
 6012:         }
 6013:         if (ref($totalref)) {
 6014:             $$totalref = $total;
 6015:         }
 6016:     }
 6017:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 6018:     chomp($questions);		# Get rid of any trailing \n.
 6019:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 6020:     while (length($questions)) {
 6021:         my $answers_needed;
 6022:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6023:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
 6024:         } else {
 6025: 	    $answers_needed = $bubble_lines_per_response{$questnum};
 6026:         }
 6027:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 6028:                              || 1;
 6029:         $questnum++;
 6030:         my $quest_id = $questnum;
 6031:         my $currentquest = substr($questions,0,$answer_length);
 6032:         $questions       = substr($questions,$answer_length);
 6033:         if (length($currentquest) < $answer_length) { next; }
 6034: 
 6035:         my $subdivided;
 6036:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6037:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
 6038:         } else {
 6039:             $subdivided = $subdivided_bubble_lines{$questnum-1};
 6040:         }
 6041:         if ($subdivided =~ /,/) {
 6042:             my $subquestnum = 1;
 6043:             my $subquestions = $currentquest;
 6044:             my @subanswers_needed = split(/,/,$subdivided);
 6045:             foreach my $subans (@subanswers_needed) {
 6046:                 my $subans_length =
 6047:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 6048:                 my $currsubquest = substr($subquestions,0,$subans_length);
 6049:                 $subquestions   = substr($subquestions,$subans_length);
 6050:                 $quest_id = "$questnum.$subquestnum";
 6051:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 6052:                     ($$scantron_config{'Qon'} eq 'number')) {
 6053:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 6054:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6055:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6056:                         $randomorder,$randompick,$respnumlookup);
 6057:                 } else {
 6058:                     $ansnum = &scantron_validator_positional($ansnum,
 6059:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6060:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6061:                         $randomorder,$randompick,$respnumlookup);
 6062:                 }
 6063:                 $subquestnum ++;
 6064:             }
 6065:         } else {
 6066:             if (($$scantron_config{'Qon'} eq 'letter') ||
 6067:                 ($$scantron_config{'Qon'} eq 'number')) {
 6068:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 6069:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6070:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6071:                     $randomorder,$randompick,$respnumlookup);
 6072:             } else {
 6073:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 6074:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6075:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6076:                     $randomorder,$randompick,$respnumlookup);
 6077:             }
 6078:         }
 6079:     }
 6080:     $record{'scantron.maxquest'}=$questnum;
 6081:     return \%record;
 6082: }
 6083: 
 6084: sub get_master_seq {
 6085:     my ($resources,$master_seq,$symb_to_resource) = @_;
 6086:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') && 
 6087:                    (ref($symb_to_resource) eq 'HASH'));
 6088:     my $resource_error;
 6089:     foreach my $resource (@{$resources}) {
 6090:         my $ressymb;
 6091:         if (ref($resource)) {
 6092:             $ressymb = $resource->symb();
 6093:             push(@{$master_seq},$ressymb);
 6094:             $symb_to_resource->{$ressymb} = $resource;
 6095:         } else {
 6096:             $resource_error = 1;
 6097:             last;
 6098:         }
 6099:     }
 6100:     return $resource_error;
 6101: }
 6102: 
 6103: sub get_respnum_lookups {
 6104:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
 6105:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
 6106:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
 6107:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
 6108:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
 6109:                    (ref($startline) eq 'HASH'));
 6110:     my ($user,$scancode);
 6111:     if ((exists($record->{'scantron.CODE'})) &&
 6112:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
 6113:         $scancode = $record->{'scantron.CODE'};
 6114:     } else {
 6115:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
 6116:     }
 6117:     my @mapresources =
 6118:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
 6119:                      $orderedforcode);
 6120:     my $total = 0;
 6121:     my $count = 0;
 6122:     foreach my $resource (@mapresources) {
 6123:         my $id = $resource->id();
 6124:         my $symb = $resource->symb();
 6125:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
 6126:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
 6127:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
 6128:                 if ($respnum ne '') {
 6129:                     $respnumlookup->{$count} = $respnum;
 6130:                     $startline->{$count} = $total;
 6131:                     $total += $bubble_lines_per_response{$respnum};
 6132:                     $count ++;
 6133:                 }
 6134:             }
 6135:         }
 6136:     }
 6137:     return $total;
 6138: }
 6139: 
 6140: sub scantron_validator_lettnum {
 6141:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 6142:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
 6143:         $randompick,$respnumlookup) = @_;
 6144: 
 6145:     # Qon 'letter' implies for each slot in currquest we have:
 6146:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 6147:     #    about anything else (esp. a value of Qoff) for missing
 6148:     #    bubbles.
 6149:     #
 6150:     # Qon 'number' implies each slot gives a digit that indexes the
 6151:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 6152:     #    and * or ? for double bubbles on a single line.
 6153:     #
 6154: 
 6155:     my $matchon;
 6156:     if ($$scantron_config{'Qon'} eq 'letter') {
 6157:         $matchon = '[A-Z]';
 6158:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 6159:         $matchon = '\d';
 6160:     }
 6161:     my $occurrences = 0;
 6162:     my $responsenum = $questnum-1;
 6163:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6164:        $responsenum = $respnumlookup->{$questnum-1} 
 6165:     }
 6166:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6167:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6168:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6169:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6170:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6171:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6172:         my @singlelines = split('',$currquest);
 6173:         foreach my $entry (@singlelines) {
 6174:             $occurrences = &occurence_count($entry,$matchon);
 6175:             if ($occurrences > 1) {
 6176:                 last;
 6177:             }
 6178:         }
 6179:     } else {
 6180:         $occurrences = &occurence_count($currquest,$matchon); 
 6181:     }
 6182:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 6183:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6184:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6185:             my $bubble = substr($currquest,$ans,1);
 6186:             if ($bubble =~ /$matchon/ ) {
 6187:                 if ($$scantron_config{'Qon'} eq 'number') {
 6188:                     if ($bubble == 0) {
 6189:                         $bubble = 10; 
 6190:                     }
 6191:                     $record->{"scantron.$ansnum.answer"} = 
 6192:                         $alphabet->[$bubble-1];
 6193:                 } else {
 6194:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 6195:                 }
 6196:             } else {
 6197:                 $record->{"scantron.$ansnum.answer"}='';
 6198:             }
 6199:             $ansnum++;
 6200:         }
 6201:     } elsif (!defined($currquest)
 6202:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 6203:             || (&occurence_count($currquest,$matchon) == 0)) {
 6204:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6205:             $record->{"scantron.$ansnum.answer"}='';
 6206:             $ansnum++;
 6207:         }
 6208:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6209:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 6210:         }
 6211:     } else {
 6212:         if ($$scantron_config{'Qon'} eq 'number') {
 6213:             $currquest = &digits_to_letters($currquest);            
 6214:         }
 6215:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6216:             my $bubble = substr($currquest,$ans,1);
 6217:             $record->{"scantron.$ansnum.answer"} = $bubble;
 6218:             $ansnum++;
 6219:         }
 6220:     }
 6221:     return $ansnum;
 6222: }
 6223: 
 6224: sub scantron_validator_positional {
 6225:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 6226:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
 6227:         $randomorder,$randompick,$respnumlookup) = @_;
 6228: 
 6229:     # Otherwise there's a positional notation;
 6230:     # each bubble line requires Qlength items, and there are filled in
 6231:     # bubbles for each case where there 'Qon' characters.
 6232:     #
 6233: 
 6234:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 6235: 
 6236:     # If the split only gives us one element.. the full length of the
 6237:     # answer string, no bubbles are filled in:
 6238: 
 6239:     if ($answers_needed eq '') {
 6240:         return;
 6241:     }
 6242: 
 6243:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 6244:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6245:             $record->{"scantron.$ansnum.answer"}='';
 6246:             $ansnum++;
 6247:         }
 6248:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6249:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 6250:         }
 6251:     } elsif (scalar(@array) == 2) {
 6252:         my $location = length($array[0]);
 6253:         my $line_num = int($location / $$scantron_config{'Qlength'});
 6254:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 6255:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6256:             if ($ans eq $line_num) {
 6257:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 6258:             } else {
 6259:                 $record->{"scantron.$ansnum.answer"} = ' ';
 6260:             }
 6261:             $ansnum++;
 6262:          }
 6263:     } else {
 6264:         #  If there's more than one instance of a bubble character
 6265:         #  That's a double bubble; with positional notation we can
 6266:         #  record all the bubbles filled in as well as the
 6267:         #  fact this response consists of multiple bubbles.
 6268:         #
 6269:         my $responsenum = $questnum-1;
 6270:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6271:             $responsenum = $respnumlookup->{$questnum-1}
 6272:         }
 6273:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6274:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6275:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6276:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6277:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6278:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6279:             my $doubleerror = 0;
 6280:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 6281:                    (!$doubleerror)) {
 6282:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 6283:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 6284:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 6285:                if (length(@currarray) > 2) {
 6286:                    $doubleerror = 1;
 6287:                } 
 6288:             }
 6289:             if ($doubleerror) {
 6290:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6291:             }
 6292:         } else {
 6293:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6294:         }
 6295:         my $item = $ansnum;
 6296:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6297:             $record->{"scantron.$item.answer"} = '';
 6298:             $item ++;
 6299:         }
 6300: 
 6301:         my @ans=@array;
 6302:         my $i=0;
 6303:         my $increment = 0;
 6304:         while ($#ans) {
 6305:             $i+=length($ans[0]) + $increment;
 6306:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 6307:             my $bubble = $i%$$scantron_config{'Qlength'};
 6308:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 6309:             shift(@ans);
 6310:             $increment = 1;
 6311:         }
 6312:         $ansnum += $answers_needed;
 6313:     }
 6314:     return $ansnum;
 6315: }
 6316: 
 6317: =pod
 6318: 
 6319: =item scantron_add_delay
 6320: 
 6321:    Adds an error message that occurred during the grading phase to a
 6322:    queue of messages to be shown after grading pass is complete
 6323: 
 6324:  Arguments:
 6325:    $delayqueue  - arrary ref of hash ref of error messages
 6326:    $scanline    - the scanline that caused the error
 6327:    $errormesage - the error message
 6328:    $errorcode   - a numeric code for the error
 6329: 
 6330:  Side Effects:
 6331:    updates the $delayqueue to have a new hash ref of the error
 6332: 
 6333: =cut
 6334: 
 6335: sub scantron_add_delay {
 6336:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 6337:     push(@$delayqueue,
 6338: 	 {'line' => $scanline, 'emsg' => $errormessage,
 6339: 	  'ecode' => $errorcode }
 6340: 	 );
 6341: }
 6342: 
 6343: =pod
 6344: 
 6345: =item scantron_find_student
 6346: 
 6347:    Finds the username for the current scanline
 6348: 
 6349:   Arguments:
 6350:    $scantron_record - hash result from scantron_parse_scanline
 6351:    $scan_data       - hash of correction information 
 6352:                       (see &scantron_getfile() form more information)
 6353:    $idmap           - hash from &username_to_idmap()
 6354:    $line            - number of current scanline
 6355:  
 6356:   Returns:
 6357:    Either 'username:domain' or undef if unknown
 6358: 
 6359: =cut
 6360: 
 6361: sub scantron_find_student {
 6362:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 6363:     my $scanID=$$scantron_record{'scantron.ID'};
 6364:     if ($scanID =~ /^\s*$/) {
 6365:  	return &scan_data($scan_data,"$line.user");
 6366:     }
 6367:     foreach my $id (keys(%$idmap)) {
 6368:  	if (lc($id) eq lc($scanID)) {
 6369:  	    return $$idmap{$id};
 6370:  	}
 6371:     }
 6372:     return undef;
 6373: }
 6374: 
 6375: =pod
 6376: 
 6377: =item scantron_filter
 6378: 
 6379:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 6380:    hidden resources was selected
 6381: 
 6382: =cut
 6383: 
 6384: sub scantron_filter {
 6385:     my ($curres)=@_;
 6386: 
 6387:     if (ref($curres) && $curres->is_problem()) {
 6388: 	# if the user has asked to not have either hidden
 6389: 	# or 'randomout' controlled resources to be graded
 6390: 	# don't include them
 6391: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6392: 	    && $curres->randomout) {
 6393: 	    return 0;
 6394: 	}
 6395: 	return 1;
 6396:     }
 6397:     return 0;
 6398: }
 6399: 
 6400: =pod
 6401: 
 6402: =item scantron_process_corrections
 6403: 
 6404:    Gets correction information out of submitted form data and corrects
 6405:    the scanline
 6406: 
 6407: =cut
 6408: 
 6409: sub scantron_process_corrections {
 6410:     my ($r) = @_;
 6411:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6412:     my ($scanlines,$scan_data)=&scantron_getfile();
 6413:     my $classlist=&Apache::loncoursedata::get_classlist();
 6414:     my $which=$env{'form.scantron_line'};
 6415:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 6416:     my ($skip,$err,$errmsg);
 6417:     if ($env{'form.scantron_skip_record'}) {
 6418: 	$skip=1;
 6419:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 6420: 	my $newstudent=$env{'form.scantron_username'}.':'.
 6421: 	    $env{'form.scantron_domain'};
 6422: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 6423: 	($line,$err,$errmsg)=
 6424: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6425: 				     'ID',{'newid'=>$newid,
 6426: 				    'username'=>$env{'form.scantron_username'},
 6427: 				    'domain'=>$env{'form.scantron_domain'}});
 6428:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 6429: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 6430: 	my $newCODE;
 6431: 	my %args;
 6432: 	if      ($resolution eq 'use_unfound') {
 6433: 	    $newCODE='use_unfound';
 6434: 	} elsif ($resolution eq 'use_found') {
 6435: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6436: 	} elsif ($resolution eq 'use_typed') {
 6437: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6438: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6439: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6440: 	}
 6441: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6442: 	    $args{'CODE_ignore_dup'}=1;
 6443: 	}
 6444: 	$args{'CODE'}=$newCODE;
 6445: 	($line,$err,$errmsg)=
 6446: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6447: 				     'CODE',\%args);
 6448:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6449: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6450: 	    ($line,$err,$errmsg)=
 6451: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6452: 					 $which,'answer',
 6453: 					 { 'question'=>$question,
 6454: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6455:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6456: 	    if ($err) { last; }
 6457: 	}
 6458:     }
 6459:     if ($err) {
 6460:         $r->print(
 6461:             '<p class="LC_error">'
 6462:            .&mt('Unable to accept last correction, an error occurred: [_1]',
 6463:                 $errmsg)
 6464:            .'</p>');
 6465:     } else {
 6466: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 6467: 	&scantron_putfile($scanlines,$scan_data);
 6468:     }
 6469: }
 6470: 
 6471: =pod
 6472: 
 6473: =item reset_skipping_status
 6474: 
 6475:    Forgets the current set of remember skipped scanlines (and thus
 6476:    reverts back to considering all lines in the
 6477:    scantron_skipped_<filename> file)
 6478: 
 6479: =cut
 6480: 
 6481: sub reset_skipping_status {
 6482:     my ($scanlines,$scan_data)=&scantron_getfile();
 6483:     &scan_data($scan_data,'remember_skipping',undef,1);
 6484:     &scantron_putfile(undef,$scan_data);
 6485: }
 6486: 
 6487: =pod
 6488: 
 6489: =item start_skipping
 6490: 
 6491:    Marks a scanline to be skipped. 
 6492: 
 6493: =cut
 6494: 
 6495: sub start_skipping {
 6496:     my ($scan_data,$i)=@_;
 6497:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6498:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6499: 	$remembered{$i}=2;
 6500:     } else {
 6501: 	$remembered{$i}=1;
 6502:     }
 6503:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6504: }
 6505: 
 6506: =pod
 6507: 
 6508: =item should_be_skipped
 6509: 
 6510:    Checks whether a scanline should be skipped.
 6511: 
 6512: =cut
 6513: 
 6514: sub should_be_skipped {
 6515:     my ($scanlines,$scan_data,$i)=@_;
 6516:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6517: 	# not redoing old skips
 6518: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6519: 	return 0;
 6520:     }
 6521:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6522: 
 6523:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6524: 	return 0;
 6525:     }
 6526:     return 1;
 6527: }
 6528: 
 6529: =pod
 6530: 
 6531: =item remember_current_skipped
 6532: 
 6533:    Discovers what scanlines are in the scantron_skipped_<filename>
 6534:    file and remembers them into scan_data for later use.
 6535: 
 6536: =cut
 6537: 
 6538: sub remember_current_skipped {
 6539:     my ($scanlines,$scan_data)=&scantron_getfile();
 6540:     my %to_remember;
 6541:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6542: 	if ($scanlines->{'skipped'}[$i]) {
 6543: 	    $to_remember{$i}=1;
 6544: 	}
 6545:     }
 6546: 
 6547:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6548:     &scantron_putfile(undef,$scan_data);
 6549: }
 6550: 
 6551: =pod
 6552: 
 6553: =item check_for_error
 6554: 
 6555:     Checks if there was an error when attempting to remove a specific
 6556:     scantron_.. bubblesheet data file. Prints out an error if
 6557:     something went wrong.
 6558: 
 6559: =cut
 6560: 
 6561: sub check_for_error {
 6562:     my ($r,$result)=@_;
 6563:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6564: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6565:     }
 6566: }
 6567: 
 6568: =pod
 6569: 
 6570: =item scantron_warning_screen
 6571: 
 6572:    Interstitial screen to make sure the operator has selected the
 6573:    correct options before we start the validation phase.
 6574: 
 6575: =cut
 6576: 
 6577: sub scantron_warning_screen {
 6578:     my ($button_text,$symb)=@_;
 6579:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6580:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6581:     my $CODElist;
 6582:     if ($scantron_config{'CODElocation'} &&
 6583: 	$scantron_config{'CODEstart'} &&
 6584: 	$scantron_config{'CODElength'}) {
 6585: 	$CODElist=$env{'form.scantron_CODElist'};
 6586: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
 6587: 	$CODElist=
 6588: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6589: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6590:     }
 6591:     my $lastbubblepoints;
 6592:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 6593:         $lastbubblepoints =
 6594:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
 6595:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
 6596:     }
 6597:     return ('
 6598: <p>
 6599: <span class="LC_warning">
 6600: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
 6601: </p>
 6602: <table>
 6603: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6604: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6605: '.$CODElist.$lastbubblepoints.'
 6606: </table>
 6607: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
 6608: '.&mt('If something is incorrect, please return to [_1]Grade/Manage/Review Bubblesheets[_2] to start over.','<a href="/adm/grades?symb='.$symb.'&command=scantron_selectphase" class="LC_info">','</a>').'</p>
 6609: 
 6610: <br />
 6611: ');
 6612: }
 6613: 
 6614: =pod
 6615: 
 6616: =item scantron_do_warning
 6617: 
 6618:    Check if the operator has picked something for all required
 6619:    fields. Error out if something is missing.
 6620: 
 6621: =cut
 6622: 
 6623: sub scantron_do_warning {
 6624:     my ($r,$symb)=@_;
 6625:     if (!$symb) {return '';}
 6626:     my $default_form_data=&defaultFormData($symb);
 6627:     $r->print(&scantron_form_start().$default_form_data);
 6628:     if ( $env{'form.selectpage'} eq '' ||
 6629: 	 $env{'form.scantron_selectfile'} eq '' ||
 6630: 	 $env{'form.scantron_format'} eq '' ) {
 6631: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
 6632: 	if ( $env{'form.selectpage'} eq '') {
 6633: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6634: 	} 
 6635: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6636: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
 6637: 	} 
 6638: 	if ( $env{'form.scantron_format'} eq '') {
 6639: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
 6640: 	} 
 6641:     } else {
 6642: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
 6643:         my $bubbledbyhand=&hand_bubble_option();
 6644: 	$r->print('
 6645: '.$warning.$bubbledbyhand.'
 6646: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6647: <input type="hidden" name="command" value="scantron_validate" />
 6648: ');
 6649:     }
 6650:     $r->print("</form><br />");
 6651:     return '';
 6652: }
 6653: 
 6654: =pod
 6655: 
 6656: =item scantron_form_start
 6657: 
 6658:     html hidden input for remembering all selected grading options
 6659: 
 6660: =cut
 6661: 
 6662: sub scantron_form_start {
 6663:     my ($max_bubble)=@_;
 6664:     my $result= <<SCANTRONFORM;
 6665: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6666:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6667:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6668:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6669:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6670:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6671:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6672:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6673:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6674:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6675: SCANTRONFORM
 6676: 
 6677:   my $line = 0;
 6678:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6679:        my $chunk =
 6680: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6681:        $chunk .=
 6682: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6683:        $chunk .= 
 6684:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6685:        $chunk .=
 6686:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6687:        $chunk .=
 6688:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
 6689:        $result .= $chunk;
 6690:        $line++;
 6691:     }
 6692:     return $result;
 6693: }
 6694: 
 6695: =pod
 6696: 
 6697: =item scantron_validate_file
 6698: 
 6699:     Dispatch routine for doing validation of a bubblesheet data file.
 6700: 
 6701:     Also processes any necessary information resets that need to
 6702:     occur before validation begins (ignore previous corrections,
 6703:     restarting the skipped records processing)
 6704: 
 6705: =cut
 6706: 
 6707: sub scantron_validate_file {
 6708:     my ($r,$symb) = @_;
 6709:     if (!$symb) {return '';}
 6710:     my $default_form_data=&defaultFormData($symb);
 6711:     
 6712:     # do the detection of only doing skipped records first before we delete
 6713:     # them when doing the corrections reset
 6714:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6715: 	&reset_skipping_status();
 6716:     }
 6717:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6718: 	&remember_current_skipped();
 6719: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6720:     }
 6721: 
 6722:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6723: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6724: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6725: 	&check_for_error($r,&scantron_remove_scan_data());
 6726: 	$env{'form.scantron_options_ignore'}='done';
 6727:     }
 6728: 
 6729:     if ($env{'form.scantron_corrections'}) {
 6730: 	&scantron_process_corrections($r);
 6731:     }
 6732:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6733:     #get the student pick code ready
 6734:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6735:     my $nav_error;
 6736:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6737:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 6738:     if ($nav_error) {
 6739:         $r->print(&navmap_errormsg());
 6740:         return '';
 6741:     }
 6742:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6743:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 6744:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
 6745:     }
 6746:     $r->print($result);
 6747:     
 6748:     my @validate_phases=( 'sequence',
 6749: 			  'ID',
 6750: 			  'CODE',
 6751: 			  'doublebubble',
 6752: 			  'missingbubbles');
 6753:     if (!$env{'form.validatepass'}) {
 6754: 	$env{'form.validatepass'} = 0;
 6755:     }
 6756:     my $currentphase=$env{'form.validatepass'};
 6757: 
 6758: 
 6759:     my $stop=0;
 6760:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6761: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6762: 	$r->rflush();
 6763:      
 6764: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6765: 	{
 6766: 	    no strict 'refs';
 6767: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6768: 	}
 6769:     }
 6770:     if (!$stop) {
 6771: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
 6772: 	$r->print(&mt('Validation process complete.').'<br />'.
 6773:                   $warning.
 6774:                   &mt('Perform verification for each student after storage of submissions?').
 6775:                   '&nbsp;<span class="LC_nobreak"><label>'.
 6776:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 6777:                   ('&nbsp;'x3).'<label>'.
 6778:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 6779:                   '</label></span><br />'.
 6780:                   &mt('Grading will take longer if you use verification.').'<br />'.
 6781:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
 6782:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 6783:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 6784:     } else {
 6785: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6786: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6787:     }
 6788:     if ($stop) {
 6789: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6790: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 6791: 	    $r->print(' '.&mt('this error').' <br />');
 6792: 
 6793: 	    $r->print('<p>'.&mt('Or return to [_1]Grade/Manage/Review Bubblesheets[_2] to start over.','<a href="/adm/grades?symb='.$symb.'&command=scantron_selectphase" class="LC_info">','</a>').'</p>');
 6794: 	} else {
 6795:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6796: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 6797:             } else {
 6798:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 6799:             }
 6800: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6801: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6802: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6803: 	}
 6804:     }
 6805:     $r->print(" </form><br />");
 6806:     return '';
 6807: }
 6808: 
 6809: 
 6810: =pod
 6811: 
 6812: =item scantron_remove_file
 6813: 
 6814:    Removes the requested bubblesheet data file, makes sure that
 6815:    scantron_original_<filename> is never removed
 6816: 
 6817: 
 6818: =cut
 6819: 
 6820: sub scantron_remove_file {
 6821:     my ($which)=@_;
 6822:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6823:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6824:     my $file='scantron_';
 6825:     if ($which eq 'corrected' || $which eq 'skipped') {
 6826: 	$file.=$which.'_';
 6827:     } else {
 6828: 	return 'refused';
 6829:     }
 6830:     $file.=$env{'form.scantron_selectfile'};
 6831:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6832: }
 6833: 
 6834: 
 6835: =pod
 6836: 
 6837: =item scantron_remove_scan_data
 6838: 
 6839:    Removes all scan_data correction for the requested bubblesheet
 6840:    data file.  (In the case that both the are doing skipped records we need
 6841:    to remember the old skipped lines for the time being so that element
 6842:    persists for a while.)
 6843: 
 6844: =cut
 6845: 
 6846: sub scantron_remove_scan_data {
 6847:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6848:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6849:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6850:     my @todelete;
 6851:     my $filename=$env{'form.scantron_selectfile'};
 6852:     foreach my $key (@keys) {
 6853: 	if ($key=~/^\Q$filename\E_/) {
 6854: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6855: 		$key=~/remember_skipping/) {
 6856: 		next;
 6857: 	    }
 6858: 	    push(@todelete,$key);
 6859: 	}
 6860:     }
 6861:     my $result;
 6862:     if (@todelete) {
 6863: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6864: 				       \@todelete,$cdom,$cname);
 6865:     } else {
 6866: 	$result = 'ok';
 6867:     }
 6868:     return $result;
 6869: }
 6870: 
 6871: 
 6872: =pod
 6873: 
 6874: =item scantron_getfile
 6875: 
 6876:     Fetches the requested bubblesheet data file (all 3 versions), and
 6877:     the scan_data hash
 6878:   
 6879:   Arguments:
 6880:     None
 6881: 
 6882:   Returns:
 6883:     2 hash references
 6884: 
 6885:      - first one has 
 6886:          orig      -
 6887:          corrected -
 6888:          skipped   -  each of which points to an array ref of the specified
 6889:                       file broken up into individual lines
 6890:          count     - number of scanlines
 6891:  
 6892:      - second is the scan_data hash possible keys are
 6893:        ($number refers to scanline numbered $number and thus the key affects
 6894:         only that scanline
 6895:         $bubline refers to the specific bubble line element and the aspects
 6896:         refers to that specific bubble line element)
 6897: 
 6898:        $number.user - username:domain to use
 6899:        $number.CODE_ignore_dup 
 6900:                     - ignore the duplicate CODE error 
 6901:        $number.useCODE
 6902:                     - use the CODE in the scanline as is
 6903:        $number.no_bubble.$bubline
 6904:                     - it is valid that there is no bubbled in bubble
 6905:                       at $number $bubline
 6906:        remember_skipping
 6907:                     - a frozen hash containing keys of $number and values
 6908:                       of either 
 6909:                         1 - we are on a 'do skipped records pass' and plan
 6910:                             on processing this line
 6911:                         2 - we are on a 'do skipped records pass' and this
 6912:                             scanline has been marked to skip yet again
 6913: 
 6914: =cut
 6915: 
 6916: sub scantron_getfile {
 6917:     #FIXME really would prefer a scantron directory
 6918:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6919:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6920:     my $lines;
 6921:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6922: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 6923:     my %scanlines;
 6924:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 6925:     my $temp=$scanlines{'orig'};
 6926:     $scanlines{'count'}=$#$temp;
 6927: 
 6928:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6929: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 6930:     if ($lines eq '-1') {
 6931: 	$scanlines{'corrected'}=[];
 6932:     } else {
 6933: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 6934:     }
 6935:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6936: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 6937:     if ($lines eq '-1') {
 6938: 	$scanlines{'skipped'}=[];
 6939:     } else {
 6940: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 6941:     }
 6942:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 6943:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 6944:     my %scan_data = @tmp;
 6945:     return (\%scanlines,\%scan_data);
 6946: }
 6947: 
 6948: =pod
 6949: 
 6950: =item lonnet_putfile
 6951: 
 6952:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 6953: 
 6954:  Arguments:
 6955:    $contents - data to store
 6956:    $filename - filename to store $contents into
 6957: 
 6958:  Returns:
 6959:    result value from &Apache::lonnet::finishuserfileupload
 6960: 
 6961: =cut
 6962: 
 6963: sub lonnet_putfile {
 6964:     my ($contents,$filename)=@_;
 6965:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6966:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6967:     $env{'form.sillywaytopassafilearound'}=$contents;
 6968:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 6969: 
 6970: }
 6971: 
 6972: =pod
 6973: 
 6974: =item scantron_putfile
 6975: 
 6976:     Stores the current version of the bubblesheet data files, and the
 6977:     scan_data hash. (Does not modify the original version only the
 6978:     corrected and skipped versions.
 6979: 
 6980:  Arguments:
 6981:     $scanlines - hash ref that looks like the first return value from
 6982:                  &scantron_getfile()
 6983:     $scan_data - hash ref that looks like the second return value from
 6984:                  &scantron_getfile()
 6985: 
 6986: =cut
 6987: 
 6988: sub scantron_putfile {
 6989:     my ($scanlines,$scan_data) = @_;
 6990:     #FIXME really would prefer a scantron directory
 6991:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6992:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6993:     if ($scanlines) {
 6994: 	my $prefix='scantron_';
 6995: # no need to update orig, shouldn't change
 6996: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 6997: #		    $env{'form.scantron_selectfile'});
 6998: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 6999: 			$prefix.'corrected_'.
 7000: 			$env{'form.scantron_selectfile'});
 7001: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 7002: 			$prefix.'skipped_'.
 7003: 			$env{'form.scantron_selectfile'});
 7004:     }
 7005:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 7006: }
 7007: 
 7008: =pod
 7009: 
 7010: =item scantron_get_line
 7011: 
 7012:    Returns the correct version of the scanline
 7013: 
 7014:  Arguments:
 7015:     $scanlines - hash ref that looks like the first return value from
 7016:                  &scantron_getfile()
 7017:     $scan_data - hash ref that looks like the second return value from
 7018:                  &scantron_getfile()
 7019:     $i         - number of the requested line (starts at 0)
 7020: 
 7021:  Returns:
 7022:    A scanline, (either the original or the corrected one if it
 7023:    exists), or undef if the requested scanline should be
 7024:    skipped. (Either because it's an skipped scanline, or it's an
 7025:    unskipped scanline and we are not doing a 'do skipped scanlines'
 7026:    pass.
 7027: 
 7028: =cut
 7029: 
 7030: sub scantron_get_line {
 7031:     my ($scanlines,$scan_data,$i)=@_;
 7032:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 7033:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 7034:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 7035:     return $scanlines->{'orig'}[$i]; 
 7036: }
 7037: 
 7038: =pod
 7039: 
 7040: =item scantron_todo_count
 7041: 
 7042:     Counts the number of scanlines that need processing.
 7043: 
 7044:  Arguments:
 7045:     $scanlines - hash ref that looks like the first return value from
 7046:                  &scantron_getfile()
 7047:     $scan_data - hash ref that looks like the second return value from
 7048:                  &scantron_getfile()
 7049: 
 7050:  Returns:
 7051:     $count - number of scanlines to process
 7052: 
 7053: =cut
 7054: 
 7055: sub get_todo_count {
 7056:     my ($scanlines,$scan_data)=@_;
 7057:     my $count=0;
 7058:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7059: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7060: 	if ($line=~/^[\s\cz]*$/) { next; }
 7061: 	$count++;
 7062:     }
 7063:     return $count;
 7064: }
 7065: 
 7066: =pod
 7067: 
 7068: =item scantron_put_line
 7069: 
 7070:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
 7071:     data file.
 7072: 
 7073:  Arguments:
 7074:     $scanlines - hash ref that looks like the first return value from
 7075:                  &scantron_getfile()
 7076:     $scan_data - hash ref that looks like the second return value from
 7077:                  &scantron_getfile()
 7078:     $i         - line number to update
 7079:     $newline   - contents of the updated scanline
 7080:     $skip      - if true make the line for skipping and update the
 7081:                  'skipped' file
 7082: 
 7083: =cut
 7084: 
 7085: sub scantron_put_line {
 7086:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 7087:     if ($skip) {
 7088: 	$scanlines->{'skipped'}[$i]=$newline;
 7089: 	&start_skipping($scan_data,$i);
 7090: 	return;
 7091:     }
 7092:     $scanlines->{'corrected'}[$i]=$newline;
 7093: }
 7094: 
 7095: =pod
 7096: 
 7097: =item scantron_clear_skip
 7098: 
 7099:    Remove a line from the 'skipped' file
 7100: 
 7101:  Arguments:
 7102:     $scanlines - hash ref that looks like the first return value from
 7103:                  &scantron_getfile()
 7104:     $scan_data - hash ref that looks like the second return value from
 7105:                  &scantron_getfile()
 7106:     $i         - line number to update
 7107: 
 7108: =cut
 7109: 
 7110: sub scantron_clear_skip {
 7111:     my ($scanlines,$scan_data,$i)=@_;
 7112:     if (exists($scanlines->{'skipped'}[$i])) {
 7113: 	undef($scanlines->{'skipped'}[$i]);
 7114: 	return 1;
 7115:     }
 7116:     return 0;
 7117: }
 7118: 
 7119: =pod
 7120: 
 7121: =item scantron_filter_not_exam
 7122: 
 7123:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 7124:    filter out resources that are not marked as 'exam' mode
 7125: 
 7126: =cut
 7127: 
 7128: sub scantron_filter_not_exam {
 7129:     my ($curres)=@_;
 7130:     
 7131:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 7132: 	# if the user has asked to not have either hidden
 7133: 	# or 'randomout' controlled resources to be graded
 7134: 	# don't include them
 7135: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 7136: 	    && $curres->randomout) {
 7137: 	    return 0;
 7138: 	}
 7139: 	return 1;
 7140:     }
 7141:     return 0;
 7142: }
 7143: 
 7144: =pod
 7145: 
 7146: =item scantron_validate_sequence
 7147: 
 7148:     Validates the selected sequence, checking for resource that are
 7149:     not set to exam mode.
 7150: 
 7151: =cut
 7152: 
 7153: sub scantron_validate_sequence {
 7154:     my ($r,$currentphase) = @_;
 7155: 
 7156:     my $navmap=Apache::lonnavmaps::navmap->new();
 7157:     unless (ref($navmap)) {
 7158:         $r->print(&navmap_errormsg());
 7159:         return (1,$currentphase);
 7160:     }
 7161:     my (undef,undef,$sequence)=
 7162: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7163: 
 7164:     my $map=$navmap->getResourceByUrl($sequence);
 7165: 
 7166:     $r->print('<input type="hidden" name="validate_sequence_exam"
 7167:                                     value="ignore" />');
 7168:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 7169: 	my @resources=
 7170: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 7171: 	if (@resources) {
 7172: 	    $r->print(
 7173:                 '<p class="LC_warning">'
 7174:                .&mt('Some resources in the sequence currently are not set to'
 7175:                    .' bubblesheet exam mode. Grading these resources currently may not'
 7176:                    .' work correctly.')
 7177:                .'</p>'
 7178:             );
 7179: 	    return (1,$currentphase);
 7180: 	}
 7181:     }
 7182: 
 7183:     return (0,$currentphase+1);
 7184: }
 7185: 
 7186: 
 7187: 
 7188: sub scantron_validate_ID {
 7189:     my ($r,$currentphase) = @_;
 7190:     
 7191:     #get student info
 7192:     my $classlist=&Apache::loncoursedata::get_classlist();
 7193:     my %idmap=&username_to_idmap($classlist);
 7194: 
 7195:     #get scantron line setup
 7196:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7197:     my ($scanlines,$scan_data)=&scantron_getfile();
 7198: 
 7199:     my $nav_error;
 7200:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
 7201:     if ($nav_error) {
 7202:         $r->print(&navmap_errormsg());
 7203:         return(1,$currentphase);
 7204:     }
 7205: 
 7206:     my %found=('ids'=>{},'usernames'=>{});
 7207:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7208: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7209: 	if ($line=~/^[\s\cz]*$/) { next; }
 7210: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7211: 						 $scan_data);
 7212: 	my $id=$$scan_record{'scantron.ID'};
 7213: 	my $found;
 7214: 	foreach my $checkid (keys(%idmap)) {
 7215: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 7216: 	}
 7217: 	if ($found) {
 7218: 	    my $username=$idmap{$found};
 7219: 	    if ($found{'ids'}{$found}) {
 7220: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7221: 					 $line,'duplicateID',$found);
 7222: 		return(1,$currentphase);
 7223: 	    } elsif ($found{'usernames'}{$username}) {
 7224: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7225: 					 $line,'duplicateID',$username);
 7226: 		return(1,$currentphase);
 7227: 	    }
 7228: 	    #FIXME store away line we previously saw the ID on to use above
 7229: 	    $found{'ids'}{$found}++;
 7230: 	    $found{'usernames'}{$username}++;
 7231: 	} else {
 7232: 	    if ($id =~ /^\s*$/) {
 7233: 		my $username=&scan_data($scan_data,"$i.user");
 7234: 		if (defined($username) && $found{'usernames'}{$username}) {
 7235: 		    &scantron_get_correction($r,$i,$scan_record,
 7236: 					     \%scantron_config,
 7237: 					     $line,'duplicateID',$username);
 7238: 		    return(1,$currentphase);
 7239: 		} elsif (!defined($username)) {
 7240: 		    &scantron_get_correction($r,$i,$scan_record,
 7241: 					     \%scantron_config,
 7242: 					     $line,'incorrectID');
 7243: 		    return(1,$currentphase);
 7244: 		}
 7245: 		$found{'usernames'}{$username}++;
 7246: 	    } else {
 7247: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7248: 					 $line,'incorrectID');
 7249: 		return(1,$currentphase);
 7250: 	    }
 7251: 	}
 7252:     }
 7253: 
 7254:     return (0,$currentphase+1);
 7255: }
 7256: 
 7257: 
 7258: sub scantron_get_correction {
 7259:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
 7260:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
 7261: #FIXME in the case of a duplicated ID the previous line, probably need
 7262: #to show both the current line and the previous one and allow skipping
 7263: #the previous one or the current one
 7264: 
 7265:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 7266:         $r->print(
 7267:             '<p class="LC_warning">'
 7268:            .&mt('An error was detected ([_1]) for PaperID [_2]',
 7269:                 "<b>$error</b>",
 7270:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
 7271:            ."</p> \n");
 7272:     } else {
 7273:         $r->print(
 7274:             '<p class="LC_warning">'
 7275:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
 7276:                 "<b>$error</b>", $i, "<pre>$line</pre>")
 7277:            ."</p> \n");
 7278:     }
 7279:     my $message =
 7280:         '<p>'
 7281:        .&mt('The ID on the form is [_1]',
 7282:             "<tt>$$scan_record{'scantron.ID'}</tt>")
 7283:        .'<br />'
 7284:        .&mt('The name on the paper is [_1], [_2]',
 7285:             $$scan_record{'scantron.LastName'},
 7286:             $$scan_record{'scantron.FirstName'})
 7287:        .'</p>';
 7288: 
 7289:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 7290:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 7291:                            # Array populated for doublebubble or
 7292:     my @lines_to_correct;  # missingbubble errors to build javascript
 7293:                            # to validate radio button checking   
 7294: 
 7295:     if ($error =~ /ID$/) {
 7296: 	if ($error eq 'incorrectID') {
 7297:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
 7298: 		      "</p>\n");
 7299: 	} elsif ($error eq 'duplicateID') {
 7300:             $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 7301: 	}
 7302: 	$r->print($message);
 7303: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 7304: 	$r->print("\n<ul><li> ");
 7305: 	#FIXME it would be nice if this sent back the user ID and
 7306: 	#could do partial userID matches
 7307: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 7308: 				       'scantron_username','scantron_domain'));
 7309: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 7310: 	$r->print("\n:\n".
 7311: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 7312: 
 7313: 	$r->print('</li>');
 7314:     } elsif ($error =~ /CODE$/) {
 7315: 	if ($error eq 'incorrectCODE') {
 7316: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 7317: 	} elsif ($error eq 'duplicateCODE') {
 7318: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE has also been used by a previous paper [_1], and CODEs are supposed to be unique.",join(', ',@{$arg}))."</p>\n");
 7319: 	}
 7320: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
 7321: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
 7322:                  ."</p>\n");
 7323: 	$r->print($message);
 7324: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
 7325: 	$r->print("\n<br /> ");
 7326: 	my $i=0;
 7327: 	if ($error eq 'incorrectCODE' 
 7328: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 7329: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 7330: 	    if ($closest > 0) {
 7331: 		foreach my $testcode (@{$closest}) {
 7332: 		    my $checked='';
 7333: 		    if (!$i) { $checked=' checked="checked"'; }
 7334: 		    $r->print("
 7335:    <label>
 7336:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 7337:        ".&mt("Use the similar CODE [_1] instead.",
 7338: 	    "<b><tt>".$testcode."</tt></b>")."
 7339:     </label>
 7340:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 7341: 		    $r->print("\n<br />");
 7342: 		    $i++;
 7343: 		}
 7344: 	    }
 7345: 	}
 7346: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 7347: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 7348: 	    $r->print("
 7349:     <label>
 7350:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 7351:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
 7352: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 7353:     </label>");
 7354: 	    $r->print("\n<br />");
 7355: 	}
 7356: 
 7357: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
 7358: function change_radio(field) {
 7359:     var slct=document.scantronupload.scantron_CODE_resolution;
 7360:     var i;
 7361:     for (i=0;i<slct.length;i++) {
 7362:         if (slct[i].value==field) { slct[i].checked=true; }
 7363:     }
 7364: }
 7365: ENDSCRIPT
 7366: 	my $href="/adm/pickcode?".
 7367: 	   "form=".&escape("scantronupload").
 7368: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 7369: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 7370: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 7371: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 7372: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 7373: 	    $r->print("
 7374:     <label>
 7375:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 7376:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 7377: 	     "<a target='_blank' href='$href'>","</a>")."
 7378:     </label> 
 7379:     ".&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\')" />'));
 7380: 	    $r->print("\n<br />");
 7381: 	}
 7382: 	$r->print("
 7383:     <label>
 7384:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 7385:        ".&mt("Use [_1] as the CODE.",
 7386: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 7387: 	$r->print("\n<br /><br />");
 7388:     } elsif ($error eq 'doublebubble') {
 7389: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 7390: 
 7391: 	# The form field scantron_questions is acutally a list of line numbers.
 7392: 	# represented by this form so:
 7393: 
 7394: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7395:                                                 $respnumlookup,$startline);
 7396: 
 7397: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7398: 		  $line_list.'" />');
 7399: 	$r->print($message);
 7400: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 7401: 	foreach my $question (@{$arg}) {
 7402: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7403:                                                    $scan_record, $error,
 7404:                                                    $randomorder,$randompick,
 7405:                                                    $respnumlookup,$startline);
 7406:             push(@lines_to_correct,@linenums);
 7407: 	}
 7408:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7409:     } elsif ($error eq 'missingbubble') {
 7410: 	$r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
 7411: 	$r->print($message);
 7412: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 7413: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 7414: 
 7415: 	# The form field scantron_questions is actually a list of line numbers not
 7416: 	# a list of question numbers. Therefore:
 7417: 	#
 7418: 
 7419: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7420:                                                 $respnumlookup,$startline);
 7421: 
 7422: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7423: 		  $line_list.'" />');
 7424: 	foreach my $question (@{$arg}) {
 7425: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7426:                                                    $scan_record, $error,
 7427:                                                    $randomorder,$randompick,
 7428:                                                    $respnumlookup,$startline);
 7429:             push(@lines_to_correct,@linenums);
 7430: 	}
 7431:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7432:     } else {
 7433: 	$r->print("\n<ul>");
 7434:     }
 7435:     $r->print("\n</li></ul>");
 7436: }
 7437: 
 7438: sub verify_bubbles_checked {
 7439:     my (@ansnums) = @_;
 7440:     my $ansnumstr = join('","',@ansnums);
 7441:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 7442:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
 7443: function verify_bubble_radio(form) {
 7444:     var ansnumArray = new Array ("$ansnumstr");
 7445:     var need_bubble_count = 0;
 7446:     for (var i=0; i<ansnumArray.length; i++) {
 7447:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 7448:             var bubble_picked = 0; 
 7449:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 7450:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 7451:                     bubble_picked = 1;
 7452:                 }
 7453:             }
 7454:             if (bubble_picked == 0) {
 7455:                 need_bubble_count ++;
 7456:             }
 7457:         }
 7458:     }
 7459:     if (need_bubble_count) {
 7460:         alert("$warning");
 7461:         return;
 7462:     }
 7463:     form.submit(); 
 7464: }
 7465: ENDSCRIPT
 7466:     return $output;
 7467: }
 7468: 
 7469: =pod
 7470: 
 7471: =item  questions_to_line_list
 7472: 
 7473: Converts a list of questions into a string of comma separated
 7474: line numbers in the answer sheet used by the questions.  This is
 7475: used to fill in the scantron_questions form field.
 7476: 
 7477:   Arguments:
 7478:      questions    - Reference to an array of questions.
 7479:      randomorder  - True if randomorder in use.
 7480:      randompick   - True if randompick in use.
 7481:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
 7482:                      for current line to question number used for same question
 7483:                      in "Master Seqence" (as seen by Course Coordinator).
 7484:      startline    - Reference to hash where key is question number (0 is first)
 7485:                     and key is number of first bubble line for current student
 7486:                     or code-based randompick and/or randomorder.
 7487: 
 7488: =cut
 7489: 
 7490: 
 7491: sub questions_to_line_list {
 7492:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
 7493:     my @lines;
 7494: 
 7495:     foreach my $item (@{$questions}) {
 7496:         my $question = $item;
 7497:         my ($first,$count,$last);
 7498:         if ($item =~ /^(\d+)\.(\d+)$/) {
 7499:             $question = $1;
 7500:             my $subquestion = $2;
 7501:             my $responsenum = $question-1;
 7502:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7503:                 $responsenum = $respnumlookup->{$question-1};
 7504:                 if (ref($startline) eq 'HASH') {
 7505:                     $first = $startline->{$question-1} + 1;
 7506:                 }
 7507:             } else {
 7508:                 $first = $first_bubble_line{$responsenum} + 1;
 7509:             }
 7510:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 7511:             my $subcount = 1;
 7512:             while ($subcount<$subquestion) {
 7513:                 $first += $subans[$subcount-1];
 7514:                 $subcount ++;
 7515:             }
 7516:             $count = $subans[$subquestion-1];
 7517:         } else {
 7518:             my $responsenum = $question-1;
 7519:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7520:                 $responsenum = $respnumlookup->{$question-1};
 7521:                 if (ref($startline) eq 'HASH') {
 7522:                     $first = $startline->{$question-1} + 1;
 7523:                 }
 7524:             } else {
 7525:                 $first = $first_bubble_line{$responsenum} + 1;
 7526:             }
 7527: 	    $count   = $bubble_lines_per_response{$responsenum};
 7528:         }
 7529:         $last = $first+$count-1;
 7530:         push(@lines, ($first..$last));
 7531:     }
 7532:     return join(',', @lines);
 7533: }
 7534: 
 7535: =pod 
 7536: 
 7537: =item prompt_for_corrections
 7538: 
 7539: Prompts for a potentially multiline correction to the
 7540: user's bubbling (factors out common code from scantron_get_correction
 7541: for multi and missing bubble cases).
 7542: 
 7543:  Arguments:
 7544:    $r           - Apache request object.
 7545:    $question    - The question number to prompt for.
 7546:    $scan_config - The scantron file configuration hash.
 7547:    $scan_record - Reference to the hash that has the the parsed scanlines.
 7548:    $error       - Type of error
 7549:    $randomorder - True if randomorder in use.
 7550:    $randompick  - True if randompick in use.
 7551:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
 7552:                     for current line to question number used for same question
 7553:                     in "Master Seqence" (as seen by Course Coordinator).
 7554:    $startline   - Reference to hash where key is question number (0 is first)
 7555:                   and value is number of first bubble line for current student
 7556:                   or code-based randompick and/or randomorder.
 7557: 
 7558: 
 7559:  Implicit inputs:
 7560:    %bubble_lines_per_response   - Starting line numbers for each question.
 7561:                                   Numbered from 0 (but question numbers are from
 7562:                                   1.
 7563:    %first_bubble_line           - Starting bubble line for each question.
 7564:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 7565:                                   type problems render as separate sub-questions, 
 7566:                                   in exam mode. This hash contains a 
 7567:                                   comma-separated list of the lines per 
 7568:                                   sub-question.
 7569:    %responsetype_per_response   - essayresponse, formularesponse,
 7570:                                   stringresponse, imageresponse, reactionresponse,
 7571:                                   and organicresponse type problem parts can have
 7572:                                   multiple lines per response if the weight
 7573:                                   assigned exceeds 10.  In this case, only
 7574:                                   one bubble per line is permitted, but more 
 7575:                                   than one line might contain bubbles, e.g.
 7576:                                   bubbling of: line 1 - J, line 2 - J, 
 7577:                                   line 3 - B would assign 22 points.  
 7578: 
 7579: =cut
 7580: 
 7581: sub prompt_for_corrections {
 7582:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
 7583:         $randompick, $respnumlookup, $startline) = @_;
 7584:     my ($current_line,$lines);
 7585:     my @linenums;
 7586:     my $questionnum = $question;
 7587:     my ($first,$responsenum);
 7588:     if ($question =~ /^(\d+)\.(\d+)$/) {
 7589:         $question = $1;
 7590:         my $subquestion = $2;
 7591:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7592:             $responsenum = $respnumlookup->{$question-1};
 7593:             if (ref($startline) eq 'HASH') {
 7594:                 $first = $startline->{$question-1};
 7595:             }
 7596:         } else {
 7597:             $responsenum = $question-1;
 7598:             $first = $first_bubble_line{$responsenum};
 7599:         }
 7600:         $current_line = $first + 1 ;
 7601:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 7602:         my $subcount = 1;
 7603:         while ($subcount<$subquestion) {
 7604:             $current_line += $subans[$subcount-1];
 7605:             $subcount ++;
 7606:         }
 7607:         $lines = $subans[$subquestion-1];
 7608:     } else {
 7609:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7610:             $responsenum = $respnumlookup->{$question-1};
 7611:             if (ref($startline) eq 'HASH') { 
 7612:                 $first = $startline->{$question-1};
 7613:             }
 7614:         } else {
 7615:             $responsenum = $question-1;
 7616:             $first = $first_bubble_line{$responsenum};
 7617:         }
 7618:         $current_line = $first + 1;
 7619:         $lines        = $bubble_lines_per_response{$responsenum};
 7620:     }
 7621:     if ($lines > 1) {
 7622:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7623:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 7624:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 7625:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 7626:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 7627:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 7628:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 7629:             $r->print(
 7630:                 &mt("Although this particular question type requires handgrading, the instructions for this question in the bubblesheet exam directed students to leave [quant,_1,line] blank on their bubblesheets.",$lines)
 7631:                .'<br /><br />'
 7632:                .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
 7633:                .'<br />'
 7634:                .&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.')
 7635:                .'<br />'
 7636:                .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
 7637:                .'<br /><br />'
 7638:             );
 7639:         } else {
 7640:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7641:         }
 7642:     }
 7643:     for (my $i =0; $i < $lines; $i++) {
 7644:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7645: 	&scantron_bubble_selector($r,$scan_config,$current_line,
 7646: 	        		  $questionnum,$error,split('', $selected));
 7647:         push(@linenums,$current_line);
 7648: 	$current_line++;
 7649:     }
 7650:     if ($lines > 1) {
 7651: 	$r->print("<hr /><br />");
 7652:     }
 7653:     return @linenums;
 7654: }
 7655: 
 7656: =pod
 7657: 
 7658: =item scantron_bubble_selector
 7659:   
 7660:    Generates the html radiobuttons to correct a single bubble line
 7661:    possibly showing the existing the selected bubbles if known
 7662: 
 7663:  Arguments:
 7664:     $r           - Apache request object
 7665:     $scan_config - hash from &get_scantron_config()
 7666:     $line        - Number of the line being displayed.
 7667:     $questionnum - Question number (may include subquestion)
 7668:     $error       - Type of error.
 7669:     @selected    - Array of bubbles picked on this line.
 7670: 
 7671: =cut
 7672: 
 7673: sub scantron_bubble_selector {
 7674:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7675:     my $max=$$scan_config{'Qlength'};
 7676: 
 7677:     my $scmode=$$scan_config{'Qon'};
 7678:     if ($scmode eq 'number' || $scmode eq 'letter') { 
 7679:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
 7680:             ($$scan_config{'BubblesPerRow'} > 0)) {
 7681:             $max=$$scan_config{'BubblesPerRow'};
 7682:             if (($scmode eq 'number') && ($max > 10)) {
 7683:                 $max = 10;
 7684:             } elsif (($scmode eq 'letter') && $max > 26) {
 7685:                 $max = 26;
 7686:             }
 7687:         } else {
 7688:             $max = 10;
 7689:         }
 7690:     }
 7691: 
 7692:     my @alphabet=('A'..'Z');
 7693:     $r->print(&Apache::loncommon::start_data_table().
 7694:               &Apache::loncommon::start_data_table_row());
 7695:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7696:     for (my $i=0;$i<$max+1;$i++) {
 7697: 	$r->print("\n".'<td align="center">');
 7698: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7699: 	else { $r->print('&nbsp;'); }
 7700: 	$r->print('</td>');
 7701:     }
 7702:     $r->print(&Apache::loncommon::end_data_table_row().
 7703:               &Apache::loncommon::start_data_table_row());
 7704:     for (my $i=0;$i<$max;$i++) {
 7705: 	$r->print("\n".
 7706: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7707: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7708:     }
 7709:     my $nobub_checked = ' ';
 7710:     if ($error eq 'missingbubble') {
 7711:         $nobub_checked = ' checked = "checked" ';
 7712:     }
 7713:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7714: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7715:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7716:               $line.'" value="'.$questionnum.'" /></td>');
 7717:     $r->print(&Apache::loncommon::end_data_table_row().
 7718:               &Apache::loncommon::end_data_table());
 7719: }
 7720: 
 7721: =pod
 7722: 
 7723: =item num_matches
 7724: 
 7725:    Counts the number of characters that are the same between the two arguments.
 7726: 
 7727:  Arguments:
 7728:    $orig - CODE from the scanline
 7729:    $code - CODE to match against
 7730: 
 7731:  Returns:
 7732:    $count - integer count of the number of same characters between the
 7733:             two arguments
 7734: 
 7735: =cut
 7736: 
 7737: sub num_matches {
 7738:     my ($orig,$code) = @_;
 7739:     my @code=split(//,$code);
 7740:     my @orig=split(//,$orig);
 7741:     my $same=0;
 7742:     for (my $i=0;$i<scalar(@code);$i++) {
 7743: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7744:     }
 7745:     return $same;
 7746: }
 7747: 
 7748: =pod
 7749: 
 7750: =item scantron_get_closely_matching_CODEs
 7751: 
 7752:    Cycles through all CODEs and finds the set that has the greatest
 7753:    number of same characters as the provided CODE
 7754: 
 7755:  Arguments:
 7756:    $allcodes - hash ref returned by &get_codes()
 7757:    $CODE     - CODE from the current scanline
 7758: 
 7759:  Returns:
 7760:    2 element list
 7761:     - first elements is number of how closely matching the best fit is 
 7762:       (5 means best set has 5 matching characters)
 7763:     - second element is an arrary ref containing the set of valid CODEs
 7764:       that best fit the passed in CODE
 7765: 
 7766: =cut
 7767: 
 7768: sub scantron_get_closely_matching_CODEs {
 7769:     my ($allcodes,$CODE)=@_;
 7770:     my @CODEs;
 7771:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7772: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7773:     }
 7774: 
 7775:     return ($#CODEs,$CODEs[-1]);
 7776: }
 7777: 
 7778: =pod
 7779: 
 7780: =item get_codes
 7781: 
 7782:    Builds a hash which has keys of all of the valid CODEs from the selected
 7783:    set of remembered CODEs.
 7784: 
 7785:  Arguments:
 7786:   $old_name - name of the set of remembered CODEs
 7787:   $cdom     - domain of the course
 7788:   $cnum     - internal course name
 7789: 
 7790:  Returns:
 7791:   %allcodes - keys are the valid CODEs, values are all 1
 7792: 
 7793: =cut
 7794: 
 7795: sub get_codes {
 7796:     my ($old_name, $cdom, $cnum) = @_;
 7797:     if (!$old_name) {
 7798: 	$old_name=$env{'form.scantron_CODElist'};
 7799:     }
 7800:     if (!$cdom) {
 7801: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7802:     }
 7803:     if (!$cnum) {
 7804: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7805:     }
 7806:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7807: 				    $cdom,$cnum);
 7808:     my %allcodes;
 7809:     if ($result{"type\0$old_name"} eq 'number') {
 7810: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7811:     } else {
 7812: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7813:     }
 7814:     return %allcodes;
 7815: }
 7816: 
 7817: =pod
 7818: 
 7819: =item scantron_validate_CODE
 7820: 
 7821:    Validates all scanlines in the selected file to not have any
 7822:    invalid or underspecified CODEs and that none of the codes are
 7823:    duplicated if this was requested.
 7824: 
 7825: =cut
 7826: 
 7827: sub scantron_validate_CODE {
 7828:     my ($r,$currentphase) = @_;
 7829:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7830:     if ($scantron_config{'CODElocation'} &&
 7831: 	$scantron_config{'CODEstart'} &&
 7832: 	$scantron_config{'CODElength'}) {
 7833: 	if (!defined($env{'form.scantron_CODElist'})) {
 7834: 	    &FIXME_blow_up()
 7835: 	}
 7836:     } else {
 7837: 	return (0,$currentphase+1);
 7838:     }
 7839:     
 7840:     my %usedCODEs;
 7841: 
 7842:     my %allcodes=&get_codes();
 7843: 
 7844:     my $nav_error;
 7845:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
 7846:     if ($nav_error) {
 7847:         $r->print(&navmap_errormsg());
 7848:         return(1,$currentphase);
 7849:     }
 7850: 
 7851:     my ($scanlines,$scan_data)=&scantron_getfile();
 7852:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7853: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7854: 	if ($line=~/^[\s\cz]*$/) { next; }
 7855: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7856: 						 $scan_data);
 7857: 	my $CODE=$$scan_record{'scantron.CODE'};
 7858: 	my $error=0;
 7859: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7860: 	    &scantron_get_correction($r,$i,$scan_record,
 7861: 				     \%scantron_config,
 7862: 				     $line,'incorrectCODE',\%allcodes);
 7863: 	    return(1,$currentphase);
 7864: 	}
 7865: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7866: 	    && !$$scan_record{'scantron.useCODE'}) {
 7867: 	    &scantron_get_correction($r,$i,$scan_record,
 7868: 				     \%scantron_config,
 7869: 				     $line,'incorrectCODE',\%allcodes);
 7870: 	    return(1,$currentphase);
 7871: 	}
 7872: 	if (exists($usedCODEs{$CODE}) 
 7873: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 7874: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 7875: 	    &scantron_get_correction($r,$i,$scan_record,
 7876: 				     \%scantron_config,
 7877: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 7878: 	    return(1,$currentphase);
 7879: 	}
 7880: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 7881:     }
 7882:     return (0,$currentphase+1);
 7883: }
 7884: 
 7885: =pod
 7886: 
 7887: =item scantron_validate_doublebubble
 7888: 
 7889:    Validates all scanlines in the selected file to not have any
 7890:    bubble lines with multiple bubbles marked.
 7891: 
 7892: =cut
 7893: 
 7894: sub scantron_validate_doublebubble {
 7895:     my ($r,$currentphase) = @_;
 7896:     #get student info
 7897:     my $classlist=&Apache::loncoursedata::get_classlist();
 7898:     my %idmap=&username_to_idmap($classlist);
 7899:     my (undef,undef,$sequence)=
 7900:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 7901: 
 7902:     #get scantron line setup
 7903:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7904:     my ($scanlines,$scan_data)=&scantron_getfile();
 7905: 
 7906:     my $navmap = Apache::lonnavmaps::navmap->new();
 7907:     unless (ref($navmap)) {
 7908:         $r->print(&navmap_errormsg());
 7909:         return(1,$currentphase);
 7910:     }
 7911:     my $map=$navmap->getResourceByUrl($sequence);
 7912:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7913:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 7914:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 7915:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 7916: 
 7917:     my $nav_error;
 7918:     if (ref($map)) {
 7919:         $randomorder = $map->randomorder();
 7920:         $randompick = $map->randompick();
 7921:         if ($randomorder || $randompick) {
 7922:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 7923:             if ($nav_error) {
 7924:                 $r->print(&navmap_errormsg());
 7925:                 return(1,$currentphase);
 7926:             }
 7927:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 7928:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 7929:         }
 7930:     } else {
 7931:         $r->print(&navmap_errormsg());
 7932:         return(1,$currentphase);
 7933:     }
 7934: 
 7935:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
 7936:     if ($nav_error) {
 7937:         $r->print(&navmap_errormsg());
 7938:         return(1,$currentphase);
 7939:     }
 7940: 
 7941:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7942: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7943: 	if ($line=~/^[\s\cz]*$/) { next; }
 7944: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7945: 						 $scan_data,undef,\%idmap,$randomorder,
 7946:                                                  $randompick,$sequence,\@master_seq,
 7947:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 7948:                                                  \%orderedforcode,\%respnumlookup,\%startline);
 7949: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 7950: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 7951: 				 'doublebubble',
 7952: 				 $$scan_record{'scantron.doubleerror'},
 7953:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
 7954:     	return (1,$currentphase);
 7955:     }
 7956:     return (0,$currentphase+1);
 7957: }
 7958: 
 7959: 
 7960: sub scantron_get_maxbubble {
 7961:     my ($nav_error,$scantron_config) = @_;
 7962:     if (defined($env{'form.scantron_maxbubble'}) &&
 7963: 	$env{'form.scantron_maxbubble'}) {
 7964: 	&restore_bubble_lines();
 7965: 	return $env{'form.scantron_maxbubble'};
 7966:     }
 7967: 
 7968:     my (undef, undef, $sequence) =
 7969: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7970: 
 7971:     my $navmap=Apache::lonnavmaps::navmap->new();
 7972:     unless (ref($navmap)) {
 7973:         if (ref($nav_error)) {
 7974:             $$nav_error = 1;
 7975:         }
 7976:         return;
 7977:     }
 7978:     my $map=$navmap->getResourceByUrl($sequence);
 7979:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7980:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
 7981: 
 7982:     &Apache::lonxml::clear_problem_counter();
 7983: 
 7984:     my $uname       = $env{'user.name'};
 7985:     my $udom        = $env{'user.domain'};
 7986:     my $cid         = $env{'request.course.id'};
 7987:     my $total_lines = 0;
 7988:     %bubble_lines_per_response = ();
 7989:     %first_bubble_line         = ();
 7990:     %subdivided_bubble_lines   = ();
 7991:     %responsetype_per_response = ();
 7992:     %masterseq_id_responsenum  = ();
 7993: 
 7994:     my $response_number = 0;
 7995:     my $bubble_line     = 0;
 7996:     foreach my $resource (@resources) {
 7997:         my $resid = $resource->id(); 
 7998:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
 7999:                                                           $udom,undef,$bubbles_per_row);
 8000:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 8001: 	    foreach my $part_id (@{$parts}) {
 8002:                 my $lines;
 8003: 
 8004: 	        # TODO - make this a persistent hash not an array.
 8005: 
 8006:                 # optionresponse, matchresponse and rankresponse type items 
 8007:                 # render as separate sub-questions in exam mode.
 8008:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 8009:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 8010:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 8011:                     my ($numbub,$numshown);
 8012:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 8013:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 8014:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 8015:                         }
 8016:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 8017:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 8018:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 8019:                         }
 8020:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 8021:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 8022:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 8023:                         }
 8024:                     }
 8025:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 8026:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 8027:                     }
 8028:                     my $bubbles_per_row =
 8029:                         &bubblesheet_bubbles_per_row($scantron_config);
 8030:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
 8031:                     if (($numbub % $bubbles_per_row) != 0) {
 8032:                         $inner_bubble_lines++;
 8033:                     }
 8034:                     for (my $i=0; $i<$numshown; $i++) {
 8035:                         $subdivided_bubble_lines{$response_number} .= 
 8036:                             $inner_bubble_lines.',';
 8037:                     }
 8038:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 8039:                     $lines = $numshown * $inner_bubble_lines;
 8040:                 } else {
 8041:                     $lines = $analysis->{"$part_id.bubble_lines"};
 8042:                 }
 8043: 
 8044:                 $first_bubble_line{$response_number} = $bubble_line;
 8045: 	        $bubble_lines_per_response{$response_number} = $lines;
 8046:                 $responsetype_per_response{$response_number} = 
 8047:                     $analysis->{$part_id.'.type'};
 8048:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;  
 8049: 	        $response_number++;
 8050: 
 8051: 	        $bubble_line +=  $lines;
 8052: 	        $total_lines +=  $lines;
 8053: 	    }
 8054:         }
 8055:     }
 8056:     &Apache::lonnet::delenv('scantron.');
 8057: 
 8058:     &save_bubble_lines();
 8059:     $env{'form.scantron_maxbubble'} =
 8060: 	$total_lines;
 8061:     return $env{'form.scantron_maxbubble'};
 8062: }
 8063: 
 8064: sub bubblesheet_bubbles_per_row {
 8065:     my ($scantron_config) = @_;
 8066:     my $bubbles_per_row;
 8067:     if (ref($scantron_config) eq 'HASH') {
 8068:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
 8069:     }
 8070:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
 8071:         $bubbles_per_row = 10;
 8072:     }
 8073:     return $bubbles_per_row;
 8074: }
 8075: 
 8076: sub scantron_validate_missingbubbles {
 8077:     my ($r,$currentphase) = @_;
 8078:     #get student info
 8079:     my $classlist=&Apache::loncoursedata::get_classlist();
 8080:     my %idmap=&username_to_idmap($classlist);
 8081:     my (undef,undef,$sequence)=
 8082:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8083: 
 8084:     #get scantron line setup
 8085:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8086:     my ($scanlines,$scan_data)=&scantron_getfile();
 8087: 
 8088:     my $navmap = Apache::lonnavmaps::navmap->new();
 8089:     unless (ref($navmap)) {
 8090:         $r->print(&navmap_errormsg());
 8091:         return(1,$currentphase);
 8092:     }
 8093: 
 8094:     my $map=$navmap->getResourceByUrl($sequence);
 8095:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8096:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8097:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8098:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8099: 
 8100:     my $nav_error;
 8101:     if (ref($map)) {
 8102:         $randomorder = $map->randomorder();
 8103:         $randompick = $map->randompick();
 8104:         if ($randomorder || $randompick) {
 8105:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8106:             if ($nav_error) {
 8107:                 $r->print(&navmap_errormsg());
 8108:                 return(1,$currentphase);
 8109:             }
 8110:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8111:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8112:         }
 8113:     } else {
 8114:         $r->print(&navmap_errormsg());
 8115:         return(1,$currentphase);
 8116:     }
 8117: 
 8118: 
 8119:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 8120:     if ($nav_error) {
 8121:         $r->print(&navmap_errormsg());
 8122:         return(1,$currentphase);
 8123:     }
 8124: 
 8125:     if (!$max_bubble) { $max_bubble=2**31; }
 8126:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8127: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8128: 	if ($line=~/^[\s\cz]*$/) { next; }
 8129: 	my $scan_record =
 8130:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
 8131: 				     $randomorder,$randompick,$sequence,\@master_seq,
 8132:                                      \%symb_to_resource,\%grader_partids_by_symb,
 8133:                                      \%orderedforcode,\%respnumlookup,\%startline);
 8134: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 8135: 	my @to_correct;
 8136: 	
 8137: 	# Probably here's where the error is...
 8138: 
 8139: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 8140:             my $lastbubble;
 8141:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 8142:                my $question = $1;
 8143:                my $subquestion = $2;
 8144:                my ($first,$responsenum);
 8145:                if ($randomorder || $randompick) {
 8146:                    $responsenum = $respnumlookup{$question-1};
 8147:                    $first = $startline{$question-1};
 8148:                } else {
 8149:                    $responsenum = $question-1; 
 8150:                    $first = $first_bubble_line{$responsenum};
 8151:                }
 8152:                if (!defined($first)) { next; }
 8153:                my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8154:                my $subcount = 1;
 8155:                while ($subcount<$subquestion) {
 8156:                    $first += $subans[$subcount-1];
 8157:                    $subcount ++;
 8158:                }
 8159:                my $count = $subans[$subquestion-1];
 8160:                $lastbubble = $first + $count;
 8161:             } else {
 8162:                my ($first,$responsenum);
 8163:                if ($randomorder || $randompick) {
 8164:                    $responsenum = $respnumlookup{$missing-1};
 8165:                    $first = $startline{$missing-1};
 8166:                } else {
 8167:                    $responsenum = $missing-1;
 8168:                    $first = $first_bubble_line{$responsenum};
 8169:                }
 8170:                if (!defined($first)) { next; }
 8171:                $lastbubble = $first + $bubble_lines_per_response{$responsenum};
 8172:             }
 8173:             if ($lastbubble > $max_bubble) { next; }
 8174: 	    push(@to_correct,$missing);
 8175: 	}
 8176: 	if (@to_correct) {
 8177: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 8178: 				     $line,'missingbubble',\@to_correct,
 8179:                                      $randomorder,$randompick,\%respnumlookup,
 8180:                                      \%startline);
 8181: 	    return (1,$currentphase);
 8182: 	}
 8183: 
 8184:     }
 8185:     return (0,$currentphase+1);
 8186: }
 8187: 
 8188: sub hand_bubble_option {
 8189:     my (undef, undef, $sequence) =
 8190:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8191:     return if ($sequence eq '');
 8192:     my $navmap = Apache::lonnavmaps::navmap->new();
 8193:     unless (ref($navmap)) {
 8194:         return;
 8195:     }
 8196:     my $needs_hand_bubbles;
 8197:     my $map=$navmap->getResourceByUrl($sequence);
 8198:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8199:     foreach my $res (@resources) {
 8200:         if (ref($res)) {
 8201:             if ($res->is_problem()) {
 8202:                 my $partlist = $res->parts();
 8203:                 foreach my $part (@{ $partlist }) {
 8204:                     my @types = $res->responseType($part);
 8205:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
 8206:                         $needs_hand_bubbles = 1;
 8207:                         last;
 8208:                     }
 8209:                 }
 8210:             }
 8211:         }
 8212:     }
 8213:     if ($needs_hand_bubbles) {
 8214:         my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8215:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8216:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
 8217:                &mt('If you have already graded these by bubbling sheets to indicate points awarded, [_1]what point value is assigned to a filled last bubble in each row?','<br />').
 8218:                '<label><input type="radio" name="scantron_lastbubblepoints" value="'.$bubbles_per_row.'" checked="checked" />'.&mt('[quant,_1,point]',$bubbles_per_row).'</label>&nbsp;'.&mt('or').'&nbsp;'.
 8219:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0"/>0 points</label></p>';
 8220:     }
 8221:     return;
 8222: }
 8223: 
 8224: sub scantron_process_students {
 8225:     my ($r,$symb) = @_;
 8226: 
 8227:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8228:     if (!$symb) {
 8229: 	return '';
 8230:     }
 8231:     my $default_form_data=&defaultFormData($symb);
 8232: 
 8233:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8234:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config); 
 8235:     my ($scanlines,$scan_data)=&scantron_getfile();
 8236:     my $classlist=&Apache::loncoursedata::get_classlist();
 8237:     my %idmap=&username_to_idmap($classlist);
 8238:     my $navmap=Apache::lonnavmaps::navmap->new();
 8239:     unless (ref($navmap)) {
 8240:         $r->print(&navmap_errormsg());
 8241:         return '';
 8242:     }
 8243:     my $map=$navmap->getResourceByUrl($sequence);
 8244:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8245:         %grader_randomlists_by_symb);
 8246:     if (ref($map)) {
 8247:         $randomorder = $map->randomorder();
 8248:         $randompick = $map->randompick();
 8249:     } else {
 8250:         $r->print(&navmap_errormsg());
 8251:         return '';
 8252:     }
 8253:     my $nav_error;
 8254:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8255:     if ($randomorder || $randompick) {
 8256:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8257:         if ($nav_error) {
 8258:             $r->print(&navmap_errormsg());
 8259:             return '';
 8260:         }
 8261:     }
 8262:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8263:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 8264: 
 8265:     my ($uname,$udom);
 8266:     my $result= <<SCANTRONFORM;
 8267: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 8268:   <input type="hidden" name="command" value="scantron_configphase" />
 8269:   $default_form_data
 8270: SCANTRONFORM
 8271:     $r->print($result);
 8272: 
 8273:     my @delayqueue;
 8274:     my (%completedstudents,%scandata);
 8275:     
 8276:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 8277:     my $count=&get_todo_count($scanlines,$scan_data);
 8278:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 8279:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
 8280:     $r->print('<br />');
 8281:     my $start=&Time::HiRes::time();
 8282:     my $i=-1;
 8283:     my $started;
 8284: 
 8285:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 8286:     if ($nav_error) {
 8287:         $r->print(&navmap_errormsg());
 8288:         return '';
 8289:     }
 8290: 
 8291:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 8292:     # the user and return.
 8293: 
 8294:     if ($ssi_error) {
 8295: 	$r->print("</form>");
 8296: 	&ssi_print_error($r);
 8297:         &Apache::lonnet::remove_lock($lock);
 8298: 	return '';		# Dunno why the other returns return '' rather than just returning.
 8299:     }
 8300: 
 8301:     my %lettdig = &letter_to_digits();
 8302:     my $numletts = scalar(keys(%lettdig));
 8303:     my %orderedforcode;
 8304: 
 8305:     while ($i<$scanlines->{'count'}) {
 8306:  	($uname,$udom)=('','');
 8307:  	$i++;
 8308:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8309:  	if ($line=~/^[\s\cz]*$/) { next; }
 8310: 	if ($started) {
 8311: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 8312: 	}
 8313: 	$started=1;
 8314:         my %respnumlookup = ();
 8315:         my %startline = ();
 8316:         my $total;
 8317:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8318:                                                  $scan_data,undef,\%idmap,$randomorder,
 8319:                                                  $randompick,$sequence,\@master_seq,
 8320:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8321:                                                  \%orderedforcode,\%respnumlookup,\%startline,
 8322:                                                  \$total);
 8323:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 8324:  					      \%idmap,$i)) {
 8325:   	    &scantron_add_delay(\@delayqueue,$line,
 8326:  				'Unable to find a student that matches',1);
 8327:  	    next;
 8328:   	}
 8329:  	if (exists $completedstudents{$uname}) {
 8330:  	    &scantron_add_delay(\@delayqueue,$line,
 8331:  				'Student '.$uname.' has multiple sheets',2);
 8332:  	    next;
 8333:  	}
 8334:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 8335:         my $user = $uname.':'.$usec;
 8336:   	($uname,$udom)=split(/:/,$uname);
 8337: 
 8338:         my $scancode;
 8339:         if ((exists($scan_record->{'scantron.CODE'})) &&
 8340:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 8341:             $scancode = $scan_record->{'scantron.CODE'};
 8342:         } else {
 8343:             $scancode = '';
 8344:         }
 8345: 
 8346:         my @mapresources = @resources;
 8347:         if ($randomorder || $randompick) {
 8348:             @mapresources = 
 8349:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 8350:                              \%orderedforcode);
 8351:         }
 8352:         my (%partids_by_symb,$res_error);
 8353:         foreach my $resource (@mapresources) {
 8354:             my $ressymb;
 8355:             if (ref($resource)) {
 8356:                 $ressymb = $resource->symb();
 8357:             } else {
 8358:                 $res_error = 1;
 8359:                 last;
 8360:             }
 8361:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8362:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8363:                 my ($analysis,$parts) =
 8364:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 8365:                                               $uname,$udom,undef,$bubbles_per_row);
 8366:                 $partids_by_symb{$ressymb} = $parts;
 8367:             } else {
 8368:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 8369:             }
 8370:         }
 8371: 
 8372:         if ($res_error) {
 8373:             &scantron_add_delay(\@delayqueue,$line,
 8374:                                 'An error occurred while grading student '.$uname,2);
 8375:             next;
 8376:         }
 8377: 
 8378: 	&Apache::lonxml::clear_problem_counter();
 8379:   	&Apache::lonnet::appenv($scan_record);
 8380: 
 8381: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 8382: 	    &scantron_putfile($scanlines,$scan_data);
 8383: 	}
 8384: 	
 8385:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8386:                                    \@mapresources,\%partids_by_symb,
 8387:                                    $bubbles_per_row,$randomorder,$randompick,
 8388:                                    \%respnumlookup,\%startline) 
 8389:             eq 'ssi_error') {
 8390:             $ssi_error = 0; # So end of handler error message does not trigger.
 8391:             $r->print("</form>");
 8392:             &ssi_print_error($r);
 8393:             &Apache::lonnet::remove_lock($lock);
 8394:             return '';      # Why return ''?  Beats me.
 8395:         }
 8396: 
 8397:         if (($scancode) && ($randomorder || $randompick)) {
 8398:             my $parmresult =
 8399:                 &Apache::lonparmset::storeparm_by_symb($symb,
 8400:                                                        '0_examcode',2,$scancode,
 8401:                                                        'string_examcode',$uname,
 8402:                                                        $udom);
 8403:         }
 8404: 	$completedstudents{$uname}={'line'=>$line};
 8405:         if ($env{'form.verifyrecord'}) {
 8406:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8407:             if ($randompick) {
 8408:                 if ($total) {
 8409:                     $lastpos = $total*$scantron_config{'Qlength'};
 8410:                 }
 8411:             }
 8412: 
 8413:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8414:             chomp($studentdata);
 8415:             $studentdata =~ s/\r$//;
 8416:             my $studentrecord = '';
 8417:             my $counter = -1;
 8418:             foreach my $resource (@mapresources) {
 8419:                 my $ressymb = $resource->symb();
 8420:                 ($counter,my $recording) =
 8421:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8422:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 8423:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
 8424:                                              $randompick,\%respnumlookup,\%startline);
 8425:                 $studentrecord .= $recording;
 8426:             }
 8427:             if ($studentrecord ne $studentdata) {
 8428:                 &Apache::lonxml::clear_problem_counter();
 8429:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8430:                                            \@mapresources,\%partids_by_symb,
 8431:                                            $bubbles_per_row,$randomorder,$randompick,
 8432:                                            \%respnumlookup,\%startline) 
 8433:                     eq 'ssi_error') {
 8434:                     $ssi_error = 0; # So end of handler error message does not trigger.
 8435:                     $r->print("</form>");
 8436:                     &ssi_print_error($r);
 8437:                     &Apache::lonnet::remove_lock($lock);
 8438:                     delete($completedstudents{$uname});
 8439:                     return '';
 8440:                 }
 8441:                 $counter = -1;
 8442:                 $studentrecord = '';
 8443:                 foreach my $resource (@mapresources) {
 8444:                     my $ressymb = $resource->symb();
 8445:                     ($counter,my $recording) =
 8446:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8447:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 8448:                                                  \%scantron_config,\%lettdig,$numletts,
 8449:                                                  $randomorder,$randompick,\%respnumlookup,
 8450:                                                  \%startline);
 8451:                     $studentrecord .= $recording;
 8452:                 }
 8453:                 if ($studentrecord ne $studentdata) {
 8454:                     $r->print('<p><span class="LC_warning">');
 8455:                     if ($scancode eq '') {
 8456:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
 8457:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 8458:                     } else {
 8459:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
 8460:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 8461:                     }
 8462:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 8463:                               &Apache::loncommon::start_data_table_header_row()."\n".
 8464:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 8465:                               &Apache::loncommon::end_data_table_header_row()."\n".
 8466:                               &Apache::loncommon::start_data_table_row().
 8467:                               '<td>'.&mt('Bubblesheet').'</td>'.
 8468:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
 8469:                               &Apache::loncommon::end_data_table_row().
 8470:                               &Apache::loncommon::start_data_table_row().
 8471:                               '<td>'.&mt('Stored submissions').'</td>'.
 8472:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
 8473:                               &Apache::loncommon::end_data_table_row().
 8474:                               &Apache::loncommon::end_data_table().'</p>');
 8475:                 } else {
 8476:                     $r->print('<br /><span class="LC_warning">'.
 8477:                              &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 />'.
 8478:                              &mt("As a consequence, this user's submission history records two tries.").
 8479:                                  '</span><br />');
 8480:                 }
 8481:             }
 8482:         }
 8483:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 8484:     } continue {
 8485: 	&Apache::lonxml::clear_problem_counter();
 8486: 	&Apache::lonnet::delenv('scantron.');
 8487:     }
 8488:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8489:     &Apache::lonnet::remove_lock($lock);
 8490: #    my $lasttime = &Time::HiRes::time()-$start;
 8491: #    $r->print("<p>took $lasttime</p>");
 8492: 
 8493:     $r->print("</form>");
 8494:     return '';
 8495: }
 8496: 
 8497: sub graders_resources_pass {
 8498:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
 8499:         $bubbles_per_row) = @_;
 8500:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 8501:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 8502:         foreach my $resource (@{$resources}) {
 8503:             my $ressymb = $resource->symb();
 8504:             my ($analysis,$parts) =
 8505:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 8506:                                           $env{'user.name'},$env{'user.domain'},
 8507:                                           1,$bubbles_per_row);
 8508:             $grader_partids_by_symb->{$ressymb} = $parts;
 8509:             if (ref($analysis) eq 'HASH') {
 8510:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 8511:                     $grader_randomlists_by_symb->{$ressymb} =
 8512:                         $analysis->{'parts_withrandomlist'};
 8513:                 }
 8514:             }
 8515:         }
 8516:     }
 8517:     return;
 8518: }
 8519: 
 8520: =pod
 8521: 
 8522: =item users_order
 8523: 
 8524:   Returns array of resources in current map, ordered based on either CODE,
 8525:   if this is a CODEd exam, or based on student's identity if this is a 
 8526:   "NAMEd" exam.
 8527: 
 8528:   Should be used when randomorder and/or randompick applied when the 
 8529:   corresponding exam was printed, prior to students completing bubblesheets 
 8530:   for the version of the exam the student received.
 8531: 
 8532: =cut
 8533: 
 8534: sub users_order  {
 8535:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
 8536:     my @mapresources;
 8537:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
 8538:         return @mapresources;
 8539:     }
 8540:     if ($scancode) {
 8541:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
 8542:             @mapresources = @{$orderedforcode->{$scancode}};
 8543:         } else {
 8544:             $env{'form.CODE'} = $scancode;
 8545:             my $actual_seq =
 8546:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 8547:                                                                $master_seq,
 8548:                                                                $user,$scancode,1);
 8549:             if (ref($actual_seq) eq 'ARRAY') {
 8550:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
 8551:                 if (ref($orderedforcode) eq 'HASH') {
 8552:                     if (@mapresources > 0) { 
 8553:                         $orderedforcode->{$scancode} = \@mapresources;
 8554:                     }
 8555:                 }
 8556:             }
 8557:             delete($env{'form.CODE'});
 8558:         }
 8559:     } else {
 8560:         my $actual_seq =
 8561:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 8562:                                                            $master_seq,
 8563:                                                            $user,undef,1);
 8564:         if (ref($actual_seq) eq 'ARRAY') {
 8565:             @mapresources = 
 8566:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
 8567:         }
 8568:     }
 8569:     return @mapresources;
 8570: }
 8571: 
 8572: sub grade_student_bubbles {
 8573:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
 8574:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
 8575:     my $uselookup = 0;
 8576:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
 8577:         (ref($startline) eq 'HASH')) {
 8578:         $uselookup = 1;
 8579:     }
 8580: 
 8581:     if (ref($resources) eq 'ARRAY') {
 8582:         my $count = 0;
 8583:         foreach my $resource (@{$resources}) {
 8584:             my $ressymb = $resource->symb();
 8585:             my %form = ('submitted'      => 'scantron',
 8586:                         'grade_target'   => 'grade',
 8587:                         'grade_username' => $uname,
 8588:                         'grade_domain'   => $udom,
 8589:                         'grade_courseid' => $env{'request.course.id'},
 8590:                         'grade_symb'     => $ressymb,
 8591:                         'CODE'           => $scancode
 8592:                        );
 8593:             if ($bubbles_per_row ne '') {
 8594:                 $form{'bubbles_per_row'} = $bubbles_per_row;
 8595:             }
 8596:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
 8597:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
 8598:             }
 8599:             if (ref($parts) eq 'HASH') {
 8600:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 8601:                     foreach my $part (@{$parts->{$ressymb}}) {
 8602:                         if ($uselookup) {
 8603:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
 8604:                         } else {
 8605:                             $form{'scantron_questnum_start.'.$part} =
 8606:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
 8607:                         }
 8608:                         $count++;
 8609:                     }
 8610:                 }
 8611:             }
 8612:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 8613:             return 'ssi_error' if ($ssi_error);
 8614:             last if (&Apache::loncommon::connection_aborted($r));
 8615:         }
 8616:     }
 8617:     return;
 8618: }
 8619: 
 8620: sub scantron_upload_scantron_data {
 8621:     my ($r,$symb)=@_;
 8622:     my $dom = $env{'request.role.domain'};
 8623:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 8624:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 8625:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 8626: 							  'domainid',
 8627: 							  'coursename',$dom);
 8628:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 8629:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
 8630:     my $default_form_data=&defaultFormData($symb);
 8631:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 8632:     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.");
 8633:     $r->print(&Apache::lonhtmlcommon::scripttag('
 8634:     function checkUpload(formname) {
 8635: 	if (formname.upfile.value == "") {
 8636: 	    alert("'.$nofile_alert.'");
 8637: 	    return false;
 8638: 	}
 8639:         if (formname.courseid.value == "") {
 8640:             alert("'.$nocourseid_alert.'");
 8641:             return false;
 8642:         }
 8643: 	formname.submit();
 8644:     }
 8645: 
 8646:     function ToSyllabus() {
 8647:         var cdom = '."'$dom'".';
 8648:         var cnum = document.rules.courseid.value;
 8649:         if (cdom == "" || cdom == null) {
 8650:             return;
 8651:         }
 8652:         if (cnum == "" || cnum == null) {
 8653:            return;
 8654:         }
 8655:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 8656:                             "height=350,width=350,scrollbars=yes,menubar=no");
 8657:         return;
 8658:     }
 8659: 
 8660: '));
 8661:     $r->print('
 8662: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
 8663: 
 8664: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 8665: '.$default_form_data.
 8666:   &Apache::lonhtmlcommon::start_pick_box().
 8667:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 8668:   '<input name="courseid" type="text" size="30" />'.$select_link.
 8669:   &Apache::lonhtmlcommon::row_closure().
 8670:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 8671:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 8672:   &Apache::lonhtmlcommon::row_closure().
 8673:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 8674:   '<input name="domainid" type="hidden" />'.$domdesc.
 8675:   &Apache::lonhtmlcommon::row_closure().
 8676:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 8677:   '<input type="file" name="upfile" size="50" />'.
 8678:   &Apache::lonhtmlcommon::row_closure(1).
 8679:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 8680: 
 8681: <input name="command" value="scantronupload_save" type="hidden" />
 8682: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 8683: </form>
 8684: ');
 8685:     return '';
 8686: }
 8687: 
 8688: 
 8689: sub scantron_upload_scantron_data_save {
 8690:     my($r,$symb)=@_;
 8691:     my $doanotherupload=
 8692: 	'<br /><form action="/adm/grades" method="post">'."\n".
 8693: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 8694: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 8695: 	'</form>'."\n";
 8696:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 8697: 	!&Apache::lonnet::allowed('usc',
 8698: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 8699: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 8700: 	unless ($symb) {
 8701: 	    $r->print($doanotherupload);
 8702: 	}
 8703: 	return '';
 8704:     }
 8705:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 8706:     my $uploadedfile;
 8707:     $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
 8708:     if (length($env{'form.upfile'}) < 2) {
 8709:         $r->print(
 8710:             &Apache::lonhtmlcommon::confirm_success(
 8711:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
 8712:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
 8713:     } else {
 8714:         my $result = 
 8715:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
 8716:                                             $env{'form.courseid'},$env{'form.domainid'});
 8717:         if ($result =~ m{^/uploaded/}) {
 8718:             $r->print(
 8719:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
 8720:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
 8721:                         (length($env{'form.upfile'})-1),
 8722:                         '<span class="LC_filename">'.$result.'</span>'));
 8723:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 8724:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 8725:                                                        $env{'form.courseid'},$uploadedfile));
 8726:         } else {
 8727:             $r->print(
 8728:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
 8729:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
 8730:                           $result,
 8731: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 8732: 	}
 8733:     }
 8734:     if ($symb) {
 8735: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
 8736:     } else {
 8737: 	$r->print($doanotherupload);
 8738:     }
 8739:     return '';
 8740: }
 8741: 
 8742: sub validate_uploaded_scantron_file {
 8743:     my ($cdom,$cname,$fname) = @_;
 8744:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 8745:     my @lines;
 8746:     if ($scanlines ne '-1') {
 8747:         @lines=split("\n",$scanlines,-1);
 8748:     }
 8749:     my $output;
 8750:     if (@lines) {
 8751:         my (%counts,$max_match_format);
 8752:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
 8753:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 8754:         my %idmap = &username_to_idmap($classlist);
 8755:         foreach my $key (keys(%idmap)) {
 8756:             my $lckey = lc($key);
 8757:             $idmap{$lckey} = $idmap{$key};
 8758:         }
 8759:         my %unique_formats;
 8760:         my @formatlines = &get_scantronformat_file();
 8761:         foreach my $line (@formatlines) {
 8762:             chomp($line);
 8763:             my @config = split(/:/,$line);
 8764:             my $idstart = $config[5];
 8765:             my $idlength = $config[6];
 8766:             if (($idstart ne '') && ($idlength > 0)) {
 8767:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 8768:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 8769:                 } else {
 8770:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 8771:                 }
 8772:             }
 8773:         }
 8774:         foreach my $key (keys(%unique_formats)) {
 8775:             my ($idstart,$idlength) = split(':',$key);
 8776:             %{$counts{$key}} = (
 8777:                                'found'   => 0,
 8778:                                'total'   => 0,
 8779:                               );
 8780:             foreach my $line (@lines) {
 8781:                 next if ($line =~ /^#/);
 8782:                 next if ($line =~ /^[\s\cz]*$/);
 8783:                 my $id = substr($line,$idstart-1,$idlength);
 8784:                 $id = lc($id);
 8785:                 if (exists($idmap{$id})) {
 8786:                     $counts{$key}{'found'} ++;
 8787:                 }
 8788:                 $counts{$key}{'total'} ++;
 8789:             }
 8790:             if ($counts{$key}{'total'}) {
 8791:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 8792:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 8793:                     $max_match_pct = $percent_match;
 8794:                     $max_match_format = $key;
 8795:                     $found_match_count = $counts{$key}{'found'};
 8796:                     $max_match_count = $counts{$key}{'total'};
 8797:                 }
 8798:             }
 8799:         }
 8800:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 8801:             my $format_descs;
 8802:             my $numwithformat = @{$unique_formats{$max_match_format}};
 8803:             for (my $i=0; $i<$numwithformat; $i++) {
 8804:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 8805:                 if ($i<$numwithformat-2) {
 8806:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 8807:                 } elsif ($i==$numwithformat-2) {
 8808:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 8809:                 } elsif ($i==$numwithformat-1) {
 8810:                     $format_descs .= '"<i>'.$desc.'</i>"';
 8811:                 }
 8812:             }
 8813:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 8814:             $output .= '<br />';
 8815:             if ($found_match_count == $max_match_count) {
 8816:                 # 100% matching entries
 8817:                 $output .= &Apache::lonhtmlcommon::confirm_success(
 8818:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
 8819:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
 8820:                 &mt('Comparison of student IDs in the uploaded file with'.
 8821:                     ' the course roster found matches for [_1] of the [_2] entries'.
 8822:                     ' in the file (for the format defined for [_3]).',
 8823:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
 8824:             } else {
 8825:                 # Not all entries matching? -> Show warning and additional info
 8826:                 $output .=
 8827:                     &Apache::lonhtmlcommon::confirm_success(
 8828:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
 8829:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
 8830:                         &mt('Not all entries could be matched!'),1).'<br />'.
 8831:                     &mt('Comparison of student IDs in the uploaded file with'.
 8832:                         ' the course roster found matches for [_1] of the [_2] entries'.
 8833:                         ' in the file (for the format defined for [_3]).',
 8834:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
 8835:                     '<p class="LC_info">'.
 8836:                     &mt('A low percentage of matches results from one of the following:').
 8837:                     '</p><ul>'.
 8838:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
 8839:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
 8840:                                '<i>'.$cdom.'</i>').'</li>'.
 8841:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 8842:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
 8843:                     '</ul>';
 8844:             }
 8845:         }
 8846:     } else {
 8847:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
 8848:     }
 8849:     return $output;
 8850: }
 8851: 
 8852: sub valid_file {
 8853:     my ($requested_file)=@_;
 8854:     foreach my $filename (sort(&scantron_filenames())) {
 8855: 	if ($requested_file eq $filename) { return 1; }
 8856:     }
 8857:     return 0;
 8858: }
 8859: 
 8860: sub scantron_download_scantron_data {
 8861:     my ($r,$symb)=@_;
 8862:     my $default_form_data=&defaultFormData($symb);
 8863:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8864:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8865:     my $file=$env{'form.scantron_selectfile'};
 8866:     if (! &valid_file($file)) {
 8867: 	$r->print('
 8868: 	<p>
 8869: 	    '.&mt('The requested filename was invalid.').'
 8870:         </p>
 8871: ');
 8872: 	return;
 8873:     }
 8874:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 8875:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 8876:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 8877:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 8878:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 8879:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 8880:     $r->print('
 8881:     <p>
 8882: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet office.',
 8883: 	      '<a href="'.$orig.'">','</a>').'
 8884:     </p>
 8885:     <p>
 8886: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 8887: 	      '<a href="'.$corrected.'">','</a>').'
 8888:     </p>
 8889:     <p>
 8890: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 8891: 	      '<a href="'.$skipped.'">','</a>').'
 8892:     </p>
 8893: ');
 8894:     return '';
 8895: }
 8896: 
 8897: sub checkscantron_results {
 8898:     my ($r,$symb) = @_;
 8899:     if (!$symb) {return '';}
 8900:     my $cid = $env{'request.course.id'};
 8901:     my %lettdig = &letter_to_digits();
 8902:     my $numletts = scalar(keys(%lettdig));
 8903:     my $cnum = $env{'course.'.$cid.'.num'};
 8904:     my $cdom = $env{'course.'.$cid.'.domain'};
 8905:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8906:     my %record;
 8907:     my %scantron_config =
 8908:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 8909:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8910:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 8911:     my $classlist=&Apache::loncoursedata::get_classlist();
 8912:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 8913:     my $navmap=Apache::lonnavmaps::navmap->new();
 8914:     unless (ref($navmap)) {
 8915:         $r->print(&navmap_errormsg());
 8916:         return '';
 8917:     }
 8918:     my $map=$navmap->getResourceByUrl($sequence);
 8919:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8920:         %grader_randomlists_by_symb,%orderedforcode);
 8921:     if (ref($map)) { 
 8922:         $randomorder=$map->randomorder();
 8923:         $randompick=$map->randompick();
 8924:     }
 8925:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8926:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8927:     if ($nav_error) {
 8928:         $r->print(&navmap_errormsg());
 8929:         return '';
 8930:     }
 8931:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8932:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 8933:     my ($uname,$udom);
 8934:     my (%scandata,%lastname,%bylast);
 8935:     $r->print('
 8936: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 8937: 
 8938:     my @delayqueue;
 8939:     my %completedstudents;
 8940: 
 8941:     my $count=&get_todo_count($scanlines,$scan_data);
 8942:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 8943:     my ($username,$domain,$started);
 8944:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 8945:     if ($nav_error) {
 8946:         $r->print(&navmap_errormsg());
 8947:         return '';
 8948:     }
 8949: 
 8950:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
 8951:     my $start=&Time::HiRes::time();
 8952:     my $i=-1;
 8953: 
 8954:     while ($i<$scanlines->{'count'}) {
 8955:         ($username,$domain,$uname)=('','','');
 8956:         $i++;
 8957:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 8958:         if ($line=~/^[\s\cz]*$/) { next; }
 8959:         if ($started) {
 8960:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 8961:         }
 8962:         $started=1;
 8963:         my $scan_record=
 8964:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 8965:                                                      $scan_data);
 8966:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
 8967:                                               \%idmap,$i)) {
 8968:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8969:                                 'Unable to find a student that matches',1);
 8970:             next;
 8971:         }
 8972:         if (exists $completedstudents{$uname}) {
 8973:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8974:                                 'Student '.$uname.' has multiple sheets',2);
 8975:             next;
 8976:         }
 8977:         my $pid = $scan_record->{'scantron.ID'};
 8978:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 8979:         push(@{$bylast{$lastname{$pid}}},$pid);
 8980:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 8981:         my $user = $uname.':'.$usec;
 8982:         ($username,$domain)=split(/:/,$uname);
 8983: 
 8984:         my $scancode;
 8985:         if ((exists($scan_record->{'scantron.CODE'})) &&
 8986:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 8987:             $scancode = $scan_record->{'scantron.CODE'};
 8988:         } else {
 8989:             $scancode = '';
 8990:         }
 8991: 
 8992:         my @mapresources = @resources;
 8993:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8994:         my %respnumlookup=();
 8995:         my %startline=();
 8996:         if ($randomorder || $randompick) {
 8997:             @mapresources =
 8998:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 8999:                              \%orderedforcode);
 9000:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
 9001:                                              $scan_record,\@master_seq,\%symb_to_resource,
 9002:                                              \%grader_partids_by_symb,\%orderedforcode,
 9003:                                              \%respnumlookup,\%startline);
 9004:             if ($randompick && $total) {
 9005:                 $lastpos = $total*$scantron_config{'Qlength'};
 9006:             }
 9007:         }
 9008:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 9009:         chomp($scandata{$pid});
 9010:         $scandata{$pid} =~ s/\r$//;
 9011: 
 9012:         my $counter = -1;
 9013:         foreach my $resource (@mapresources) {
 9014:             my $parts;
 9015:             my $ressymb = $resource->symb();
 9016:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 9017:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 9018:                 (my $analysis,$parts) =
 9019:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 9020:                                               $username,$domain,undef,
 9021:                                               $bubbles_per_row);
 9022:             } else {
 9023:                 $parts = $grader_partids_by_symb{$ressymb};
 9024:             }
 9025:             ($counter,my $recording) =
 9026:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 9027:                                          $scandata{$pid},$parts,
 9028:                                          \%scantron_config,\%lettdig,$numletts,
 9029:                                          $randomorder,$randompick,
 9030:                                          \%respnumlookup,\%startline);
 9031:             $record{$pid} .= $recording;
 9032:         }
 9033:     }
 9034:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 9035:     $r->print('<br />');
 9036:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 9037:     $passed = 0;
 9038:     $failed = 0;
 9039:     $numstudents = 0;
 9040:     foreach my $last (sort(keys(%bylast))) {
 9041:         if (ref($bylast{$last}) eq 'ARRAY') {
 9042:             foreach my $pid (sort(@{$bylast{$last}})) {
 9043:                 my $showscandata = $scandata{$pid};
 9044:                 my $showrecord = $record{$pid};
 9045:                 $showscandata =~ s/\s/&nbsp;/g;
 9046:                 $showrecord =~ s/\s/&nbsp;/g;
 9047:                 if ($scandata{$pid} eq $record{$pid}) {
 9048:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 9049:                     $okstudents .= '<tr class="'.$css_class.'">'.
 9050: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 9051: '</tr>'."\n".
 9052: '<tr class="'.$css_class.'">'."\n".
 9053: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
 9054:                     $passed ++;
 9055:                 } else {
 9056:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 9057:                     $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".
 9058: '</tr>'."\n".
 9059: '<tr class="'.$css_class.'">'."\n".
 9060: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 9061: '</tr>'."\n";
 9062:                     $failed ++;
 9063:                 }
 9064:                 $numstudents ++;
 9065:             }
 9066:         }
 9067:     }
 9068:     $r->print(
 9069:         '<p>'
 9070:        .&mt('Comparison of bubblesheet data (including corrections) with corresponding submission records (most recent submission) for [_1][quant,_2,student][_3] ([quant,_4,bubblesheet line] per student).',
 9071:             '<b>',
 9072:             $numstudents,
 9073:             '</b>',
 9074:             $env{'form.scantron_maxbubble'})
 9075:        .'</p>'
 9076:     );
 9077:     $r->print('<p>'
 9078:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
 9079:              .'<br />'
 9080:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
 9081:              .'</p>'
 9082:     );
 9083:     if ($passed) {
 9084:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 9085:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9086:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9087:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9088:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9089:                  $okstudents."\n".
 9090:                  &Apache::loncommon::end_data_table().'<br />');
 9091:     }
 9092:     if ($failed) {
 9093:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 9094:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9095:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9096:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9097:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9098:                  $badstudents."\n".
 9099:                  &Apache::loncommon::end_data_table()).'<br />'.
 9100:                  &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.');  
 9101:     }
 9102:     $r->print('</form><br />');
 9103:     return;
 9104: }
 9105: 
 9106: sub verify_scantron_grading {
 9107:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 9108:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
 9109:         $respnumlookup,$startline) = @_;
 9110:     my ($record,%expected,%startpos);
 9111:     return ($counter,$record) if (!ref($resource));
 9112:     return ($counter,$record) if (!$resource->is_problem());
 9113:     my $symb = $resource->symb();
 9114:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 9115:     foreach my $part_id (@{$partids}) {
 9116:         $counter ++;
 9117:         $expected{$part_id} = 0;
 9118:         my $respnum = $counter;
 9119:         if ($randomorder || $randompick) {
 9120:             $respnum = $respnumlookup->{$counter};
 9121:             $startpos{$part_id} = $startline->{$counter} + 1;
 9122:         } else {
 9123:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 9124:         }
 9125:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
 9126:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
 9127:             foreach my $item (@sub_lines) {
 9128:                 $expected{$part_id} += $item;
 9129:             }
 9130:         } else {
 9131:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
 9132:         }
 9133:     }
 9134:     if ($symb) {
 9135:         my %recorded;
 9136:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 9137:         if ($returnhash{'version'}) {
 9138:             my %lasthash=();
 9139:             my $version;
 9140:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 9141:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 9142:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 9143:                 }
 9144:             }
 9145:             foreach my $key (keys(%lasthash)) {
 9146:                 if ($key =~ /\.scantron$/) {
 9147:                     my $value = &unescape($lasthash{$key});
 9148:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 9149:                     if ($value eq '') {
 9150:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 9151:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 9152:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9153:                             }
 9154:                         }
 9155:                     } else {
 9156:                         my @tocheck;
 9157:                         my @items = split(//,$value);
 9158:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 9159:                             ($scantron_config->{'Qon'} eq 'number')) {
 9160:                             if (@items < $expected{$part_id}) {
 9161:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 9162:                                 my @singles = split(//,$fragment);
 9163:                                 foreach my $pos (@singles) {
 9164:                                     if ($pos eq ' ') {
 9165:                                         push(@tocheck,$pos);
 9166:                                     } else {
 9167:                                         my $next = shift(@items);
 9168:                                         push(@tocheck,$next);
 9169:                                     }
 9170:                                 }
 9171:                             } else {
 9172:                                 @tocheck = @items;
 9173:                             }
 9174:                             foreach my $letter (@tocheck) {
 9175:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 9176:                                     if ($letter !~ /^[A-J]$/) {
 9177:                                         $letter = $scantron_config->{'Qoff'};
 9178:                                     }
 9179:                                     $recorded{$part_id} .= $letter;
 9180:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 9181:                                     my $digit;
 9182:                                     if ($letter !~ /^[A-J]$/) {
 9183:                                         $digit = $scantron_config->{'Qoff'};
 9184:                                     } else {
 9185:                                         $digit = $lettdig->{$letter};
 9186:                                     }
 9187:                                     $recorded{$part_id} .= $digit;
 9188:                                 }
 9189:                             }
 9190:                         } else {
 9191:                             @tocheck = @items;
 9192:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 9193:                                 my $curr_sub = shift(@tocheck);
 9194:                                 my $digit;
 9195:                                 if ($curr_sub =~ /^[A-J]$/) {
 9196:                                     $digit = $lettdig->{$curr_sub}-1;
 9197:                                 }
 9198:                                 if ($curr_sub eq 'J') {
 9199:                                     $digit += scalar($numletts);
 9200:                                 }
 9201:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9202:                                     if ($j == $digit) {
 9203:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 9204:                                     } else {
 9205:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9206:                                     }
 9207:                                 }
 9208:                             }
 9209:                         }
 9210:                     }
 9211:                 }
 9212:             }
 9213:         }
 9214:         foreach my $part_id (@{$partids}) {
 9215:             if ($recorded{$part_id} eq '') {
 9216:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 9217:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9218:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9219:                     }
 9220:                 }
 9221:             }
 9222:             $record .= $recorded{$part_id};
 9223:         }
 9224:     }
 9225:     return ($counter,$record);
 9226: }
 9227: 
 9228: sub letter_to_digits {
 9229:     my %lettdig = (
 9230:                     A => 1,
 9231:                     B => 2,
 9232:                     C => 3,
 9233:                     D => 4,
 9234:                     E => 5,
 9235:                     F => 6,
 9236:                     G => 7,
 9237:                     H => 8,
 9238:                     I => 9,
 9239:                     J => 0,
 9240:                   );
 9241:     return %lettdig;
 9242: }
 9243: 
 9244: 
 9245: #-------- end of section for handling grading scantron forms -------
 9246: #
 9247: #-------------------------------------------------------------------
 9248: 
 9249: #-------------------------- Menu interface -------------------------
 9250: #
 9251: #--- Href with symb and command ---
 9252: 
 9253: sub href_symb_cmd {
 9254:     my ($symb,$cmd)=@_;
 9255:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
 9256: }
 9257: 
 9258: sub grading_menu {
 9259:     my ($request,$symb) = @_;
 9260:     if (!$symb) {return '';}
 9261: 
 9262:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 9263:                   'command'=>'individual');
 9264:     
 9265:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9266: 
 9267:     $fields{'command'}='ungraded';
 9268:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9269: 
 9270:     $fields{'command'}='table';
 9271:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9272: 
 9273:     $fields{'command'}='all_for_one';
 9274:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9275: 
 9276:     $fields{'command'}='downloadfilesselect';
 9277:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9278: 
 9279:     $fields{'command'} = 'csvform';
 9280:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9281:     
 9282:     $fields{'command'} = 'processclicker';
 9283:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9284:     
 9285:     $fields{'command'} = 'scantron_selectphase';
 9286:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9287: 
 9288:     $fields{'command'} = 'initialverifyreceipt';
 9289:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9290:     
 9291:     my @menu = ({	categorytitle=>'Hand Grading',
 9292:             items =>[
 9293:                         {	linktext => 'Select individual students to grade',
 9294:                     		url => $url1a,
 9295:                     		permission => 'F',
 9296:                     		icon => 'grade_students.png',
 9297:                     		linktitle => 'Grade current resource for a selection of students.'
 9298:                         }, 
 9299:                         {       linktext => 'Grade ungraded submissions.',
 9300:                                 url => $url1b,
 9301:                                 permission => 'F',
 9302:                                 icon => 'ungrade_sub.png',
 9303:                                 linktitle => 'Grade all submissions that have not been graded yet.'
 9304:                         },
 9305: 
 9306:                         {       linktext => 'Grading table',
 9307:                                 url => $url1c,
 9308:                                 permission => 'F',
 9309:                                 icon => 'grading_table.png',
 9310:                                 linktitle => 'Grade current resource for all students.'
 9311:                         },
 9312:                         {       linktext => 'Grade page/folder for one student',
 9313:                                 url => $url1d,
 9314:                                 permission => 'F',
 9315:                                 icon => 'grade_PageFolder.png',
 9316:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
 9317:                         },
 9318:                         {       linktext => 'Download submissions',
 9319:                                 url => $url1e,
 9320:                                 permission => 'F',
 9321:                                 icon => 'download_sub.png',
 9322:                                 linktitle => 'Download all students submissions.'
 9323:                         }]},
 9324:                          { categorytitle=>'Automated Grading',
 9325:                items =>[
 9326: 
 9327:                 	    {	linktext => 'Upload Scores',
 9328:                     		url => $url2,
 9329:                     		permission => 'F',
 9330:                     		icon => 'uploadscores.png',
 9331:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 9332:                 	    },
 9333:                 	    {	linktext => 'Process Clicker',
 9334:                     		url => $url3,
 9335:                     		permission => 'F',
 9336:                     		icon => 'addClickerInfoFile.png',
 9337:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 9338:                 	    },
 9339:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
 9340:                     		url => $url4,
 9341:                     		permission => 'F',
 9342:                     		icon => 'bubblesheet.png',
 9343:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
 9344:                 	    },
 9345:                             {   linktext => 'Verify Receipt Number',
 9346:                                 url => $url5,
 9347:                                 permission => 'F',
 9348:                                 icon => 'receipt_number.png',
 9349:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
 9350:                             }
 9351: 
 9352:                     ]
 9353:             });
 9354: 
 9355:     # Create the menu
 9356:     my $Str;
 9357:     $Str .= '<form method="post" action="" name="gradingMenu">';
 9358:     $Str .= '<input type="hidden" name="command" value="" />'.
 9359:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9360: 
 9361:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
 9362:     return $Str;    
 9363: }
 9364: 
 9365: 
 9366: sub ungraded {
 9367:     my ($request)=@_;
 9368:     &submit_options($request);
 9369: }
 9370: 
 9371: sub submit_options_sequence {
 9372:     my ($request,$symb) = @_;
 9373:     if (!$symb) {return '';}
 9374:     &commonJSfunctions($request);
 9375:     my $result;
 9376: 
 9377:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9378:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9379:     $result.=&selectfield(0).
 9380:             '<input type="hidden" name="command" value="pickStudentPage" />
 9381:             <div>
 9382:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 9383:             </div>
 9384:         </div>
 9385:   </form>';
 9386:     return $result;
 9387: }
 9388: 
 9389: sub submit_options_table {
 9390:     my ($request,$symb) = @_;
 9391:     if (!$symb) {return '';}
 9392:     &commonJSfunctions($request);
 9393:     my $result;
 9394: 
 9395:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9396:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9397: 
 9398:     $result.=&selectfield(0).
 9399:             '<input type="hidden" name="command" value="viewgrades" />
 9400:             <div>
 9401:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 9402:             </div>
 9403:         </div>
 9404:   </form>';
 9405:     return $result;
 9406: }
 9407: 
 9408: sub submit_options_download {
 9409:     my ($request,$symb) = @_;
 9410:     if (!$symb) {return '';}
 9411: 
 9412:     &commonJSfunctions($request);
 9413: 
 9414:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9415:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9416:     $result.='
 9417: <h2>
 9418:   '.&mt('Select Students for Which to Download Submissions').'
 9419: </h2>'.&selectfield(1).'
 9420:                 <input type="hidden" name="command" value="downloadfileslink" /> 
 9421:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 9422:             </div>
 9423:           </div>
 9424: 
 9425: 
 9426:   </form>';
 9427:     return $result;
 9428: }
 9429: 
 9430: #--- Displays the submissions first page -------
 9431: sub submit_options {
 9432:     my ($request,$symb) = @_;
 9433:     if (!$symb) {return '';}
 9434: 
 9435:     &commonJSfunctions($request);
 9436:     my $result;
 9437: 
 9438:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9439: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9440:     $result.=&selectfield(1).'
 9441:                 <input type="hidden" name="command" value="submission" /> 
 9442: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
 9443:             </div>
 9444:           </div>
 9445: 
 9446: 
 9447:   </form>';
 9448:     return $result;
 9449: }
 9450: 
 9451: sub selectfield {
 9452:    my ($full)=@_;
 9453:    my %options = 
 9454:           (&Apache::lonlocal::texthash(
 9455:              'yes'       => 'with submissions',
 9456:              'queued'    => 'in grading queue',
 9457:              'graded'    => 'with ungraded submissions',
 9458:              'incorrect' => 'with incorrect submissions',
 9459:              'all'       => 'with any status'),
 9460:              'select_form_order' => ['yes','queued','graded','incorrect','all']);
 9461:    my $result='<div class="LC_columnSection">
 9462:   
 9463:     <fieldset>
 9464:       <legend>
 9465:        '.&mt('Sections').'
 9466:       </legend>
 9467:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
 9468:     </fieldset>
 9469:   
 9470:     <fieldset>
 9471:       <legend>
 9472:         '.&mt('Groups').'
 9473:       </legend>
 9474:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 9475:     </fieldset>
 9476:   
 9477:     <fieldset>
 9478:       <legend>
 9479:         '.&mt('Access Status').'
 9480:       </legend>
 9481:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
 9482:     </fieldset>';
 9483:     if ($full) {
 9484:        $result.='
 9485:     <fieldset>
 9486:       <legend>
 9487:         '.&mt('Submission Status').'
 9488:       </legend>'.
 9489:        &Apache::loncommon::select_form('all','submitonly',\%options).
 9490:    '</fieldset>';
 9491:     }
 9492:     $result.='</div><br />';
 9493:     return $result;
 9494: }
 9495: 
 9496: sub reset_perm {
 9497:     undef(%perm);
 9498: }
 9499: 
 9500: sub init_perm {
 9501:     &reset_perm();
 9502:     foreach my $test_perm ('vgr','mgr','opa') {
 9503: 
 9504: 	my $scope = $env{'request.course.id'};
 9505: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 9506: 
 9507: 	    $scope .= '/'.$env{'request.course.sec'};
 9508: 	    if ( $perm{$test_perm}=
 9509: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 9510: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 9511: 	    } else {
 9512: 		delete($perm{$test_perm});
 9513: 	    }
 9514: 	}
 9515:     }
 9516: }
 9517: 
 9518: sub init_old_essays {
 9519:     my ($symb,$apath,$adom,$aname) = @_;
 9520:     if ($symb ne '') {
 9521:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 9522:         if (keys(%essays) > 0) {
 9523:             $old_essays{$symb} = \%essays;
 9524:         }
 9525:     }
 9526:     return;
 9527: }
 9528: 
 9529: sub reset_old_essays {
 9530:     undef(%old_essays);
 9531: }
 9532: 
 9533: sub gather_clicker_ids {
 9534:     my %clicker_ids;
 9535: 
 9536:     my $classlist = &Apache::loncoursedata::get_classlist();
 9537: 
 9538:     # Set up a couple variables.
 9539:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 9540:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 9541:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 9542: 
 9543:     foreach my $student (keys(%$classlist)) {
 9544:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 9545:         my $username = $classlist->{$student}->[$username_idx];
 9546:         my $domain   = $classlist->{$student}->[$domain_idx];
 9547:         my $clickers =
 9548: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 9549:         foreach my $id (split(/\,/,$clickers)) {
 9550:             $id=~s/^[\#0]+//;
 9551:             $id=~s/[\-\:]//g;
 9552:             if (exists($clicker_ids{$id})) {
 9553: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 9554:             } else {
 9555: 		$clicker_ids{$id}=$username.':'.$domain;
 9556:             }
 9557:         }
 9558:     }
 9559:     return %clicker_ids;
 9560: }
 9561: 
 9562: sub gather_adv_clicker_ids {
 9563:     my %clicker_ids;
 9564:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 9565:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9566:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 9567:     foreach my $element (sort(keys(%coursepersonnel))) {
 9568:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 9569:             my ($puname,$pudom)=split(/\:/,$person);
 9570:             my $clickers =
 9571: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 9572:             foreach my $id (split(/\,/,$clickers)) {
 9573: 		$id=~s/^[\#0]+//;
 9574:                 $id=~s/[\-\:]//g;
 9575: 		if (exists($clicker_ids{$id})) {
 9576: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 9577: 		} else {
 9578: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 9579: 		}
 9580:             }
 9581:         }
 9582:     }
 9583:     return %clicker_ids;
 9584: }
 9585: 
 9586: sub clicker_grading_parameters {
 9587:     return ('gradingmechanism' => 'scalar',
 9588:             'upfiletype' => 'scalar',
 9589:             'specificid' => 'scalar',
 9590:             'pcorrect' => 'scalar',
 9591:             'pincorrect' => 'scalar');
 9592: }
 9593: 
 9594: sub process_clicker {
 9595:     my ($r,$symb)=@_;
 9596:     if (!$symb) {return '';}
 9597:     my $result=&checkforfile_js();
 9598:     $result.=&Apache::loncommon::start_data_table().
 9599:              &Apache::loncommon::start_data_table_header_row().
 9600:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
 9601:              &Apache::loncommon::end_data_table_header_row().
 9602:              &Apache::loncommon::start_data_table_row()."<td>\n";
 9603: # Attempt to restore parameters from last session, set defaults if not present
 9604:     my %Saveable_Parameters=&clicker_grading_parameters();
 9605:     &Apache::loncommon::restore_course_settings('grades_clicker',
 9606:                                                  \%Saveable_Parameters);
 9607:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 9608:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 9609:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 9610:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 9611: 
 9612:     my %checked;
 9613:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 9614:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 9615:           $checked{$gradingmechanism}=' checked="checked"';
 9616:        }
 9617:     }
 9618: 
 9619:     my $upload=&mt("Evaluate File");
 9620:     my $type=&mt("Type");
 9621:     my $attendance=&mt("Award points just for participation");
 9622:     my $personnel=&mt("Correctness determined from response by course personnel");
 9623:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 9624:     my $given=&mt("Correctness determined from given list of answers").' '.
 9625:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 9626:     my $pcorrect=&mt("Percentage points for correct solution");
 9627:     my $pincorrect=&mt("Percentage points for incorrect solution");
 9628:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 9629: 						   {'iclicker' => 'i>clicker',
 9630:                                                     'interwrite' => 'interwrite PRS',
 9631:                                                     'turning' => 'Turning Technologies'});
 9632:     $symb = &Apache::lonenc::check_encrypt($symb);
 9633:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
 9634: function sanitycheck() {
 9635: // Accept only integer percentages
 9636:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 9637:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 9638: // Find out grading choice
 9639:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 9640:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 9641:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 9642:       }
 9643:    }
 9644: // By default, new choice equals user selection
 9645:    newgradingchoice=gradingchoice;
 9646: // Not good to give more points for false answers than correct ones
 9647:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 9648:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 9649:    }
 9650: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 9651:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 9652:       document.forms.gradesupload.pcorrect.value=100;
 9653:       document.forms.gradesupload.pincorrect.value=100;
 9654:    }
 9655: // If the values are different, cannot be attendance only
 9656:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 9657:        (gradingchoice=='attendance')) {
 9658:        newgradingchoice='personnel';
 9659:    }
 9660: // Change grading choice to new one
 9661:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 9662:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 9663:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 9664:       } else {
 9665:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 9666:       }
 9667:    }
 9668: // Remember the old state
 9669:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 9670: }
 9671: ENDUPFORM
 9672:     $result.= <<ENDUPFORM;
 9673: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 9674: <input type="hidden" name="symb" value="$symb" />
 9675: <input type="hidden" name="command" value="processclickerfile" />
 9676: <input type="file" name="upfile" size="50" />
 9677: <br /><label>$type: $selectform</label>
 9678: ENDUPFORM
 9679:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
 9680:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
 9681:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
 9682: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
 9683: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
 9684: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 9685: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
 9686: <br />&nbsp;&nbsp;&nbsp;
 9687: <input type="text" name="givenanswer" size="50" />
 9688: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 9689: ENDGRADINGFORM
 9690:          $result.='</td>'.&Apache::loncommon::end_data_table_row().
 9691:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
 9692:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
 9693: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
 9694: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 9695: </form>'
 9696: ENDPERCFORM
 9697:     $result.='</td>'.
 9698:              &Apache::loncommon::end_data_table_row().
 9699:              &Apache::loncommon::end_data_table();
 9700:     return $result;
 9701: }
 9702: 
 9703: sub process_clicker_file {
 9704:     my ($r,$symb)=@_;
 9705:     if (!$symb) {return '';}
 9706: 
 9707:     my %Saveable_Parameters=&clicker_grading_parameters();
 9708:     &Apache::loncommon::store_course_settings('grades_clicker',
 9709:                                               \%Saveable_Parameters);
 9710:     my $result='';
 9711:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 9712: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 9713: 	return $result;
 9714:     }
 9715:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 9716:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 9717:         return $result;
 9718:     }
 9719:     my $foundgiven=0;
 9720:     if ($env{'form.gradingmechanism'} eq 'given') {
 9721:         $env{'form.givenanswer'}=~s/^\s*//gs;
 9722:         $env{'form.givenanswer'}=~s/\s*$//gs;
 9723:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
 9724:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 9725:         my @answers=split(/\,/,$env{'form.givenanswer'});
 9726:         $foundgiven=$#answers+1;
 9727:     }
 9728:     my %clicker_ids=&gather_clicker_ids();
 9729:     my %correct_ids;
 9730:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 9731: 	%correct_ids=&gather_adv_clicker_ids();
 9732:     }
 9733:     if ($env{'form.gradingmechanism'} eq 'specific') {
 9734: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 9735: 	   $correct_id=~tr/a-z/A-Z/;
 9736: 	   $correct_id=~s/\s//gs;
 9737: 	   $correct_id=~s/^[\#0]+//;
 9738:            $correct_id=~s/[\-\:]//g;
 9739:            if ($correct_id) {
 9740: 	      $correct_ids{$correct_id}='specified';
 9741:            }
 9742:         }
 9743:     }
 9744:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 9745: 	$result.=&mt('Score based on attendance only');
 9746:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
 9747:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
 9748:     } else {
 9749: 	my $number=0;
 9750: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 9751: 	foreach my $id (sort(keys(%correct_ids))) {
 9752: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 9753: 	    if ($correct_ids{$id} eq 'specified') {
 9754: 		$result.=&mt('specified');
 9755: 	    } else {
 9756: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 9757: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 9758: 	    }
 9759: 	    $number++;
 9760: 	}
 9761:         $result.="</p>\n";
 9762:         if ($number==0) {
 9763:             $result .=
 9764:                  &Apache::lonhtmlcommon::confirm_success(
 9765:                      &mt('No IDs found to determine correct answer'),1);
 9766:             return $result;
 9767:         }
 9768:     }
 9769:     if (length($env{'form.upfile'}) < 2) {
 9770:         $result .=
 9771:             &Apache::lonhtmlcommon::confirm_success(
 9772:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
 9773:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
 9774:         return $result;
 9775:     }
 9776: 
 9777: # Were able to get all the info needed, now analyze the file
 9778: 
 9779:     $result.=&Apache::loncommon::studentbrowser_javascript();
 9780:     $symb = &Apache::lonenc::check_encrypt($symb);
 9781:     $result.=&Apache::loncommon::start_data_table().
 9782:              &Apache::loncommon::start_data_table_header_row().
 9783:              '<th>'.&mt('Evaluate clicker file').'</th>'.
 9784:              &Apache::loncommon::end_data_table_header_row().
 9785:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
 9786: <td>
 9787: <form method="post" action="/adm/grades" name="clickeranalysis">
 9788: <input type="hidden" name="symb" value="$symb" />
 9789: <input type="hidden" name="command" value="assignclickergrades" />
 9790: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 9791: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 9792: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 9793: ENDHEADER
 9794:     if ($env{'form.gradingmechanism'} eq 'given') {
 9795:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
 9796:     } 
 9797:     my %responses;
 9798:     my @questiontitles;
 9799:     my $errormsg='';
 9800:     my $number=0;
 9801:     if ($env{'form.upfiletype'} eq 'iclicker') {
 9802: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 9803:     }
 9804:     if ($env{'form.upfiletype'} eq 'interwrite') {
 9805:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 9806:     }
 9807:     if ($env{'form.upfiletype'} eq 'turning') {
 9808:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
 9809:     }
 9810:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 9811:              '<input type="hidden" name="number" value="'.$number.'" />'.
 9812:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 9813:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 9814:              '<br />';
 9815:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
 9816:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
 9817:        return $result;
 9818:     } 
 9819: # Remember Question Titles
 9820: # FIXME: Possibly need delimiter other than ":"
 9821:     for (my $i=0;$i<$number;$i++) {
 9822:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 9823:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 9824:     }
 9825:     my $correct_count=0;
 9826:     my $student_count=0;
 9827:     my $unknown_count=0;
 9828: # Match answers with usernames
 9829: # FIXME: Possibly need delimiter other than ":"
 9830:     foreach my $id (keys(%responses)) {
 9831:        if ($correct_ids{$id}) {
 9832:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 9833:           $correct_count++;
 9834:        } elsif ($clicker_ids{$id}) {
 9835:           if ($clicker_ids{$id}=~/\,/) {
 9836: # More than one user with the same clicker!
 9837:              $result.="</td>".&Apache::loncommon::end_data_table_row().
 9838:                            &Apache::loncommon::start_data_table_row()."<td>".
 9839:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 9840:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9841:                            "<select name='multi".$id."'>";
 9842:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 9843:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 9844:              }
 9845:              $result.='</select>';
 9846:              $unknown_count++;
 9847:           } else {
 9848: # Good: found one and only one user with the right clicker
 9849:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 9850:              $student_count++;
 9851:           }
 9852:        } else {
 9853:           $result.="</td>".&Apache::loncommon::end_data_table_row().
 9854:                            &Apache::loncommon::start_data_table_row()."<td>".
 9855:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 9856:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9857:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 9858:                    "\n".&mt("Domain").": ".
 9859:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 9860:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
 9861:           $unknown_count++;
 9862:        }
 9863:     }
 9864:     $result.='<hr />'.
 9865:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 9866:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
 9867:        if ($correct_count==0) {
 9868:           $errormsg.="Found no correct answers for grading!";
 9869:        } elsif ($correct_count>1) {
 9870:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 9871:        }
 9872:     }
 9873:     if ($number<1) {
 9874:        $errormsg.="Found no questions.";
 9875:     }
 9876:     if ($errormsg) {
 9877:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 9878:     } else {
 9879:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 9880:     }
 9881:     $result.='</form></td>'.
 9882:              &Apache::loncommon::end_data_table_row().
 9883:              &Apache::loncommon::end_data_table();
 9884:     return $result;
 9885: }
 9886: 
 9887: sub iclicker_eval {
 9888:     my ($questiontitles,$responses)=@_;
 9889:     my $number=0;
 9890:     my $errormsg='';
 9891:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9892:         my %components=&Apache::loncommon::record_sep($line);
 9893:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9894: 	if ($entries[0] eq 'Question') {
 9895: 	    for (my $i=3;$i<$#entries;$i+=6) {
 9896: 		$$questiontitles[$number]=$entries[$i];
 9897: 		$number++;
 9898: 	    }
 9899: 	}
 9900: 	if ($entries[0]=~/^\#/) {
 9901: 	    my $id=$entries[0];
 9902: 	    my @idresponses;
 9903: 	    $id=~s/^[\#0]+//;
 9904: 	    for (my $i=0;$i<$number;$i++) {
 9905: 		my $idx=3+$i*6;
 9906:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
 9907: 		push(@idresponses,$entries[$idx]);
 9908: 	    }
 9909: 	    $$responses{$id}=join(',',@idresponses);
 9910: 	}
 9911:     }
 9912:     return ($errormsg,$number);
 9913: }
 9914: 
 9915: sub interwrite_eval {
 9916:     my ($questiontitles,$responses)=@_;
 9917:     my $number=0;
 9918:     my $errormsg='';
 9919:     my $skipline=1;
 9920:     my $questionnumber=0;
 9921:     my %idresponses=();
 9922:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9923:         my %components=&Apache::loncommon::record_sep($line);
 9924:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9925:         if ($entries[1] eq 'Time') { $skipline=0; next; }
 9926:         if ($entries[1] eq 'Response') { $skipline=1; }
 9927:         next if $skipline;
 9928:         if ($entries[0]!=$questionnumber) {
 9929:            $questionnumber=$entries[0];
 9930:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
 9931:            $number++;
 9932:         }
 9933:         my $id=$entries[4];
 9934:         $id=~s/^[\#0]+//;
 9935:         $id=~s/^v\d*\://i;
 9936:         $id=~s/[\-\:]//g;
 9937:         $idresponses{$id}[$number]=$entries[6];
 9938:     }
 9939:     foreach my $id (keys(%idresponses)) {
 9940:        $$responses{$id}=join(',',@{$idresponses{$id}});
 9941:        $$responses{$id}=~s/^\s*\,//;
 9942:     }
 9943:     return ($errormsg,$number);
 9944: }
 9945: 
 9946: sub turning_eval {
 9947:     my ($questiontitles,$responses)=@_;
 9948:     my $number=0;
 9949:     my $errormsg='';
 9950:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9951:         my %components=&Apache::loncommon::record_sep($line);
 9952:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9953:         if ($#entries>$number) { $number=$#entries; }
 9954:         my $id=$entries[0];
 9955:         my @idresponses;
 9956:         $id=~s/^[\#0]+//;
 9957:         unless ($id) { next; }
 9958:         for (my $idx=1;$idx<=$#entries;$idx++) {
 9959:             $entries[$idx]=~s/\,/\;/g;
 9960:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
 9961:             push(@idresponses,$entries[$idx]);
 9962:         }
 9963:         $$responses{$id}=join(',',@idresponses);
 9964:     }
 9965:     for (my $i=1; $i<=$number; $i++) {
 9966:         $$questiontitles[$i]=&mt('Question [_1]',$i);
 9967:     }
 9968:     return ($errormsg,$number);
 9969: }
 9970: 
 9971: 
 9972: sub assign_clicker_grades {
 9973:     my ($r,$symb)=@_;
 9974:     if (!$symb) {return '';}
 9975: # See which part we are saving to
 9976:     my $res_error;
 9977:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 9978:     if ($res_error) {
 9979:         return &navmap_errormsg();
 9980:     }
 9981: # FIXME: This should probably look for the first handgradeable part
 9982:     my $part=$$partlist[0];
 9983: # Start screen output
 9984:     my $result=&Apache::loncommon::start_data_table().
 9985:              &Apache::loncommon::start_data_table_header_row().
 9986:              '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
 9987:              &Apache::loncommon::end_data_table_header_row().
 9988:              &Apache::loncommon::start_data_table_row().'<td>';
 9989: # Get correct result
 9990: # FIXME: Possibly need delimiter other than ":"
 9991:     my @correct=();
 9992:     my $gradingmechanism=$env{'form.gradingmechanism'};
 9993:     my $number=$env{'form.number'};
 9994:     if ($gradingmechanism ne 'attendance') {
 9995:        foreach my $key (keys(%env)) {
 9996:           if ($key=~/^form\.correct\:/) {
 9997:              my @input=split(/\,/,$env{$key});
 9998:              for (my $i=0;$i<=$#input;$i++) {
 9999:                  if (($correct[$i]) && ($input[$i]) &&
10000:                      ($correct[$i] ne $input[$i])) {
10001:                     $result.='<br /><span class="LC_warning">'.
10002:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
10003:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
10004:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
10005:                     $correct[$i]=$input[$i];
10006:                  }
10007:              }
10008:           }
10009:        }
10010:        for (my $i=0;$i<$number;$i++) {
10011:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
10012:              $result.='<br /><span class="LC_error">'.
10013:                       &mt('No correct result given for question "[_1]"!',
10014:                           $env{'form.question:'.$i}).'</span>';
10015:           }
10016:        }
10017:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
10018:     }
10019: # Start grading
10020:     my $pcorrect=$env{'form.pcorrect'};
10021:     my $pincorrect=$env{'form.pincorrect'};
10022:     my $storecount=0;
10023:     my %users=();
10024:     foreach my $key (keys(%env)) {
10025:        my $user='';
10026:        if ($key=~/^form\.student\:(.*)$/) {
10027:           $user=$1;
10028:        }
10029:        if ($key=~/^form\.unknown\:(.*)$/) {
10030:           my $id=$1;
10031:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
10032:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
10033:           } elsif ($env{'form.multi'.$id}) {
10034:              $user=$env{'form.multi'.$id};
10035:           }
10036:        }
10037:        if ($user) {
10038:           if ($users{$user}) {
10039:              $result.='<br /><span class="LC_warning">'.
10040:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
10041:                       '</span><br />';
10042:           }
10043:           $users{$user}=1; 
10044:           my @answer=split(/\,/,$env{$key});
10045:           my $sum=0;
10046:           my $realnumber=$number;
10047:           for (my $i=0;$i<$number;$i++) {
10048:              if  ($correct[$i] eq '-') {
10049:                 $realnumber--;
10050:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/))  {
10051:                 if ($gradingmechanism eq 'attendance') {
10052:                    $sum+=$pcorrect;
10053:                 } elsif ($correct[$i] eq '*') {
10054:                    $sum+=$pcorrect;
10055:                 } else {
10056: # We actually grade if correct or not
10057:                    my $increment=$pincorrect;
10058: # Special case: numerical answer "0"
10059:                    if ($correct[$i] eq '0') {
10060:                       if ($answer[$i]=~/^[0\.]+$/) {
10061:                          $increment=$pcorrect;
10062:                       }
10063: # General numerical answer, both evaluate to something non-zero
10064:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
10065:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
10066:                          $increment=$pcorrect;
10067:                       }
10068: # Must be just alphanumeric
10069:                    } elsif ($answer[$i] eq $correct[$i]) {
10070:                       $increment=$pcorrect;
10071:                    }
10072:                    $sum+=$increment;
10073:                 }
10074:              }
10075:           }
10076:           my $ave=$sum/(100*$realnumber);
10077: # Store
10078:           my ($username,$domain)=split(/\:/,$user);
10079:           my %grades=();
10080:           $grades{"resource.$part.solved"}='correct_by_override';
10081:           $grades{"resource.$part.awarded"}=$ave;
10082:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
10083:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
10084:                                                  $env{'request.course.id'},
10085:                                                  $domain,$username);
10086:           if ($returncode ne 'ok') {
10087:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
10088:           } else {
10089:              $storecount++;
10090:           }
10091:        }
10092:     }
10093: # We are done
10094:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
10095:              '</td>'.
10096:              &Apache::loncommon::end_data_table_row().
10097:              &Apache::loncommon::end_data_table();
10098:     return $result;
10099: }
10100: 
10101: sub navmap_errormsg {
10102:     return '<div class="LC_error">'.
10103:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
10104:            &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>').
10105:            '</div>';
10106: }
10107: 
10108: sub startpage {
10109:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js) = @_;
10110:     if ($nomenu) {
10111:         $r->print(&Apache::loncommon::start_page("Student's Version",$js,{'only_body' => '1'}));
10112:     } else {
10113:         unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
10114:         $r->print(&Apache::loncommon::start_page('Grading',$js,
10115:                                                  {'bread_crumbs' => $crumbs}));
10116:         &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
10117:     }
10118:     unless ($nodisplayflag) {
10119:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
10120:     }
10121: }
10122: 
10123: sub select_problem {
10124:     my ($r)=@_;
10125:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
10126:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1));
10127:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
10128:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
10129: }
10130: 
10131: sub handler {
10132:     my $request=$_[0];
10133:     &reset_caches();
10134:     if ($request->header_only) {
10135:         &Apache::loncommon::content_type($request,'text/html');
10136:         $request->send_http_header;
10137:         return OK;
10138:     }
10139:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
10140: 
10141: # see what command we need to execute
10142: 
10143:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
10144:     my $command=$commands[0];
10145: 
10146:     &init_perm();
10147:     if (!$env{'request.course.id'}) {
10148:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
10149:                 ($command =~ /^scantronupload/)) {
10150:             # Not in a course.
10151:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
10152:             return HTTP_NOT_ACCEPTABLE;
10153:         }
10154:     } elsif (!%perm) {
10155:         $request->internal_redirect('/adm/quickgrades');
10156:         return OK;
10157:     }
10158:     &Apache::loncommon::content_type($request,'text/html');
10159:     $request->send_http_header;
10160: 
10161:     if ($#commands > 0) {
10162: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
10163:     }
10164: 
10165: # see what the symb is
10166: 
10167:     my $symb=$env{'form.symb'};
10168:     unless ($symb) {
10169:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
10170:        $symb=&Apache::lonnet::symbread($url);
10171:     }
10172:     &Apache::lonenc::check_decrypt(\$symb);
10173: 
10174:     $ssi_error = 0;
10175:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
10176: #
10177: # Not called from a resource, but inside a course
10178: #    
10179:         &startpage($request,undef,[],1,1);
10180:         &select_problem($request);
10181:     } else {
10182: 	if ($command eq 'submission' && $perm{'vgr'}) {
10183:             my ($stuvcurrent,$stuvdisp,$versionform,$js);
10184:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
10185:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
10186:                     &choose_task_version_form($symb,$env{'form.student'},
10187:                                               $env{'form.userdom'});
10188:             }
10189:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
10190:             if ($versionform) {
10191:                 $request->print($versionform);
10192:             }
10193:             $request->print('<br clear="all" />');
10194: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
10195:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
10196:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
10197:                 &choose_task_version_form($symb,$env{'form.student'},
10198:                                           $env{'form.userdom'},
10199:                                           $env{'form.inhibitmenu'});
10200:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
10201:             if ($versionform) {
10202:                 $request->print($versionform);
10203:             }
10204:             $request->print('<br clear="all" />');
10205:             $request->print(&show_previous_task_version($request,$symb));
10206: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
10207:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10208:                                        {href=>'',text=>'Select student'}],1,1);
10209: 	    &pickStudentPage($request,$symb);
10210: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
10211:             &startpage($request,$symb,
10212:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10213:                                        {href=>'',text=>'Select student'},
10214:                                        {href=>'',text=>'Grade student'}],1,1);
10215: 	    &displayPage($request,$symb);
10216: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
10217:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10218:                                        {href=>'',text=>'Select student'},
10219:                                        {href=>'',text=>'Grade student'},
10220:                                        {href=>'',text=>'Store grades'}],1,1);
10221: 	    &updateGradeByPage($request,$symb);
10222: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
10223:             &startpage($request,$symb,[{href=>'',text=>'...'},
10224:                                        {href=>'',text=>'Modify grades'}]);
10225: 	    &processGroup($request,$symb);
10226: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
10227:             &startpage($request,$symb);
10228: 	    $request->print(&grading_menu($request,$symb));
10229: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
10230:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
10231: 	    $request->print(&submit_options($request,$symb));
10232:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
10233:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
10234:             $request->print(&listStudents($request,$symb,'graded'));
10235:         } elsif ($command eq 'table' && $perm{'vgr'}) {
10236:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
10237:             $request->print(&submit_options_table($request,$symb));
10238:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
10239:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
10240:             $request->print(&submit_options_sequence($request,$symb));
10241: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
10242:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
10243: 	    $request->print(&viewgrades($request,$symb));
10244: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
10245:             &startpage($request,$symb,[{href=>'',text=>'...'},
10246:                                        {href=>'',text=>'Store grades'}]);
10247: 	    $request->print(&processHandGrade($request,$symb));
10248: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
10249:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
10250:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
10251:                                                                              text=>"Modify grades"},
10252:                                        {href=>'', text=>"Store grades"}]);
10253: 	    $request->print(&editgrades($request,$symb));
10254:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
10255:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
10256:             $request->print(&initialverifyreceipt($request,$symb));
10257: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
10258:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
10259:                                        {href=>'',text=>'Verification Result'}]);
10260: 	    $request->print(&verifyreceipt($request,$symb));
10261:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
10262:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
10263:             $request->print(&process_clicker($request,$symb));
10264:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
10265:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
10266:                                        {href=>'', text=>'Process clicker file'}]);
10267:             $request->print(&process_clicker_file($request,$symb));
10268:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
10269:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
10270:                                        {href=>'', text=>'Process clicker file'},
10271:                                        {href=>'', text=>'Store grades'}]);
10272:             $request->print(&assign_clicker_grades($request,$symb));
10273: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
10274:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10275: 	    $request->print(&upcsvScores_form($request,$symb));
10276: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
10277:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10278: 	    $request->print(&csvupload($request,$symb));
10279: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
10280:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10281: 	    $request->print(&csvuploadmap($request,$symb));
10282: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
10283: 	    if ($env{'form.associate'} ne 'Reverse Association') {
10284:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10285: 		$request->print(&csvuploadoptions($request,$symb));
10286: 	    } else {
10287: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
10288: 		    $env{'form.upfile_associate'} = 'reverse';
10289: 		} else {
10290: 		    $env{'form.upfile_associate'} = 'forward';
10291: 		}
10292:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10293: 		$request->print(&csvuploadmap($request,$symb));
10294: 	    }
10295: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
10296:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10297: 	    $request->print(&csvuploadassign($request,$symb));
10298: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
10299:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10300: 	    $request->print(&scantron_selectphase($request,undef,$symb));
10301:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
10302:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10303:  	    $request->print(&scantron_do_warning($request,$symb));
10304: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
10305:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10306: 	    $request->print(&scantron_validate_file($request,$symb));
10307: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
10308:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10309: 	    $request->print(&scantron_process_students($request,$symb));
10310:  	} elsif ($command eq 'scantronupload' && 
10311:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10312: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10313:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10314:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
10315:  	} elsif ($command eq 'scantronupload_save' &&
10316:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10317: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10318:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10319:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
10320:  	} elsif ($command eq 'scantron_download' &&
10321: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
10322:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10323:  	    $request->print(&scantron_download_scantron_data($request,$symb));
10324:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
10325:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10326:             $request->print(&checkscantron_results($request,$symb));
10327:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
10328:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
10329:             $request->print(&submit_options_download($request,$symb));
10330:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
10331:             &startpage($request,$symb,
10332:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
10333:     {href=>'', text=>'Download submissions'}]);
10334:             &submit_download_link($request,$symb);
10335: 	} elsif ($command) {
10336:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
10337: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
10338: 	}
10339:     }
10340:     if ($ssi_error) {
10341: 	&ssi_print_error($request);
10342:     }
10343:     if ($env{'form.inhibitmenu'}) {
10344:         $request->print(&Apache::loncommon::end_page());
10345:     } else {
10346:         &Apache::lonquickgrades::endGradeScreen($request);
10347:     }
10348:     &reset_caches();
10349:     return OK;
10350: }
10351: 
10352: 1;
10353: 
10354: __END__;
10355: 
10356: 
10357: =head1 NAME
10358: 
10359: Apache::grades
10360: 
10361: =head1 SYNOPSIS
10362: 
10363: Handles the viewing of grades.
10364: 
10365: This is part of the LearningOnline Network with CAPA project
10366: described at http://www.lon-capa.org.
10367: 
10368: =head1 OVERVIEW
10369: 
10370: Do an ssi with retries:
10371: While I'd love to factor out this with the version in lonprintout,
10372: 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
10373: I'm not quite ready to invent (e.g. an ssi_with_retry object).
10374: 
10375: At least the logic that drives this has been pulled out into loncommon.
10376: 
10377: 
10378: 
10379: ssi_with_retries - Does the server side include of a resource.
10380:                      if the ssi call returns an error we'll retry it up to
10381:                      the number of times requested by the caller.
10382:                      If we still have a problem, no text is appended to the
10383:                      output and we set some global variables.
10384:                      to indicate to the caller an SSI error occurred.  
10385:                      All of this is supposed to deal with the issues described
10386:                      in LON-CAPA BZ 5631 see:
10387:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
10388:                      by informing the user that this happened.
10389: 
10390: Parameters:
10391:   resource   - The resource to include.  This is passed directly, without
10392:                interpretation to lonnet::ssi.
10393:   form       - The form hash parameters that guide the interpretation of the resource
10394:                
10395:   retries    - Number of retries allowed before giving up completely.
10396: Returns:
10397:   On success, returns the rendered resource identified by the resource parameter.
10398: Side Effects:
10399:   The following global variables can be set:
10400:    ssi_error                - If an unrecoverable error occurred this becomes true.
10401:                               It is up to the caller to initialize this to false
10402:                               if desired.
10403:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
10404:                               of the resource that could not be rendered by the ssi
10405:                               call.
10406:    ssi_error_message   - The error string fetched from the ssi response
10407:                               in the event of an error.
10408: 
10409: 
10410: =head1 HANDLER SUBROUTINE
10411: 
10412: ssi_with_retries()
10413: 
10414: =head1 SUBROUTINES
10415: 
10416: =over
10417: 
10418: =head1 Routines to display previous version of a Task for a specific student
10419: 
10420: Tasks are graded pass/fail. Students who have yet to pass a particular Task
10421: can receive another opportunity. Access to tasks is slot-based. If a slot
10422: requires a proctor to check-in the student, a new version of the Task will
10423: be created when the student is checked in to the new opportunity.
10424: 
10425: If a particular student has tried two or more versions of a particular task,
10426: the submission screen provides a user with vgr privileges (e.g., a Course
10427: Coordinator) the ability to display a previous version worked on by the
10428: student.  By default, the current version is displayed. If a previous version
10429: has been selected for display, submission data are only shown that pertain
10430: to that particular version, and the interface to submit grades is not shown.
10431: 
10432: =over 4
10433: 
10434: =item show_previous_task_version()
10435: 
10436: Displays a specified version of a student's Task, as the student sees it.
10437: 
10438: Inputs: 2
10439:         request - request object
10440:         symb    - unique symb for current instance of resource
10441: 
10442: Output: None.
10443: 
10444: Side Effects: calls &show_problem() to print version of Task, with
10445:               version contained in form item: $env{'form.previousversion'}
10446: 
10447: =item choose_task_version_form()
10448: 
10449: Displays a web form used to select which version of a student's view of a
10450: Task should be displayed.  Either launches a pop-up window, or replaces
10451: content in existing pop-up, or replaces page in main window.
10452: 
10453: Inputs: 4
10454:         symb    - unique symb for current instance of resource
10455:         uname   - username of student
10456:         udom    - domain of student
10457:         nomenu  - 1 if display is in a pop-up window, and hence no menu
10458:                   breadcrumbs etc., are displayed
10459: 
10460: Output: 4
10461:         current   - student's current version
10462:         displayed - student's version being displayed
10463:         result    - scalar containing HTML for web form used to switch to
10464:                     a different version (or a link to close window, if pop-up).
10465:         js        - javascript for processing selection in versions web form
10466: 
10467: Side Effects: None.
10468: 
10469: =item previous_display_javascript()
10470: 
10471: Inputs: 2
10472:         nomenu  - 1 if display is in a pop-up window, and hence no menu
10473:                   breadcrumbs etc., are displayed.
10474:         current - student's current version number.
10475: 
10476: Output: 1
10477:         js      - javascript for processing selection in versions web form.
10478: 
10479: Side Effects: None.
10480: 
10481: =back
10482: 
10483: =head1 Routines to process bubblesheet data.
10484: 
10485: =over 4
10486: 
10487: =item scantron_get_correction() : 
10488: 
10489:    Builds the interface screen to interact with the operator to fix a
10490:    specific error condition in a specific scanline
10491: 
10492:  Arguments:
10493:     $r           - Apache request object
10494:     $i           - number of the current scanline
10495:     $scan_record - hash ref as returned from &scantron_parse_scanline()
10496:     $scan_config - hash ref as returned from &get_scantron_config()
10497:     $line        - full contents of the current scanline
10498:     $error       - error condition, valid values are
10499:                    'incorrectCODE', 'duplicateCODE',
10500:                    'doublebubble', 'missingbubble',
10501:                    'duplicateID', 'incorrectID'
10502:     $arg         - extra information needed
10503:        For errors:
10504:          - duplicateID   - paper number that this studentID was seen before on
10505:          - duplicateCODE - array ref of the paper numbers this CODE was
10506:                            seen on before
10507:          - incorrectCODE - current incorrect CODE 
10508:          - doublebubble  - array ref of the bubble lines that have double
10509:                            bubble errors
10510:          - missingbubble - array ref of the bubble lines that have missing
10511:                            bubble errors
10512: 
10513:    $randomorder - True if exam folder has randomorder set
10514:    $randompick  - True if exam folder has randompick set
10515:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
10516:                      for current line to question number used for same question
10517:                      in "Master Seqence" (as seen by Course Coordinator).
10518:    $startline   - Reference to hash where key is question number (0 is first)
10519:                   and value is number of first bubble line for current student
10520:                   or code-based randompick and/or randomorder.
10521: 
10522: 
10523: 
10524: =item  scantron_get_maxbubble() : 
10525: 
10526:    Arguments:
10527:        $nav_error  - Reference to scalar which is a flag to indicate a
10528:                       failure to retrieve a navmap object.
10529:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
10530:        calling routine should trap the error condition and display the warning
10531:        found in &navmap_errormsg().
10532: 
10533:        $scantron_config - Reference to bubblesheet format configuration hash.
10534: 
10535:    Returns the maximum number of bubble lines that are expected to
10536:    occur. Does this by walking the selected sequence rendering the
10537:    resource and then checking &Apache::lonxml::get_problem_counter()
10538:    for what the current value of the problem counter is.
10539: 
10540:    Caches the results to $env{'form.scantron_maxbubble'},
10541:    $env{'form.scantron.bubble_lines.n'}, 
10542:    $env{'form.scantron.first_bubble_line.n'} and
10543:    $env{"form.scantron.sub_bubblelines.n"}
10544:    which are the total number of bubble lines, the number of bubble
10545:    lines for response n and number of the first bubble line for response n,
10546:    and a comma separated list of numbers of bubble lines for sub-questions
10547:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
10548: 
10549: 
10550: =item  scantron_validate_missingbubbles() : 
10551: 
10552:    Validates all scanlines in the selected file to not have any
10553:     answers that don't have bubbles that have not been verified
10554:     to be bubble free.
10555: 
10556: =item  scantron_process_students() : 
10557: 
10558:    Routine that does the actual grading of the bubblesheet information.
10559: 
10560:    The parsed scanline hash is added to %env 
10561: 
10562:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
10563:    foreach resource , with the form data of
10564: 
10565: 	'submitted'     =>'scantron' 
10566: 	'grade_target'  =>'grade',
10567: 	'grade_username'=> username of student
10568: 	'grade_domain'  => domain of student
10569: 	'grade_courseid'=> of course
10570: 	'grade_symb'    => symb of resource to grade
10571: 
10572:     This triggers a grading pass. The problem grading code takes care
10573:     of converting the bubbled letter information (now in %env) into a
10574:     valid submission.
10575: 
10576: =item  scantron_upload_scantron_data() :
10577: 
10578:     Creates the screen for adding a new bubblesheet data file to a course.
10579: 
10580: =item  scantron_upload_scantron_data_save() : 
10581: 
10582:    Adds a provided bubble information data file to the course if user
10583:    has the correct privileges to do so. 
10584: 
10585: =item  valid_file() :
10586: 
10587:    Validates that the requested bubble data file exists in the course.
10588: 
10589: =item  scantron_download_scantron_data() : 
10590: 
10591:    Shows a list of the three internal files (original, corrected,
10592:    skipped) for a specific bubblesheet data file that exists in the
10593:    course.
10594: 
10595: =item  scantron_validate_ID() : 
10596: 
10597:    Validates all scanlines in the selected file to not have any
10598:    invalid or underspecified student/employee IDs
10599: 
10600: =item navmap_errormsg() :
10601: 
10602:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
10603:    Should be called whenever the request to instantiate a navmap object fails.
10604: 
10605: =back
10606: 
10607: =back
10608: 
10609: =cut

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