File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.772: download - view: text, annotated - select for diffs
Sat Aug 29 16:39:00 2020 UTC (3 years, 8 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Keyword highlighting.
  Convert object to string to permit use of replace().

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.772 2020/08/29 16:39:00 raeburn 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 Apache::lontexconvert();
   50: use String::Similarity;
   51: use HTML::Parser();
   52: use File::MMagic;
   53: use LONCAPA;
   54: 
   55: use POSIX qw(floor);
   56: 
   57: 
   58: 
   59: my %perm=();
   60: my %old_essays=();
   61: 
   62: #  These variables are used to recover from ssi errors
   63: 
   64: my $ssi_retries = 5;
   65: my $ssi_error;
   66: my $ssi_error_resource;
   67: my $ssi_error_message;
   68: 
   69: 
   70: sub ssi_with_retries {
   71:     my ($resource, $retries, %form) = @_;
   72:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
   73:     if ($response->is_error) {
   74: 	$ssi_error          = 1;
   75: 	$ssi_error_resource = $resource;
   76: 	$ssi_error_message  = $response->code . " " . $response->message;
   77:     }
   78: 
   79:     return $content;
   80: 
   81: }
   82: #
   83: #  Prodcuces an ssi retry failure error message to the user:
   84: #
   85: 
   86: sub ssi_print_error {
   87:     my ($r) = @_;
   88:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
   89:     $r->print('
   90: <br />
   91: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
   92: <p>
   93: '.&mt('Unable to retrieve a resource from a server:').'<br />
   94: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
   95: '.&mt('Error:').' '.$ssi_error_message.'
   96: </p>
   97: <p>'.
   98: &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 />'.
   99: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
  100: '</p>');
  101:     return;
  102: }
  103: 
  104: #
  105: # --- Retrieve the parts from the metadata file.---
  106: # Returns an array of everything that the resources stores away
  107: #
  108: 
  109: sub getpartlist {
  110:     my ($symb,$errorref) = @_;
  111: 
  112:     my $navmap   = Apache::lonnavmaps::navmap->new();
  113:     unless (ref($navmap)) {
  114:         if (ref($errorref)) { 
  115:             $$errorref = 'navmap';
  116:             return;
  117:         }
  118:     }
  119:     my $res      = $navmap->getBySymb($symb);
  120:     my $partlist = $res->parts();
  121:     my $url      = $res->src();
  122:     my $toolsymb;
  123:     if ($url =~ /ext\.tool$/) {
  124:         $toolsymb = $symb;
  125:     }
  126:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys',$toolsymb));
  127: 
  128:     my @stores;
  129:     foreach my $part (@{ $partlist }) {
  130: 	foreach my $key (@metakeys) {
  131: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
  132: 	}
  133:     }
  134:     return @stores;
  135: }
  136: 
  137: #--- Format fullname, username:domain if different for display
  138: #--- Use anywhere where the student names are listed
  139: sub nameUserString {
  140:     my ($type,$fullname,$uname,$udom) = @_;
  141:     if ($type eq 'header') {
  142: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
  143:     } else {
  144: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
  145: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
  146:     }
  147: }
  148: 
  149: #--- Get the partlist and the response type for a given problem. ---
  150: #--- Indicate if a response type is coded handgraded or not. ---
  151: #--- Sets response_error pointer to "1" if navmaps object broken ---
  152: sub response_type {
  153:     my ($symb,$response_error) = @_;
  154: 
  155:     my $navmap = Apache::lonnavmaps::navmap->new();
  156:     unless (ref($navmap)) {
  157:         if (ref($response_error)) {
  158:             $$response_error = 1;
  159:         }
  160:         return;
  161:     }
  162:     my $res = $navmap->getBySymb($symb);
  163:     unless (ref($res)) {
  164:         $$response_error = 1;
  165:         return;
  166:     }
  167:     my $partlist = $res->parts();
  168:     my %vPart = 
  169: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
  170:     my (%response_types,%handgrade);
  171:     foreach my $part (@{ $partlist }) {
  172: 	next if (%vPart && !exists($vPart{$part}));
  173: 
  174: 	my @types = $res->responseType($part);
  175: 	my @ids = $res->responseIds($part);
  176: 	for (my $i=0; $i < scalar(@ids); $i++) {
  177: 	    $response_types{$part}{$ids[$i]} = $types[$i];
  178: 	    $handgrade{$part.'_'.$ids[$i]} = 
  179: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
  180: 				     '.handgrade',$symb);
  181: 	}
  182:     }
  183:     return ($partlist,\%handgrade,\%response_types);
  184: }
  185: 
  186: sub flatten_responseType {
  187:     my ($responseType) = @_;
  188:     my @part_response_id =
  189: 	map { 
  190: 	    my $part = $_;
  191: 	    map {
  192: 		[$part,$_]
  193: 		} sort(keys(%{ $responseType->{$part} }));
  194: 	} sort(keys(%$responseType));
  195:     return @part_response_id;
  196: }
  197: 
  198: sub get_display_part {
  199:     my ($partID,$symb)=@_;
  200:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
  201:     if (defined($display) and $display ne '') {
  202:         $display.= ' (<span class="LC_internal_info">'
  203:                   .&mt('Part ID: [_1]',$partID).'</span>)';
  204:     } else {
  205: 	$display=$partID;
  206:     }
  207:     return $display;
  208: }
  209: 
  210: sub reset_caches {
  211:     &reset_analyze_cache();
  212:     &reset_perm();
  213:     &reset_old_essays();
  214: }
  215: 
  216: {
  217:     my %analyze_cache;
  218:     my %analyze_cache_formkeys;
  219: 
  220:     sub reset_analyze_cache {
  221: 	undef(%analyze_cache);
  222:         undef(%analyze_cache_formkeys);
  223:     }
  224: 
  225:     sub get_analyze {
  226: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
  227: 	my $key = "$symb\0$uname\0$udom";
  228:         if ($type eq 'randomizetry') {
  229:             if ($trial ne '') {
  230:                 $key .= "\0".$trial;
  231:             }
  232:         }
  233: 	if (exists($analyze_cache{$key})) {
  234:             my $getupdate = 0;
  235:             if (ref($add_to_hash) eq 'HASH') {
  236:                 foreach my $item (keys(%{$add_to_hash})) {
  237:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
  238:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
  239:                             $getupdate = 1;
  240:                             last;
  241:                         }
  242:                     } else {
  243:                         $getupdate = 1;
  244:                     }
  245:                 }
  246:             }
  247:             if (!$getupdate) {
  248:                 return $analyze_cache{$key};
  249:             }
  250:         }
  251: 
  252: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  253: 	$url=&Apache::lonnet::clutter($url);
  254:         my %form = ('grade_target'      => 'analyze',
  255:                     'grade_domain'      => $udom,
  256:                     'grade_symb'        => $symb,
  257:                     'grade_courseid'    =>  $env{'request.course.id'},
  258:                     'grade_username'    => $uname,
  259:                     'grade_noincrement' => $no_increment);
  260:         if ($bubbles_per_row ne '') {
  261:             $form{'bubbles_per_row'} = $bubbles_per_row;
  262:         }
  263:         if ($type eq 'randomizetry') {
  264:             $form{'grade_questiontype'} = $type;
  265:             if ($rndseed ne '') {
  266:                 $form{'grade_rndseed'} = $rndseed;
  267:             }
  268:         }
  269:         if (ref($add_to_hash)) {
  270:             %form = (%form,%{$add_to_hash});
  271:         }
  272: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
  273: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  274: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  275:         if (ref($add_to_hash) eq 'HASH') {
  276:             $analyze_cache_formkeys{$key} = $add_to_hash;
  277:         } else {
  278:             $analyze_cache_formkeys{$key} = {};
  279:         }
  280: 	return $analyze_cache{$key} = \%analyze;
  281:     }
  282: 
  283:     sub get_order {
  284: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
  285: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
  286: 	return $analyze->{"$partid.$respid.shown"};
  287:     }
  288: 
  289:     sub get_radiobutton_correct_foil {
  290: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
  291: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
  292:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
  293:         if (ref($foils) eq 'ARRAY') {
  294: 	    foreach my $foil (@{$foils}) {
  295: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  296: 		    return $foil;
  297: 	        }
  298: 	    }
  299: 	}
  300:     }
  301: 
  302:     sub scantron_partids_tograde {
  303:         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row,$scancode) = @_;
  304:         my (%analysis,@parts);
  305:         if (ref($resource)) {
  306:             my $symb = $resource->symb();
  307:             my $add_to_form;
  308:             if ($check_for_randomlist) {
  309:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
  310:             }
  311:             if ($scancode) {
  312:                 if (ref($add_to_form) eq 'HASH') {
  313:                     $add_to_form->{'code_for_randomlist'} = $scancode;
  314:                 } else {
  315:                     $add_to_form = { 'code_for_randomlist' => $scancode,};
  316:                 }
  317:             }
  318:             my $analyze =
  319:                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
  320:                              undef,undef,undef,$bubbles_per_row);
  321:             if (ref($analyze) eq 'HASH') {
  322:                 %analysis = %{$analyze};
  323:             }
  324:             if (ref($analysis{'parts'}) eq 'ARRAY') {
  325:                 foreach my $part (@{$analysis{'parts'}}) {
  326:                     my ($id,$respid) = split(/\./,$part);
  327:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
  328:                         push(@parts,$part);
  329:                     }
  330:                 }
  331:             }
  332:         }
  333:         return (\%analysis,\@parts);
  334:     }
  335: 
  336: }
  337: 
  338: #--- Clean response type for display
  339: #--- Currently filters option/rank/radiobutton/match/essay/Task
  340: #        response types only.
  341: sub cleanRecord {
  342:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  343: 	$uname,$udom,$type,$trial,$rndseed) = @_;
  344:     my $grayFont = '<span class="LC_internal_info">';
  345:     if ($response =~ /^(option|rank)$/) {
  346: 	my %answer=&Apache::lonnet::str2hash($answer);
  347:         my @answer = %answer;
  348:         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
  349: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  350: 	my ($toprow,$bottomrow);
  351: 	foreach my $foil (@$order) {
  352: 	    if ($grading{$foil} == 1) {
  353: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  354: 	    } else {
  355: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  356: 	    }
  357: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  358: 	}
  359: 	return '<blockquote><table border="1">'.
  360: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  361: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  362: 	    $bottomrow.'</tr></table></blockquote>';
  363:     } elsif ($response eq 'match') {
  364: 	my %answer=&Apache::lonnet::str2hash($answer);
  365:         my @answer = %answer;
  366:         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
  367: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  368: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  369: 	my ($toprow,$middlerow,$bottomrow);
  370: 	foreach my $foil (@$order) {
  371: 	    my $item=shift(@items);
  372: 	    if ($grading{$foil} == 1) {
  373: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  374: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  375: 	    } else {
  376: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  377: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  378: 	    }
  379: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  380: 	}
  381: 	return '<blockquote><table border="1">'.
  382: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  383: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  384: 	    $middlerow.'</tr>'.
  385: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  386: 	    $bottomrow.'</tr></table></blockquote>';
  387:     } elsif ($response eq 'radiobutton') {
  388: 	my %answer=&Apache::lonnet::str2hash($answer);
  389:         my @answer = %answer;
  390:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
  391: 	my ($toprow,$bottomrow);
  392: 	my $correct = 
  393: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
  394: 	foreach my $foil (@$order) {
  395: 	    if (exists($answer{$foil})) {
  396: 		if ($foil eq $correct) {
  397: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  398: 		} else {
  399: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  400: 		}
  401: 	    } else {
  402: 		$toprow.='<td>'.&mt('false').'</td>';
  403: 	    }
  404: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  405: 	}
  406: 	return '<blockquote><table border="1">'.
  407: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  408: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  409: 	    $bottomrow.'</tr></table></blockquote>';
  410:     } elsif ($response eq 'essay') {
  411: 	if (! exists ($env{'form.'.$symb})) {
  412: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  413: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  414: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  415: 
  416: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  417: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  418: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  419: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  420: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  421: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  422: 	}
  423:         $answer = &Apache::lontexconvert::msgtexconverted($answer);
  424: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  425:     } elsif ( $response eq 'organic') {
  426:         my $result=&mt('Smile representation: [_1]',
  427:                            '"<tt>'.&HTML::Entities::encode($answer, '"<>&').'</tt>"');
  428: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  429: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  430: 	return $result;
  431:     } elsif ( $response eq 'Task') {
  432: 	if ( $answer eq 'SUBMITTED') {
  433: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  434: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  435: 	    return $result;
  436: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  437: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  438: 			       keys(%{$record}));
  439: 	    return join('<br />',($version,@matches));
  440: 			       
  441: 			       
  442: 	} else {
  443: 	    my $result =
  444: 		'<p>'
  445: 		.&mt('Overall result: [_1]',
  446: 		     $record->{$version."resource.$respid.$partid.status"})
  447: 		.'</p>';
  448: 	    
  449: 	    $result .= '<ul>';
  450: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  451: 			     keys(%{$record}));
  452: 	    foreach my $grade (sort(@grade)) {
  453: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  454: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  455: 				     $dim, $record->{$grade}).
  456: 			  '</li>';
  457: 	    }
  458: 	    $result.='</ul>';
  459: 	    return $result;
  460: 	}
  461:     } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
  462:         # Respect multiple input fields, see Bug #5409
  463: 	$answer = 
  464: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  465: 							      $answer);
  466: 	return $answer;
  467:     }
  468:     return &HTML::Entities::encode($answer, '"<>&');
  469: }
  470: 
  471: #-- A couple of common js functions
  472: sub commonJSfunctions {
  473:     my $request = shift;
  474:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
  475:     function radioSelection(radioButton) {
  476: 	var selection=null;
  477: 	if (radioButton.length > 1) {
  478: 	    for (var i=0; i<radioButton.length; i++) {
  479: 		if (radioButton[i].checked) {
  480: 		    return radioButton[i].value;
  481: 		}
  482: 	    }
  483: 	} else {
  484: 	    if (radioButton.checked) return radioButton.value;
  485: 	}
  486: 	return selection;
  487:     }
  488: 
  489:     function pullDownSelection(selectOne) {
  490: 	var selection="";
  491: 	if (selectOne.length > 1) {
  492: 	    for (var i=0; i<selectOne.length; i++) {
  493: 		if (selectOne[i].selected) {
  494: 		    return selectOne[i].value;
  495: 		}
  496: 	    }
  497: 	} else {
  498:             // only one value it must be the selected one
  499: 	    return selectOne.value;
  500: 	}
  501:     }
  502: COMMONJSFUNCTIONS
  503: }
  504: 
  505: #--- Dumps the class list with usernames,list of sections,
  506: #--- section, ids and fullnames for each user.
  507: sub getclasslist {
  508:     my ($getsec,$filterbyaccstatus,$getgroup,$symb,$submitonly,$filterbysubmstatus) = @_;
  509:     my @getsec;
  510:     my @getgroup;
  511:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  512:     if (!ref($getsec)) {
  513: 	if ($getsec ne '' && $getsec ne 'all') {
  514: 	    @getsec=($getsec);
  515: 	}
  516:     } else {
  517: 	@getsec=@{$getsec};
  518:     }
  519:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  520:     if (!ref($getgroup)) {
  521: 	if ($getgroup ne '' && $getgroup ne 'all') {
  522: 	    @getgroup=($getgroup);
  523: 	}
  524:     } else {
  525: 	@getgroup=@{$getgroup};
  526:     }
  527:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  528: 
  529:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  530:     # Bail out if we were unable to get the classlist
  531:     return if (! defined($classlist));
  532:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  533:     #
  534:     my %sections;
  535:     my %fullnames;
  536:     my ($cdom,$cnum,$partlist);
  537:     if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
  538:         $cdom = $env{"course.$env{'request.course.id'}.domain"};
  539:         $cnum = $env{"course.$env{'request.course.id'}.num"};
  540:         my $res_error;
  541:         ($partlist,my $handgrade,my $responseType) = &response_type($symb,\$res_error);
  542:     }
  543:     foreach my $student (keys(%$classlist)) {
  544:         my $end      = 
  545:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  546:         my $start    = 
  547:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  548:         my $id       = 
  549:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  550:         my $section  = 
  551:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  552:         my $fullname = 
  553:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  554:         my $status   = 
  555:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  556:         my $group   = 
  557:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  558: 	# filter students according to status selected
  559: 	if ($filterbyaccstatus && (!($stu_status =~ /Any/))) {
  560: 	    if (!($stu_status =~ $status)) {
  561: 		delete($classlist->{$student});
  562: 		next;
  563: 	    }
  564: 	}
  565: 	# filter students according to groups selected
  566: 	my @stu_groups = split(/,/,$group);
  567: 	if (@getgroup) {
  568: 	    my $exclude = 1;
  569: 	    foreach my $grp (@getgroup) {
  570: 	        foreach my $stu_group (@stu_groups) {
  571: 	            if ($stu_group eq $grp) {
  572: 	                $exclude = 0;
  573:     	            } 
  574: 	        }
  575:     	        if (($grp eq 'none') && !$group) {
  576:         	    $exclude = 0;
  577:         	}
  578: 	    }
  579: 	    if ($exclude) {
  580: 	        delete($classlist->{$student});
  581: 		next;
  582: 	    }
  583: 	}
  584:         if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
  585:             my $udom =
  586:                 $classlist->{$student}->[&Apache::loncoursedata::CL_SDOM()];
  587:             my $uname =
  588:                 $classlist->{$student}->[&Apache::loncoursedata::CL_SNAME()];
  589:             if (($symb ne '') && ($udom ne '') && ($uname ne '')) {
  590:                 if ($submitonly eq 'queued') {
  591:                     my %queue_status =
  592:                         &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
  593:                                                                 $udom,$uname);
  594:                     if (!defined($queue_status{'gradingqueue'})) {
  595:                         delete($classlist->{$student});
  596:                         next;
  597:                     }
  598:                 } else {
  599:                     my (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
  600:                     my $submitted = 0;
  601:                     my $graded = 0;
  602:                     my $incorrect = 0;
  603:                     foreach (keys(%status)) {
  604:                         $submitted = 1 if ($status{$_} ne 'nothing');
  605:                         $graded = 1 if ($status{$_} =~ /^ungraded/);
  606:                         $incorrect = 1 if ($status{$_} =~ /^incorrect/);
  607: 
  608:                         my ($foo,$partid,$foo1) = split(/\./,$_);
  609:                         if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
  610:                             $submitted = 0;
  611:                         }
  612:                     }
  613:                     if (!$submitted && ($submitonly eq 'yes' ||
  614:                                         $submitonly eq 'incorrect' ||
  615:                                         $submitonly eq 'graded')) {
  616:                         delete($classlist->{$student});
  617:                         next;
  618:                     } elsif (!$graded && ($submitonly eq 'graded')) {
  619:                         delete($classlist->{$student});
  620:                         next;
  621:                     } elsif (!$incorrect && $submitonly eq 'incorrect') {
  622:                         delete($classlist->{$student});
  623:                         next;
  624:                     }
  625:                 }
  626:             }
  627:         }
  628: 	$section = ($section ne '' ? $section : 'none');
  629: 	if (&canview($section)) {
  630: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  631: 		$sections{$section}++;
  632: 		if ($classlist->{$student}) {
  633: 		    $fullnames{$student}=$fullname;
  634: 		}
  635: 	    } else {
  636: 		delete($classlist->{$student});
  637: 	    }
  638: 	} else {
  639: 	    delete($classlist->{$student});
  640: 	}
  641:     }
  642:     my @sections = sort(keys(%sections));
  643:     return ($classlist,\@sections,\%fullnames);
  644: }
  645: 
  646: sub canmodify {
  647:     my ($sec)=@_;
  648:     if ($perm{'mgr'}) {
  649: 	if (!defined($perm{'mgr_section'})) {
  650: 	    # can modify whole class
  651: 	    return 1;
  652: 	} else {
  653: 	    if ($sec eq $perm{'mgr_section'}) {
  654: 		#can modify the requested section
  655: 		return 1;
  656: 	    } else {
  657: 		# can't modify the requested section
  658: 		return 0;
  659: 	    }
  660: 	}
  661:     }
  662:     #can't modify
  663:     return 0;
  664: }
  665: 
  666: sub canview {
  667:     my ($sec)=@_;
  668:     if ($perm{'vgr'}) {
  669: 	if (!defined($perm{'vgr_section'})) {
  670: 	    # can view whole class
  671: 	    return 1;
  672: 	} else {
  673: 	    if ($sec eq $perm{'vgr_section'}) {
  674: 		#can view the requested section
  675: 		return 1;
  676: 	    } else {
  677: 		# can't view the requested section
  678: 		return 0;
  679: 	    }
  680: 	}
  681:     }
  682:     #can't view
  683:     return 0;
  684: }
  685: 
  686: #--- Retrieve the grade status of a student for all the parts
  687: sub student_gradeStatus {
  688:     my ($symb,$udom,$uname,$partlist) = @_;
  689:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  690:     my %partstatus = ();
  691:     foreach (@$partlist) {
  692: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  693: 	$status              = 'nothing' if ($status eq '');
  694: 	$partstatus{$_}      = $status;
  695: 	my $subkey           = "resource.$_.submitted_by";
  696: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  697:     }
  698:     return %partstatus;
  699: }
  700: 
  701: # hidden form and javascript that calls the form
  702: # Use by verifyscript and viewgrades
  703: # Shows a student's view of problem and submission
  704: sub jscriptNform {
  705:     my ($symb) = @_;
  706:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  707:     my $jscript= &Apache::lonhtmlcommon::scripttag(
  708: 	'    function viewOneStudent(user,domain) {'."\n".
  709: 	'	document.onestudent.student.value = user;'."\n".
  710: 	'	document.onestudent.userdom.value = domain;'."\n".
  711: 	'	document.onestudent.submit();'."\n".
  712: 	'    }'."\n".
  713: 	"\n");
  714:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  715: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  716: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  717: 	'<input type="hidden" name="command" value="submission" />'."\n".
  718: 	'<input type="hidden" name="student" value="" />'."\n".
  719: 	'<input type="hidden" name="userdom" value="" />'."\n".
  720: 	'</form>'."\n";
  721:     return $jscript;
  722: }
  723: 
  724: 
  725: 
  726: # Given the score (as a number [0-1] and the weight) what is the final
  727: # point value? This function will round to the nearest tenth, third,
  728: # or quarter if one of those is within the tolerance of .00001.
  729: sub compute_points {
  730:     my ($score, $weight) = @_;
  731:     
  732:     my $tolerance = .00001;
  733:     my $points = $score * $weight;
  734: 
  735:     # Check for nearness to 1/x.
  736:     my $check_for_nearness = sub {
  737:         my ($factor) = @_;
  738:         my $num = ($points * $factor) + $tolerance;
  739:         my $floored_num = floor($num);
  740:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  741:             return $floored_num / $factor;
  742:         }
  743:         return $points;
  744:     };
  745: 
  746:     $points = $check_for_nearness->(10);
  747:     $points = $check_for_nearness->(3);
  748:     $points = $check_for_nearness->(4);
  749:     
  750:     return $points;
  751: }
  752: 
  753: #------------------ End of general use routines --------------------
  754: 
  755: #
  756: # Find most similar essay
  757: #
  758: 
  759: sub most_similar {
  760:     my ($uname,$udom,$symb,$uessay)=@_;
  761: 
  762:     unless ($symb) { return ''; }
  763: 
  764:     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
  765: 
  766: # ignore spaces and punctuation
  767: 
  768:     $uessay=~s/\W+/ /gs;
  769: 
  770: # ignore empty submissions (occuring when only files are sent)
  771: 
  772:     unless ($uessay=~/\w+/s) { return ''; }
  773: 
  774: # these will be returned. Do not care if not at least 50 percent similar
  775:     my $limit=0.6;
  776:     my $sname='';
  777:     my $sdom='';
  778:     my $scrsid='';
  779:     my $sessay='';
  780: # go through all essays ...
  781:     foreach my $tkey (keys(%{$old_essays{$symb}})) {
  782: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  783: # ... except the same student
  784:         next if (($tname eq $uname) && ($tdom eq $udom));
  785: 	my $tessay=$old_essays{$symb}{$tkey};
  786: 	$tessay=~s/\W+/ /gs;
  787: # String similarity gives up if not even limit
  788: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  789: # Found one
  790: 	if ($tsimilar>$limit) {
  791: 	    $limit=$tsimilar;
  792: 	    $sname=$tname;
  793: 	    $sdom=$tdom;
  794: 	    $scrsid=$tcrsid;
  795: 	    $sessay=$old_essays{$symb}{$tkey};
  796: 	}
  797:     }
  798:     if ($limit>0.6) {
  799:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  800:     } else {
  801:        return ('','','','',0);
  802:     }
  803: }
  804: 
  805: #-------------------------------------------------------------------
  806: 
  807: #------------------------------------ Receipt Verification Routines
  808: #
  809: 
  810: sub initialverifyreceipt {
  811:    my ($request,$symb) = @_;
  812:    &commonJSfunctions($request);
  813:    return '<form name="gradingMenu" action=""><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
  814:         &Apache::lonnet::recprefix($env{'request.course.id'}).
  815:         '-<input type="text" name="receipt" size="4" />'.
  816:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  817:         '<input type="hidden" name="command" value="verify" />'.
  818:         "</form>\n";
  819: }
  820: 
  821: #--- Check whether a receipt number is valid.---
  822: sub verifyreceipt {
  823:     my ($request,$symb) = @_;
  824: 
  825:     my $courseid = $env{'request.course.id'};
  826:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  827: 	$env{'form.receipt'};
  828:     $receipt     =~ s/[^\-\d]//g;
  829: 
  830:     my $title =
  831: 	'<h3><span class="LC_info">'.
  832: 	&mt('Verifying Receipt Number [_1]',$receipt).
  833: 	'</span></h3>'."\n";
  834: 
  835:     my ($string,$contents,$matches) = ('','',0);
  836:     my (undef,undef,$fullname) = &getclasslist('all','0');
  837:     
  838:     my $receiptparts=0;
  839:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  840: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  841:     my $parts=['0'];
  842:     if ($receiptparts) {
  843:         my $res_error; 
  844:         ($parts)=&response_type($symb,\$res_error);
  845:         if ($res_error) {
  846:             return &navmap_errormsg();
  847:         } 
  848:     }
  849:     
  850:     my $header = 
  851: 	&Apache::loncommon::start_data_table().
  852: 	&Apache::loncommon::start_data_table_header_row().
  853: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  854: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  855: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  856:     if ($receiptparts) {
  857: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  858:     }
  859:     $header.=
  860: 	&Apache::loncommon::end_data_table_header_row();
  861: 
  862:     foreach (sort 
  863: 	     {
  864: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  865: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  866: 		 }
  867: 		 return $a cmp $b;
  868: 	     } (keys(%$fullname))) {
  869: 	my ($uname,$udom)=split(/\:/);
  870: 	foreach my $part (@$parts) {
  871: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  872: 		$contents.=
  873: 		    &Apache::loncommon::start_data_table_row().
  874: 		    '<td>&nbsp;'."\n".
  875: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  876: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  877: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  878: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  879: 		if ($receiptparts) {
  880: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  881: 		}
  882: 		$contents.= 
  883: 		    &Apache::loncommon::end_data_table_row()."\n";
  884: 		
  885: 		$matches++;
  886: 	    }
  887: 	}
  888:     }
  889:     if ($matches == 0) {
  890:         $string = $title
  891:                  .'<p class="LC_warning">'
  892:                  .&mt('No match found for the above receipt number.')
  893:                  .'</p>';
  894:     } else {
  895: 	$string = &jscriptNform($symb).$title.
  896: 	    '<p>'.
  897: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
  898: 	    '</p>'.
  899: 	    $header.
  900: 	    $contents.
  901: 	    &Apache::loncommon::end_data_table()."\n";
  902:     }
  903:     return $string;
  904: }
  905: 
  906: #--- This is called by a number of programs.
  907: #--- Called from the Grading Menu - View/Grade an individual student
  908: #--- Also called directly when one clicks on the subm button 
  909: #    on the problem page.
  910: sub listStudents {
  911:     my ($request,$symb,$submitonly) = @_;
  912: 
  913:     my $is_tool   = ($symb =~ /ext\.tool$/);
  914:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  915:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  916:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  917:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  918:     unless ($submitonly) {
  919:         $submitonly = $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  920:     }
  921: 
  922:     my $result='';
  923:     my $res_error;
  924:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
  925: 
  926:     my %js_lt = &Apache::lonlocal::texthash (
  927: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
  928: 		'single'   => 'Please select the student before clicking on the Next button.',
  929: 	     );
  930:     &js_escape(\%js_lt);
  931:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
  932:     function checkSelect(checkBox) {
  933: 	var ctr=0;
  934: 	var sense="";
  935: 	if (checkBox.length > 1) {
  936: 	    for (var i=0; i<checkBox.length; i++) {
  937: 		if (checkBox[i].checked) {
  938: 		    ctr++;
  939: 		}
  940: 	    }
  941: 	    sense = '$js_lt{'multiple'}';
  942: 	} else {
  943: 	    if (checkBox.checked) {
  944: 		ctr = 1;
  945: 	    }
  946: 	    sense = '$js_lt{'single'}';
  947: 	}
  948: 	if (ctr == 0) {
  949: 	    alert(sense);
  950: 	    return false;
  951: 	}
  952: 	document.gradesub.submit();
  953:     }
  954: 
  955:     function reLoadList(formname) {
  956: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  957: 	formname.command.value = 'submission';
  958: 	formname.submit();
  959:     }
  960: LISTJAVASCRIPT
  961: 
  962:     &commonJSfunctions($request);
  963:     $request->print($result);
  964: 
  965:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  966: 	"\n";
  967: 	
  968:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
  969:     unless ($is_tool) {
  970:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
  971:                       .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
  972:                       .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
  973:                       .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
  974:                       .&Apache::lonhtmlcommon::row_closure();
  975:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
  976:                       .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
  977:                       .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
  978:                       .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
  979:                       .&Apache::lonhtmlcommon::row_closure();
  980:     }
  981: 
  982:     my $submission_options;
  983:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  984:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  985:     $env{'form.Status'} = $saveStatus;
  986:     my %optiontext;
  987:     if ($is_tool) {
  988:         %optiontext = &Apache::lonlocal::texthash (
  989:                           lastonly => 'last transaction',
  990:                           last     => 'last transaction with details',
  991:                           datesub  => 'all transactions',
  992:                           all      => 'all transactions with details',
  993:                       );
  994:     } else {
  995:         %optiontext = &Apache::lonlocal::texthash (
  996:                           lastonly => 'last submission',
  997:                           last     => 'last submission with details',
  998:                           datesub  => 'all submissions',
  999:                           all      => 'all submissions with details',
 1000:                       );
 1001:     }
 1002:     $submission_options.=
 1003:         '<span class="LC_nobreak">'.
 1004:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
 1005:         $optiontext{'lastonly'}.' </label></span>'."\n".
 1006:         '<span class="LC_nobreak">'.
 1007:         '<label><input type="radio" name="lastSub" value="last" /> '.
 1008:         $optiontext{'last'}.' </label></span>'."\n".
 1009:         '<span class="LC_nobreak">'.
 1010:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
 1011:         $optiontext{'datesub'}.'</label></span>'."\n".
 1012:         '<span class="LC_nobreak">'.
 1013:         '<label><input type="radio" name="lastSub" value="all" /> '.
 1014:         $optiontext{'all'}.'</label></span>';
 1015:     my $viewtitle;
 1016:     if ($is_tool) {
 1017:         $viewtitle = &mt('View Transactions');
 1018:     } else {
 1019:         $viewtitle = &mt('View Submissions');
 1020:     }
 1021:     $gradeTable .= &Apache::lonhtmlcommon::row_title($viewtitle)
 1022:                   .$submission_options
 1023:                   .&Apache::lonhtmlcommon::row_closure();
 1024: 
 1025:     my $closure;
 1026:     if (($is_tool) && (exists($env{'form.Status'}))) {
 1027:         $closure = 1;
 1028:     }
 1029:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
 1030:                   .'<select name="increment">'
 1031:                   .'<option value="1">'.&mt('Whole Points').'</option>'
 1032:                   .'<option value=".5">'.&mt('Half Points').'</option>'
 1033:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
 1034:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
 1035:                   .'</select>'
 1036:                   .&Apache::lonhtmlcommon::row_closure($closure);
 1037: 
 1038:     $gradeTable .= 
 1039:         &build_section_inputs().
 1040: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
 1041: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1042: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
 1043: 
 1044:     if (exists($env{'form.Status'})) {
 1045: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
 1046:     } else {
 1047:         if ($is_tool) {
 1048:             $closure = 1;
 1049:         }
 1050:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
 1051:                       .&Apache::lonhtmlcommon::StatusOptions(
 1052:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
 1053:                       .&Apache::lonhtmlcommon::row_closure($closure);
 1054:     }
 1055: 
 1056:     unless ($is_tool) {
 1057:         $closure = 1;
 1058:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
 1059:                       .'<input type="checkbox" name="checkPlag" checked="checked" />'
 1060:                       .&Apache::lonhtmlcommon::row_closure($closure);
 1061:     }
 1062:     $gradeTable .= &Apache::lonhtmlcommon::end_pick_box();
 1063:     my $regrademsg;
 1064:     if ($is_tool) {
 1065:         $regrademsg =&mt("To view/grade/regrade, click on the check box(es) next to the student's name(s). Then click on the Next button.");
 1066:     } else {
 1067:         $regrademsg = &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.");
 1068:     }
 1069:     $gradeTable .= '<p>'
 1070:                   .$regrademsg."\n"
 1071:                   .'<input type="hidden" name="command" value="processGroup" />'
 1072:                   .'</p>';
 1073: 
 1074: # checkall buttons
 1075:     $gradeTable.=&check_script('gradesub', 'stuinfo');
 1076:     $gradeTable.='<input type="button" '."\n".
 1077:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
 1078:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
 1079:     $gradeTable.=&check_buttons();
 1080:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
 1081:     $gradeTable.= &Apache::loncommon::start_data_table().
 1082: 	&Apache::loncommon::start_data_table_header_row();
 1083:     my $loop = 0;
 1084:     while ($loop < 2) {
 1085: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
 1086: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
 1087: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1088: 	    foreach my $part (sort(@$partlist)) {
 1089: 		my $display_part=
 1090: 		    &get_display_part((split(/_/,$part))[0],$symb);
 1091: 		$gradeTable.=
 1092: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
 1093: 	    }
 1094: 	} elsif ($submitonly eq 'queued') {
 1095: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
 1096: 	}
 1097: 	$loop++;
 1098: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
 1099:     }
 1100:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
 1101: 
 1102:     my $ctr = 0;
 1103:     foreach my $student (sort 
 1104: 			 {
 1105: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 1106: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 1107: 			     }
 1108: 			     return $a cmp $b;
 1109: 			 }
 1110: 			 (keys(%$fullname))) {
 1111: 	my ($uname,$udom) = split(/:/,$student);
 1112: 
 1113: 	my %status = ();
 1114: 
 1115: 	if ($submitonly eq 'queued') {
 1116: 	    my %queue_status = 
 1117: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 1118: 							$udom,$uname);
 1119: 	    next if (!defined($queue_status{'gradingqueue'}));
 1120: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
 1121: 	}
 1122: 
 1123: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1124: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
 1125: 	    my $submitted = 0;
 1126: 	    my $graded = 0;
 1127: 	    my $incorrect = 0;
 1128: 	    foreach (keys(%status)) {
 1129: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1130: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1131: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1132: 		
 1133: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1134: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1135: 		    $submitted = 0;
 1136: 		    my ($part)=split(/\./,$partid);
 1137: 		    $gradeTable.='<input type="hidden" name="'.
 1138: 			$student.':'.$part.':submitted_by" value="'.
 1139: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1140: 		}
 1141: 	    }
 1142: 	    
 1143: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1144: 				     $submitonly eq 'incorrect' ||
 1145: 				     $submitonly eq 'graded'));
 1146: 	    next if (!$graded && ($submitonly eq 'graded'));
 1147: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1148: 	}
 1149: 
 1150: 	$ctr++;
 1151: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1152:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1153: 	if ( $perm{'vgr'} eq 'F' ) {
 1154: 	    if ($ctr%2 ==1) {
 1155: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1156: 	    }
 1157: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1158:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1159:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1160: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1161: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1162: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1163: 
 1164: 	    if ($submitonly ne 'all') {
 1165: 		foreach (sort(keys(%status))) {
 1166: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1167: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1168: 		}
 1169: 	    }
 1170: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1171: 	    if ($ctr%2 ==0) {
 1172: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1173: 	    }
 1174: 	}
 1175:     }
 1176:     if ($ctr%2 ==1) {
 1177: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1178: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1179: 		foreach (@$partlist) {
 1180: 		    $gradeTable.='<td>&nbsp;</td>';
 1181: 		}
 1182: 	    } elsif ($submitonly eq 'queued') {
 1183: 		$gradeTable.='<td>&nbsp;</td>';
 1184: 	    }
 1185: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1186:     }
 1187: 
 1188:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1189:         '<input type="button" '.
 1190:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
 1191:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1192:     if ($ctr == 0) {
 1193: 	my $num_students=(scalar(keys(%$fullname)));
 1194: 	if ($num_students eq 0) {
 1195: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1196: 	} else {
 1197: 	    my $submissions='submissions';
 1198: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1199: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1200: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1201: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1202: 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
 1203: 		    $num_students).
 1204: 		'</span><br />';
 1205: 	}
 1206:     } elsif ($ctr == 1) {
 1207: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1208:     }
 1209:     $request->print($gradeTable);
 1210:     return '';
 1211: }
 1212: 
 1213: #---- Called from the listStudents routine
 1214: 
 1215: sub check_script {
 1216:     my ($form,$type) = @_;
 1217:     my $chkallscript = &Apache::lonhtmlcommon::scripttag('
 1218:     function checkall() {
 1219:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1220:             ele = document.forms.'.$form.'.elements[i];
 1221:             if (ele.name == "'.$type.'") {
 1222:             document.forms.'.$form.'.elements[i].checked=true;
 1223:                                        }
 1224:         }
 1225:     }
 1226: 
 1227:     function checksec() {
 1228:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1229:             ele = document.forms.'.$form.'.elements[i];
 1230:            string = document.forms.'.$form.'.chksec.value;
 1231:            if
 1232:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1233:               document.forms.'.$form.'.elements[i].checked=true;
 1234:             }
 1235:         }
 1236:     }
 1237: 
 1238: 
 1239:     function uncheckall() {
 1240:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1241:             ele = document.forms.'.$form.'.elements[i];
 1242:             if (ele.name == "'.$type.'") {
 1243:             document.forms.'.$form.'.elements[i].checked=false;
 1244:                                        }
 1245:         }
 1246:     }
 1247: 
 1248: '."\n");
 1249:     return $chkallscript;
 1250: }
 1251: 
 1252: sub check_buttons {
 1253:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1254:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1255:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1256:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1257:     return $buttons;
 1258: }
 1259: 
 1260: #     Displays the submissions for one student or a group of students
 1261: sub processGroup {
 1262:     my ($request,$symb) = @_;
 1263:     my $ctr        = 0;
 1264:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1265:     my $total      = scalar(@stuchecked)-1;
 1266: 
 1267:     foreach my $student (@stuchecked) {
 1268: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1269: 	$env{'form.student'}        = $uname;
 1270: 	$env{'form.userdom'}        = $udom;
 1271: 	$env{'form.fullname'}       = $fullname;
 1272: 	&submission($request,$ctr,$total,$symb);
 1273: 	$ctr++;
 1274:     }
 1275:     return '';
 1276: }
 1277: 
 1278: #------------------------------------------------------------------------------------
 1279: #
 1280: #-------------------------- Next few routines handles grading by student, essentially
 1281: #                           handles essay response type problem/part
 1282: #
 1283: #--- Javascript to handle the submission page functionality ---
 1284: sub sub_page_js {
 1285:     my $request = shift;
 1286:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1287:     &js_escape(\$alertmsg);
 1288:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1289:     function updateRadio(formname,id,weight) {
 1290: 	var gradeBox = formname["GD_BOX"+id];
 1291: 	var radioButton = formname["RADVAL"+id];
 1292: 	var oldpts = formname["oldpts"+id].value;
 1293: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1294: 	gradeBox.value = pts;
 1295: 	var resetbox = false;
 1296: 	if (isNaN(pts) || pts < 0) {
 1297: 	    alert("$alertmsg"+pts);
 1298: 	    for (var i=0; i<radioButton.length; i++) {
 1299: 		if (radioButton[i].checked) {
 1300: 		    gradeBox.value = i;
 1301: 		    resetbox = true;
 1302: 		}
 1303: 	    }
 1304: 	    if (!resetbox) {
 1305: 		formtextbox.value = "";
 1306: 	    }
 1307: 	    return;
 1308: 	}
 1309: 
 1310: 	if (pts > weight) {
 1311: 	    var resp = confirm("You entered a value ("+pts+
 1312: 			       ") greater than the weight for the part. Accept?");
 1313: 	    if (resp == false) {
 1314: 		gradeBox.value = oldpts;
 1315: 		return;
 1316: 	    }
 1317: 	}
 1318: 
 1319: 	for (var i=0; i<radioButton.length; i++) {
 1320: 	    radioButton[i].checked=false;
 1321: 	    if (pts == i && pts != "") {
 1322: 		radioButton[i].checked=true;
 1323: 	    }
 1324: 	}
 1325: 	updateSelect(formname,id);
 1326: 	formname["stores"+id].value = "0";
 1327:     }
 1328: 
 1329:     function writeBox(formname,id,pts) {
 1330: 	var gradeBox = formname["GD_BOX"+id];
 1331: 	if (checkSolved(formname,id) == 'update') {
 1332: 	    gradeBox.value = pts;
 1333: 	} else {
 1334: 	    var oldpts = formname["oldpts"+id].value;
 1335: 	    gradeBox.value = oldpts;
 1336: 	    var radioButton = formname["RADVAL"+id];
 1337: 	    for (var i=0; i<radioButton.length; i++) {
 1338: 		radioButton[i].checked=false;
 1339: 		if (i == oldpts) {
 1340: 		    radioButton[i].checked=true;
 1341: 		}
 1342: 	    }
 1343: 	}
 1344: 	formname["stores"+id].value = "0";
 1345: 	updateSelect(formname,id);
 1346: 	return;
 1347:     }
 1348: 
 1349:     function clearRadBox(formname,id) {
 1350: 	if (checkSolved(formname,id) == 'noupdate') {
 1351: 	    updateSelect(formname,id);
 1352: 	    return;
 1353: 	}
 1354: 	gradeSelect = formname["GD_SEL"+id];
 1355: 	for (var i=0; i<gradeSelect.length; i++) {
 1356: 	    if (gradeSelect[i].selected) {
 1357: 		var selectx=i;
 1358: 	    }
 1359: 	}
 1360: 	var stores = formname["stores"+id];
 1361: 	if (selectx == stores.value) { return };
 1362: 	var gradeBox = formname["GD_BOX"+id];
 1363: 	gradeBox.value = "";
 1364: 	var radioButton = formname["RADVAL"+id];
 1365: 	for (var i=0; i<radioButton.length; i++) {
 1366: 	    radioButton[i].checked=false;
 1367: 	}
 1368: 	stores.value = selectx;
 1369:     }
 1370: 
 1371:     function checkSolved(formname,id) {
 1372: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1373: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1374: 	    if (!reply) {return "noupdate";}
 1375: 	    formname.overRideScore.value = 'yes';
 1376: 	}
 1377: 	return "update";
 1378:     }
 1379: 
 1380:     function updateSelect(formname,id) {
 1381: 	formname["GD_SEL"+id][0].selected = true;
 1382: 	return;
 1383:     }
 1384: 
 1385: //=========== Check that a point is assigned for all the parts  ============
 1386:     function checksubmit(formname,val,total,parttot) {
 1387: 	formname.gradeOpt.value = val;
 1388: 	if (val == "Save & Next") {
 1389: 	    for (i=0;i<=total;i++) {
 1390: 		for (j=0;j<parttot;j++) {
 1391: 		    var partid = formname["partid"+i+"_"+j].value;
 1392: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1393: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1394: 			if (points == "") {
 1395: 			    var name = formname["name"+i].value;
 1396: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1397: 			    var resp = confirm("You did not assign a score for "+studentID+
 1398: 					       ", part "+partid+". Continue?");
 1399: 			    if (resp == false) {
 1400: 				formname["GD_BOX"+i+"_"+partid].focus();
 1401: 				return false;
 1402: 			    }
 1403: 			}
 1404: 		    }
 1405: 		}
 1406: 	    }
 1407: 	}
 1408: 	formname.submit();
 1409:     }
 1410: 
 1411: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1412:     function checkSubmitPage(formname,total) {
 1413: 	noscore = new Array(100);
 1414: 	var ptr = 0;
 1415: 	for (i=1;i<total;i++) {
 1416: 	    var partid = formname["q_"+i].value;
 1417: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1418: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1419: 		var status = formname["solved"+i+"_"+partid].value;
 1420: 		if (points == "" && status != "correct_by_student") {
 1421: 		    noscore[ptr] = i;
 1422: 		    ptr++;
 1423: 		}
 1424: 	    }
 1425: 	}
 1426: 	if (ptr != 0) {
 1427: 	    var sense = ptr == 1 ? ": " : "s: ";
 1428: 	    var prolist = "";
 1429: 	    if (ptr == 1) {
 1430: 		prolist = noscore[0];
 1431: 	    } else {
 1432: 		var i = 0;
 1433: 		while (i < ptr-1) {
 1434: 		    prolist += noscore[i]+", ";
 1435: 		    i++;
 1436: 		}
 1437: 		prolist += "and "+noscore[i];
 1438: 	    }
 1439: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1440: 	    if (resp == false) {
 1441: 		return false;
 1442: 	    }
 1443: 	}
 1444: 
 1445: 	formname.submit();
 1446:     }
 1447: SUBJAVASCRIPT
 1448: }
 1449: 
 1450: #--- javascript for essay type problem --
 1451: sub sub_page_kw_js {
 1452:     my $request = shift;
 1453:     my $iconpath = $request->dir_config('lonIconsURL');
 1454:     &commonJSfunctions($request);
 1455: 
 1456:     my $inner_js_msg_central= (<<INNERJS);
 1457: <script type="text/javascript">
 1458:     function checkInput() {
 1459:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1460:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1461:       var usrctr = document.msgcenter.usrctr.value;
 1462:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1463:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1464: 
 1465:       var msgchk = "";
 1466:       if (document.msgcenter.subchk.checked) {
 1467:          msgchk = "msgsub,";
 1468:       }
 1469:       var includemsg = 0;
 1470:       for (var i=1; i<=nmsg; i++) {
 1471:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1472:           var frmmsg = document.msgcenter["msg"+i];
 1473:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1474:           var showflg = opener.document.SCORE["shownOnce"+i];
 1475:           showflg.value = "1";
 1476:           var chkbox = document.msgcenter["msgn"+i];
 1477:           if (chkbox.checked) {
 1478:              msgchk += "savemsg"+i+",";
 1479:              includemsg = 1;
 1480:           }
 1481:       }
 1482:       if (document.msgcenter.newmsgchk.checked) {
 1483:          msgchk += "newmsg"+usrctr;
 1484:          includemsg = 1;
 1485:       }
 1486:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1487:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1488:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1489:       includemsg.value = msgchk;
 1490: 
 1491:       self.close()
 1492: 
 1493:     }
 1494: </script>
 1495: INNERJS
 1496: 
 1497:     my $inner_js_highlight_central= (<<INNERJS);
 1498: <script type="text/javascript">
 1499:     function updateChoice(flag) {
 1500:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1501:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1502:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1503:       opener.document.SCORE.refresh.value = "on";
 1504:       if (opener.document.SCORE.keywords.value!=""){
 1505:          opener.document.SCORE.submit();
 1506:       }
 1507:       self.close()
 1508:     }
 1509: </script>
 1510: INNERJS
 1511: 
 1512:     my $start_page_msg_central = 
 1513:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1514: 				       {'js_ready'  => 1,
 1515: 					'only_body' => 1,
 1516: 					'bgcolor'   =>'#FFFFFF',});
 1517:     my $end_page_msg_central = 
 1518: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1519: 
 1520: 
 1521:     my $start_page_highlight_central = 
 1522:         &Apache::loncommon::start_page('Highlight Central',
 1523: 				       $inner_js_highlight_central,
 1524: 				       {'js_ready'  => 1,
 1525: 					'only_body' => 1,
 1526: 					'bgcolor'   =>'#FFFFFF',});
 1527:     my $end_page_highlight_central = 
 1528: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1529: 
 1530:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1531:     $docopen=~s/^document\.//;
 1532:     my %js_lt = &Apache::lonlocal::texthash(
 1533:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
 1534:                 plse => 'Please select a word or group of words from document and then click this link.',
 1535:                 adds => 'Add selection to keyword list? Edit if desired.',
 1536:                 col1 => 'red',
 1537:                 col2 => 'green',
 1538:                 col3 => 'blue',
 1539:                 siz1 => 'normal',
 1540:                 siz2 => '+1',
 1541:                 siz3 => '+2',
 1542:                 sty1 => 'normal',
 1543:                 sty2 => 'italic',
 1544:                 sty3 => 'bold',
 1545:              );
 1546:     my %html_js_lt = &Apache::lonlocal::texthash(
 1547:                 comp => 'Compose Message for: ',
 1548:                 incl => 'Include',
 1549:                 type => 'Type',
 1550:                 subj => 'Subject',
 1551:                 mesa => 'Message',
 1552:                 new  => 'New',
 1553:                 save => 'Save',
 1554:                 canc => 'Cancel',
 1555:                 kehi => 'Keyword Highlight Options',
 1556:                 txtc => 'Text Color',
 1557:                 font => 'Font Size',
 1558:                 fnst => 'Font Style',
 1559:              );
 1560:     &js_escape(\%js_lt);
 1561:     &html_escape(\%html_js_lt);
 1562:     &js_escape(\%html_js_lt);
 1563:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1564: 
 1565: //===================== Show list of keywords ====================
 1566:   function keywords(formname) {
 1567:     var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
 1568:     if (nret==null) return;
 1569:     formname.keywords.value = nret;
 1570: 
 1571:     if (formname.keywords.value != "") {
 1572: 	formname.refresh.value = "on";
 1573: 	formname.submit();
 1574:     }
 1575:     return;
 1576:   }
 1577: 
 1578: //===================== Script to view submitted by ==================
 1579:   function viewSubmitter(submitter) {
 1580:     document.SCORE.refresh.value = "on";
 1581:     document.SCORE.NCT.value = "1";
 1582:     document.SCORE.unamedom0.value = submitter;
 1583:     document.SCORE.submit();
 1584:     return;
 1585:   }
 1586: 
 1587: //===================== Script to add keyword(s) ==================
 1588:   function getSel() {
 1589:     if (document.getSelection) txt = document.getSelection();
 1590:     else if (document.selection) txt = document.selection.createRange().text;
 1591:     else return;
 1592:     if (typeof(txt) != 'string') {
 1593:         txt = String(txt);
 1594:     }
 1595:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1596:     if (cleantxt=="") {
 1597: 	alert("$js_lt{'plse'}");
 1598: 	return;
 1599:     }
 1600:     var nret = prompt("$js_lt{'adds'}",cleantxt);
 1601:     if (nret==null) return;
 1602:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1603:     if (document.SCORE.keywords.value != "") {
 1604: 	document.SCORE.refresh.value = "on";
 1605: 	document.SCORE.submit();
 1606:     }
 1607:     return;
 1608:   }
 1609: 
 1610: //====================== Script for composing message ==============
 1611:    // preload images
 1612:    img1 = new Image();
 1613:    img1.src = "$iconpath/mailbkgrd.gif";
 1614:    img2 = new Image();
 1615:    img2.src = "$iconpath/mailto.gif";
 1616: 
 1617:   function msgCenter(msgform,usrctr,fullname) {
 1618:     var Nmsg  = msgform.savemsgN.value;
 1619:     savedMsgHeader(Nmsg,usrctr,fullname);
 1620:     var subject = msgform.msgsub.value;
 1621:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1622:     re = /msgsub/;
 1623:     var shwsel = "";
 1624:     if (re.test(msgchk)) { shwsel = "checked" }
 1625:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1626:     displaySubject(checkEntities(subject),shwsel);
 1627:     for (var i=1; i<=Nmsg; i++) {
 1628: 	var testmsg = "savemsg"+i+",";
 1629: 	re = new RegExp(testmsg,"g");
 1630: 	shwsel = "";
 1631: 	if (re.test(msgchk)) { shwsel = "checked" }
 1632: 	var message = document.SCORE["savemsg"+i].value;
 1633: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1634: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1635: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1636:     }
 1637:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1638:     shwsel = "";
 1639:     re = /newmsg/;
 1640:     if (re.test(msgchk)) { shwsel = "checked" }
 1641:     newMsg(newmsg,shwsel);
 1642:     msgTail(); 
 1643:     return;
 1644:   }
 1645: 
 1646:   function checkEntities(strx) {
 1647:     if (strx.length == 0) return strx;
 1648:     var orgStr = ["&", "<", ">", '"']; 
 1649:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1650:     var counter = 0;
 1651:     while (counter < 4) {
 1652: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1653: 	counter++;
 1654:     }
 1655:     return strx;
 1656:   }
 1657: 
 1658:   function strReplace(strx, orgStr, newStr) {
 1659:     return strx.split(orgStr).join(newStr);
 1660:   }
 1661: 
 1662:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1663:     var height = 70*Nmsg+250;
 1664:     if (height > 600) {
 1665: 	height = 600;
 1666:     }
 1667:     var xpos = (screen.width-600)/2;
 1668:     xpos = (xpos < 0) ? '0' : xpos;
 1669:     var ypos = (screen.height-height)/2-30;
 1670:     ypos = (ypos < 0) ? '0' : ypos;
 1671: 
 1672:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
 1673:     pWin.focus();
 1674:     pDoc = pWin.document;
 1675:     pDoc.$docopen;
 1676:     pDoc.write('$start_page_msg_central');
 1677: 
 1678:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1679:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1680:     pDoc.write("<h1>&nbsp;$html_js_lt{'comp'}\"+fullname+\"<\\/h1>");
 1681: 
 1682:     pDoc.write('<table style="border:1px solid black;"><tr>');
 1683:     pDoc.write("<td><b>$html_js_lt{'incl'}<\\/b><\\/td><td><b>$html_js_lt{'type'}<\\/b><\\/td><td><b>$html_js_lt{'mesa'}<\\/td><\\/tr>");
 1684: }
 1685:     function displaySubject(msg,shwsel) {
 1686:     pDoc = pWin.document;
 1687:     pDoc.write("<tr>");
 1688:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1689:     pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
 1690:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1691: }
 1692: 
 1693:   function displaySavedMsg(ctr,msg,shwsel) {
 1694:     pDoc = pWin.document;
 1695:     pDoc.write("<tr>");
 1696:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1697:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1698:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1699: }
 1700: 
 1701:   function newMsg(newmsg,shwsel) {
 1702:     pDoc = pWin.document;
 1703:     pDoc.write("<tr>");
 1704:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1705:     pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
 1706:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1707: }
 1708: 
 1709:   function msgTail() {
 1710:     pDoc = pWin.document;
 1711:     //pDoc.write("<\\/table>");
 1712:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1713:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1714:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
 1715:     pDoc.write("<\\/form>");
 1716:     pDoc.write('$end_page_msg_central');
 1717:     pDoc.close();
 1718: }
 1719: 
 1720: //====================== Script for keyword highlight options ==============
 1721:   function kwhighlight() {
 1722:     var kwclr    = document.SCORE.kwclr.value;
 1723:     var kwsize   = document.SCORE.kwsize.value;
 1724:     var kwstyle  = document.SCORE.kwstyle.value;
 1725:     var redsel = "";
 1726:     var grnsel = "";
 1727:     var blusel = "";
 1728:     var txtcol1 = "$js_lt{'col1'}";
 1729:     var txtcol2 = "$js_lt{'col2'}";
 1730:     var txtcol3 = "$js_lt{'col3'}";
 1731:     var txtsiz1 = "$js_lt{'siz1'}";
 1732:     var txtsiz2 = "$js_lt{'siz2'}";
 1733:     var txtsiz3 = "$js_lt{'siz3'}";
 1734:     var txtsty1 = "$js_lt{'sty1'}";
 1735:     var txtsty2 = "$js_lt{'sty2'}";
 1736:     var txtsty3 = "$js_lt{'sty3'}";
 1737:     if (kwclr=="red")   {var redsel="checked='checked'"};
 1738:     if (kwclr=="green") {var grnsel="checked='checked'"};
 1739:     if (kwclr=="blue")  {var blusel="checked='checked'"};
 1740:     var sznsel = "";
 1741:     var sz1sel = "";
 1742:     var sz2sel = "";
 1743:     if (kwsize=="0")  {var sznsel="checked='checked'"};
 1744:     if (kwsize=="+1") {var sz1sel="checked='checked'"};
 1745:     if (kwsize=="+2") {var sz2sel="checked='checked'"};
 1746:     var synsel = "";
 1747:     var syisel = "";
 1748:     var sybsel = "";
 1749:     if (kwstyle=="")    {var synsel="checked='checked'"};
 1750:     if (kwstyle=="<i>") {var syisel="checked='checked'"};
 1751:     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
 1752:     highlightCentral();
 1753:     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
 1754:     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
 1755:     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
 1756:     highlightend();
 1757:     return;
 1758:   }
 1759: 
 1760:   function highlightCentral() {
 1761: //    if (window.hwdWin) window.hwdWin.close();
 1762:     var xpos = (screen.width-400)/2;
 1763:     xpos = (xpos < 0) ? '0' : xpos;
 1764:     var ypos = (screen.height-330)/2-30;
 1765:     ypos = (ypos < 0) ? '0' : ypos;
 1766: 
 1767:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1768:     hwdWin.focus();
 1769:     var hDoc = hwdWin.document;
 1770:     hDoc.$docopen;
 1771:     hDoc.write('$start_page_highlight_central');
 1772:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1773:     hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
 1774: 
 1775:     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
 1776:     hDoc.write("<th>$html_js_lt{'txtc'}<\\/th><th>$html_js_lt{'font'}<\\/th><th>$html_js_lt{'fnst'}<\\/th><\\/tr>");
 1777:   }
 1778: 
 1779:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1780:     var hDoc = hwdWin.document;
 1781:     hDoc.write("<tr>");
 1782:     hDoc.write("<td align=\\"left\\">");
 1783:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
 1784:     hDoc.write("<td align=\\"left\\">");
 1785:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
 1786:     hDoc.write("<td align=\\"left\\">");
 1787:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
 1788:     hDoc.write("<\\/tr>");
 1789:   }
 1790: 
 1791:   function highlightend() { 
 1792:     var hDoc = hwdWin.document;
 1793:     hDoc.write("<\\/table><br \\/>");
 1794:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
 1795:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
 1796:     hDoc.write("<\\/form>");
 1797:     hDoc.write('$end_page_highlight_central');
 1798:     hDoc.close();
 1799:   }
 1800: 
 1801: SUBJAVASCRIPT
 1802: }
 1803: 
 1804: sub get_increment {
 1805:     my $increment = $env{'form.increment'};
 1806:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1807:         $increment != .1) {
 1808:         $increment = 1;
 1809:     }
 1810:     return $increment;
 1811: }
 1812: 
 1813: sub gradeBox_start {
 1814:     return (
 1815:         &Apache::loncommon::start_data_table()
 1816:        .&Apache::loncommon::start_data_table_header_row()
 1817:        .'<th>'.&mt('Part').'</th>'
 1818:        .'<th>'.&mt('Points').'</th>'
 1819:        .'<th>&nbsp;</th>'
 1820:        .'<th>'.&mt('Assign Grade').'</th>'
 1821:        .'<th>'.&mt('Weight').'</th>'
 1822:        .'<th>'.&mt('Grade Status').'</th>'
 1823:        .&Apache::loncommon::end_data_table_header_row()
 1824:     );
 1825: }
 1826: 
 1827: sub gradeBox_end {
 1828:     return (
 1829:         &Apache::loncommon::end_data_table()
 1830:     );
 1831: }
 1832: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1833: sub gradeBox {
 1834:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1835:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1836: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1837:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1838:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1839:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1840:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1841:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1842: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1843:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1844:     my $display_part= &get_display_part($partid,$symb);
 1845:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1846: 				       [$partid]);
 1847:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1848:     if ($last_resets{$partid}) {
 1849:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1850:     }
 1851:     my $result=&Apache::loncommon::start_data_table_row();
 1852:     my $ctr = 0;
 1853:     my $thisweight = 0;
 1854:     my $increment = &get_increment();
 1855: 
 1856:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1857:     while ($thisweight<=$wgt) {
 1858: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1859:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1860: 	    $thisweight.')" value="'.$thisweight.'" '.
 1861: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1862: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1863:         $thisweight += $increment;
 1864: 	$ctr++;
 1865:     }
 1866:     $radio.='</tr></table>';
 1867: 
 1868:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1869: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1870: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1871: 	$wgt.')" /></td>'."\n";
 1872:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1873: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1874: 	' </td>'."\n";
 1875:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1876: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1877:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1878: 	$line.='<option></option>'.
 1879: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1880:     } else {
 1881: 	$line.='<option selected="selected"></option>'.
 1882: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1883:     }
 1884:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1885: 
 1886: 
 1887:     $result .= 
 1888: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 1889:     $result.=&Apache::loncommon::end_data_table_row();
 1890:     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
 1891:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1892: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1893: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1894: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1895:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1896:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1897:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1898:         $aggtries.'" />'."\n";
 1899:     my $res_error;
 1900:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 1901:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
 1902:     if ($res_error) {
 1903:         return &navmap_errormsg();
 1904:     }
 1905:     return $result;
 1906: }
 1907: 
 1908: sub handback_box {
 1909:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
 1910:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
 1911:     my (@respids);
 1912:     my @part_response_id = &flatten_responseType($responseType);
 1913:     foreach my $part_response_id (@part_response_id) {
 1914:     	my ($part,$resp) = @{ $part_response_id };
 1915:         if ($part eq $partid) {
 1916:             push(@respids,$resp);
 1917:         }
 1918:     }
 1919:     my $result;
 1920:     foreach my $respid (@respids) {
 1921: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1922: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1923: 	next if (!@$files);
 1924: 	my $file_counter = 0;
 1925: 	foreach my $file (@$files) {
 1926: 	    if ($file =~ /\/portfolio\//) {
 1927:                 $file_counter++;
 1928:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1929:     	        my ($name,$version,$ext) = &Apache::lonnet::file_name_version_ext($file_disp);
 1930:     	        $file_disp = "$name.$ext";
 1931:     	        $file = $file_path.$file_disp;
 1932:     	        $result.=&mt('Return commented version of [_1] to student.',
 1933:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1934:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1935:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
 1936: 	    }
 1937: 	}
 1938:         if ($file_counter) {
 1939:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
 1940:                        '<span class="LC_info">'.
 1941:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
 1942:         }
 1943:     }
 1944:     return $result;    
 1945: }
 1946: 
 1947: sub show_problem {
 1948:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1949:     my $rendered;
 1950:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1951:     &Apache::lonxml::remember_problem_counter();
 1952:     if ($mode eq 'both' or $mode eq 'text') {
 1953: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1954: 						       $env{'request.course.id'},
 1955: 						       undef,\%form);
 1956:     }
 1957:     if ($removeform) {
 1958: 	$rendered=~s|<form(.*?)>||g;
 1959: 	$rendered=~s|</form>||g;
 1960: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1961:     }
 1962:     my $companswer;
 1963:     if ($mode eq 'both' or $mode eq 'answer') {
 1964: 	&Apache::lonxml::restore_problem_counter();
 1965: 	$companswer=
 1966: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1967: 						    $env{'request.course.id'},
 1968: 						    %form);
 1969:     }
 1970:     if ($removeform) {
 1971: 	$companswer=~s|<form(.*?)>||g;
 1972: 	$companswer=~s|</form>||g;
 1973: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1974:     }
 1975:     my $renderheading = &mt('View of the problem');
 1976:     my $answerheading = &mt('Correct answer');
 1977:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 1978:         my $stu_fullname = $env{'form.fullname'};
 1979:         if ($stu_fullname eq '') {
 1980:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
 1981:         }
 1982:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
 1983:         if ($forwhom ne '') {
 1984:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
 1985:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
 1986:         }
 1987:     }
 1988:     $rendered=
 1989:         '<div class="LC_Box">'
 1990:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
 1991:        .$rendered
 1992:        .'</div>';
 1993:     $companswer=
 1994:         '<div class="LC_Box">'
 1995:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
 1996:        .$companswer
 1997:        .'</div>';
 1998:     my $result;
 1999:     if ($mode eq 'both') {
 2000:         $result=$rendered.$companswer;
 2001:     } elsif ($mode eq 'text') {
 2002:         $result=$rendered;
 2003:     } elsif ($mode eq 'answer') {
 2004:         $result=$companswer;
 2005:     }
 2006:     return $result;
 2007: }
 2008: 
 2009: sub files_exist {
 2010:     my ($r, $symb) = @_;
 2011:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 2012:     foreach my $student (@students) {
 2013:         my ($uname,$udom,$fullname) = split(/:/,$student);
 2014:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 2015: 					      $udom,$uname);
 2016:         my ($string,$timestamp)= &get_last_submission(\%record);
 2017:         foreach my $submission (@$string) {
 2018:             my ($partid,$respid) =
 2019: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2020:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 2021: 					   \%record);
 2022:             return 1 if (@$files);
 2023:         }
 2024:     }
 2025:     return 0;
 2026: }
 2027: 
 2028: sub download_all_link {
 2029:     my ($r,$symb) = @_;
 2030:     unless (&files_exist($r, $symb)) {
 2031:         $r->print(&mt('There are currently no submitted documents.'));
 2032:         return;
 2033:     }
 2034:     my $all_students = 
 2035: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 2036: 
 2037:     my $parts =
 2038: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 2039: 
 2040:     my $identifier = &Apache::loncommon::get_cgi_id();
 2041:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 2042:                              'cgi.'.$identifier.'.symb' => $symb,
 2043:                              'cgi.'.$identifier.'.parts' => $parts,});
 2044:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 2045: 	      &mt('Download All Submitted Documents').'</a>');
 2046:     return;
 2047: }
 2048: 
 2049: sub submit_download_link {
 2050:     my ($request,$symb) = @_;
 2051:     if (!$symb) { return ''; }
 2052: #FIXME: Figure out which type of problem this is and provide appropriate download
 2053:     my $res_error;
 2054:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
 2055:     if (ref($res_error)) {
 2056:         if ($$res_error) {
 2057:             $request->print(&mt('An error occurred retrieving response types'));
 2058:             return;
 2059:         }
 2060:     }
 2061:     my ($numupload,$numessay) = (0,0);
 2062:     if (ref($responseType) eq 'HASH') {
 2063:         foreach my $part (sort(keys(%$responseType))) {
 2064:             foreach my $id (sort(keys(%{ $responseType->{$part} }))) {
 2065:                 my $responsetype = $responseType->{$part}->{$id};
 2066:                 if ($responsetype eq 'essay') {
 2067:                     my $uploadedfiletypes =
 2068:                         &Apache::lonnet::EXT("resource.$part".'_'."$id.uploadedfiletypes",$symb);
 2069:                     if ($uploadedfiletypes) {
 2070:                         $numupload++;
 2071:                     } else {
 2072:                         $numessay++;
 2073:                     }
 2074:                 }
 2075:             }
 2076:         }
 2077:     }
 2078:     if (($numupload) || ($numessay)) {
 2079:         my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
 2080:         my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 2081:         my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
 2082:         (undef,undef,my $fullname) = &getclasslist($getsec,1,$getgroup,$symb,$submitonly,1);
 2083:         if (ref($fullname) eq 'HASH') {
 2084:             my @students = map { $_.':'.$fullname->{$_} } (keys(%{$fullname}));
 2085:             if (@students) {
 2086:                 @{$env{'form.stuinfo'}} = @students;
 2087:                 if ($numupload) {
 2088:                     &download_all_link($request,$symb);
 2089:                 }
 2090: # FIXME Need to provide a mechanism to download essays, i.e., if $numessay > 0
 2091: # Needs to omit user's identity if resource instance is for an anonymous survey.
 2092:             } else {
 2093:                 $request->print(&mt('No students match the criteria you selected'));
 2094:             }
 2095:         } else {
 2096:             $request->print(&mt('Could not retrieve student information'));
 2097:         }
 2098:     } else {
 2099:         $request->print(&mt('No essayresponse items found'));
 2100:     }
 2101:     return;
 2102: }
 2103: 
 2104: sub build_section_inputs {
 2105:     my $section_inputs;
 2106:     if ($env{'form.section'} eq '') {
 2107:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 2108:     } else {
 2109:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 2110:         foreach my $section (@sections) {
 2111:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 2112:         }
 2113:     }
 2114:     return $section_inputs;
 2115: }
 2116: 
 2117: # --------------------------- show submissions of a student, option to grade 
 2118: sub submission {
 2119:     my ($request,$counter,$total,$symb) = @_;
 2120:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 2121:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 2122:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2123:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 2124: 
 2125:     my $probtitle=&Apache::lonnet::gettitle($symb); 
 2126:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 2127:     my $is_tool = ($symb =~ /ext\.tool$/);
 2128:     my ($essayurl,%coursedesc_by_cid);
 2129: 
 2130:     if (!&canview($usec)) {
 2131:         $request->print(
 2132:             '<span class="LC_warning">'.
 2133:             &mt('Unable to view requested student.').
 2134:             ' '.&mt('([_1] in section [_2] in course id [_3])',
 2135:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
 2136:             '</span>');
 2137: 	return;
 2138:     }
 2139: 
 2140:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 2141:     unless ($is_tool) { 
 2142:         if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 2143:         if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 2144:     }
 2145:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 2146:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 2147: 	'" src="'.$request->dir_config('lonIconsURL').
 2148: 	'/check.gif" height="16" border="0" />';
 2149: 
 2150:     # header info
 2151:     if ($counter == 0) {
 2152: 	&sub_page_js($request);
 2153: 	&sub_page_kw_js($request);
 2154: 
 2155: 	# option to display problem, only once else it cause problems 
 2156:         # with the form later since the problem has a form.
 2157: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 2158: 	    my $mode;
 2159: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 2160: 		$mode='both';
 2161: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 2162: 		$mode='text';
 2163: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 2164: 		$mode='answer';
 2165: 	    }
 2166: 	    &Apache::lonxml::clear_problem_counter();
 2167: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 2168: 	}
 2169: 
 2170: 	# kwclr is the only variable that is guaranteed not to be blank 
 2171:         # if this subroutine has been called once.
 2172: 	my %keyhash = ();
 2173: #	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 2174:         if (1) {
 2175: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 2176: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 2177: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 2178: 
 2179: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2180: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 2181: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 2182: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 2183: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 2184: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 2185: 		$keyhash{$symb.'_subject'} : $probtitle;
 2186: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 2187: 	}
 2188: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 2189: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 2190: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 2191: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 2192: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 2193: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 2194: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 2195: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 2196: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 2197: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 2198: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 2199: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 2200: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 2201: 			&build_section_inputs().
 2202: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 2203: 			'<input type="hidden" name="NCT"'.
 2204: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 2205: #	if ($env{'form.handgrade'} eq 'yes') {
 2206:         if (1) {
 2207: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 2208: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 2209: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 2210: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 2211: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2212: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2213: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2214: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 2215: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 2216: 	    }
 2217: 	}
 2218: 	
 2219: 	my ($cts,$prnmsg) = (1,'');
 2220: 	while ($cts <= $env{'form.savemsgN'}) {
 2221: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2222: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2223: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2224: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2225: 		'" />'."\n".
 2226: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2227: 	    $cts++;
 2228: 	}
 2229: 	$request->print($prnmsg);
 2230: 
 2231: #	if ($env{'form.handgrade'} eq 'yes') {
 2232:         unless ($is_tool) {
 2233: 
 2234:             my %lt = &Apache::lonlocal::texthash(
 2235:                           keyh => 'Keyword Highlighting for Essays',
 2236:                           keyw => 'Keyword Options',
 2237:                           list => 'List',
 2238:                           past => 'Paste Selection to List',
 2239:                           high => 'Highlight Attribute',
 2240:                      );    
 2241: #
 2242: # Print out the keyword options line
 2243: #
 2244: 	    $request->print(
 2245:                 '<div class="LC_columnSection">'
 2246:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
 2247:                .&Apache::lonhtmlcommon::funclist_from_array(
 2248:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
 2249:                      '<a href="#" onmousedown="javascript:getSel(); return false"
 2250:  class="page">'.$lt{'past'}.'</a>',
 2251:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
 2252:                     {legend => $lt{'keyw'}})
 2253:                .'</fieldset></div>'
 2254:             );
 2255: 
 2256: #
 2257: # Load the other essays for similarity check
 2258: #
 2259:             (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2260:             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
 2261:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2262:                 my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2263:                 if ($cdom ne '' && $cnum ne '') {
 2264:                     my ($map,$id,$res) = &Apache::lonnet::decode_symb($symb);
 2265:                     if ($map =~ m{^\Quploaded/$cdom/$cnum/\E(default(?:|_\d+)\.(?:sequence|page))$}) {
 2266:                         my $apath = $1.'_'.$id;
 2267:                         $apath=~s/\W/\_/gs;
 2268:                         &init_old_essays($symb,$apath,$cdom,$cnum);
 2269:                     }
 2270:                 }
 2271:             } else {
 2272: 	        my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2273: 	        $apath=&escape($apath);
 2274: 	        $apath=~s/\W/\_/gs;
 2275:                 &init_old_essays($symb,$apath,$adom,$aname);
 2276:             }
 2277:         }
 2278:     }
 2279: 
 2280: # This is where output for one specific student would start
 2281:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2282:     $request->print(
 2283:         "\n\n"
 2284:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2285:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2286:        ."\n"
 2287:     );
 2288: 
 2289:     # Show additional functions if allowed
 2290:     if ($perm{'vgr'}) {
 2291:         $request->print(
 2292:             &Apache::loncommon::track_student_link(
 2293:                 'View recent activity',
 2294:                 $uname,$udom,'check')
 2295:            .' '
 2296:         );
 2297:     }
 2298:     if ($perm{'opa'}) {
 2299:         $request->print(
 2300:             &Apache::loncommon::pprmlink(
 2301:                 &mt('Set/Change parameters'),
 2302:                 $uname,$udom,$symb,'check'));
 2303:     }
 2304: 
 2305:     # Show Problem
 2306:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2307: 	my $mode;
 2308: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2309: 	    $mode='both';
 2310: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2311: 	    $mode='text';
 2312: 	} elsif ($env{'form.vAns'} eq 'all') {
 2313: 	    $mode='answer';
 2314: 	}
 2315: 	&Apache::lonxml::clear_problem_counter();
 2316: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2317:     }
 2318: 
 2319:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2320:     my $res_error;
 2321:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2322:     if ($res_error) {
 2323:         $request->print(&navmap_errormsg());
 2324:         return;
 2325:     }
 2326: 
 2327:     # Display student info
 2328:     $request->print(($counter == 0 ? '' : '<br />'));
 2329: 
 2330:     my $boxtitle = &mt('Submissions');
 2331:     if ($is_tool) {
 2332:         $boxtitle = &mt('Transactions')
 2333:     }
 2334:     my $result='<div class="LC_Box">'
 2335:               .'<h3 class="LC_hcell">'.$boxtitle.'</h3>';
 2336:     $result.='<input type="hidden" name="name'.$counter.
 2337:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2338: #    if ($env{'form.handgrade'} eq 'no') {
 2339:     unless ($is_tool) {
 2340:         $result.='<p class="LC_info">'
 2341:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2342:                 ."</p>\n";
 2343:     }
 2344: 
 2345:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2346:     my $fullname;
 2347:     my $col_fullnames = [];
 2348: #    if ($env{'form.handgrade'} eq 'yes') {
 2349:     unless ($is_tool) {
 2350: 	(my $sub_result,$fullname,$col_fullnames)=
 2351: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2352: 				 $counter);
 2353: 	$result.=$sub_result;
 2354:     }
 2355:     $request->print($result."\n");
 2356:     
 2357:     # print student answer/submission
 2358:     # Options are (1) Handgraded submission only
 2359:     #             (2) Last submission, includes submission that is not handgraded 
 2360:     #                  (for multi-response type part)
 2361:     #             (3) Last submission plus the parts info
 2362:     #             (4) The whole record for this student
 2363:     
 2364:     my ($string,$timestamp)= &get_last_submission(\%record,$is_tool);
 2365: 	
 2366:     my $lastsubonly;
 2367: 
 2368:     if ($$timestamp eq '') {
 2369:         $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2370:     } elsif ($is_tool) {
 2371:         $lastsubonly =
 2372:             '<div class="LC_grade_submissions_body">'
 2373:            .'<b>'.&mt('Date Grade Passed Back:').'</b> '.$$timestamp."</div>\n";
 2374:     } else {
 2375:         $lastsubonly =
 2376:             '<div class="LC_grade_submissions_body">'
 2377:            .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
 2378: 
 2379: 	my %seenparts;
 2380: 	my @part_response_id = &flatten_responseType($responseType);
 2381: 	foreach my $part (@part_response_id) {
 2382: 	    next if ($env{'form.lastSub'} eq 'hdgrade' 
 2383: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2384: 
 2385: 	    my ($partid,$respid) = @{ $part };
 2386: 	    my $display_part=&get_display_part($partid,$symb);
 2387: 	    if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2388: 		if (exists($seenparts{$partid})) { next; }
 2389: 		$seenparts{$partid}=1;
 2390:                 $request->print(
 2391:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2392:                     ' <b>'.&mt('Collaborative submission by: [_1]',
 2393:                                '<a href="javascript:viewSubmitter(\''.
 2394:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
 2395:                                '\');" target="_self">'.
 2396:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
 2397:                     '<br />');
 2398: 		next;
 2399: 		}
 2400: 	    my $responsetype = $responseType->{$partid}->{$respid};
 2401: 	    if (!exists($record{"resource.$partid.$respid.submission"})) {
 2402:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2403:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2404:                     ' <span class="LC_internal_info">'.
 2405:                     '('.&mt('Response ID: [_1]',$respid).')'.
 2406:                     '</span>&nbsp; &nbsp;'.
 2407: 	       	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2408: 		next;
 2409: 	    }
 2410: 	    foreach my $submission (@$string) {
 2411: 		my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2412: 		if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2413: 		my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
 2414: 		# Similarity check
 2415:                 my $similar='';
 2416:                 my ($type,$trial,$rndseed);
 2417:                 if ($hide eq 'rand') {
 2418:                     $type = 'randomizetry';
 2419:                     $trial = $record{"resource.$partid.tries"};
 2420:                     $rndseed = $record{"resource.$partid.rndseed"};
 2421:                 }
 2422: 	        if ($env{'form.checkPlag'}) {
 2423:     		    my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2424: 		        &most_similar($uname,$udom,$symb,$subval);
 2425: 		    if ($osim) {
 2426: 			$osim=int($osim*100.0);
 2427:                         if ($hide eq 'anon') {
 2428:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2429:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2430:                         } else {
 2431: 			    $similar='<hr />';
 2432:                             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
 2433:                                 $similar .= '<h3><span class="LC_warning">'.
 2434:                                             &mt('Essay is [_1]% similar to an essay by [_2]',
 2435:                                                 $osim,
 2436:                                                 &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
 2437:                                             '</span></h3>';
 2438:                             } else {
 2439:                                 my %old_course_desc;
 2440:                                 if ($ocrsid ne '') {
 2441:                                     if (ref($coursedesc_by_cid{$ocrsid}) eq 'HASH') {
 2442:                                         %old_course_desc = %{$coursedesc_by_cid{$ocrsid}};
 2443:                                     } else {
 2444:                                         my $args;
 2445:                                         if ($ocrsid ne $env{'request.course.id'}) {
 2446:                                             $args = {'one_time' => 1};
 2447:                                         }
 2448:                                         %old_course_desc =
 2449:                                             &Apache::lonnet::coursedescription($ocrsid,$args);
 2450:                                         $coursedesc_by_cid{$ocrsid} = \%old_course_desc;
 2451:                                     }
 2452:                                     $similar .=
 2453:                                         '<h3><span class="LC_warning">'.
 2454:                                         &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2455:                                             $osim,
 2456:                                             &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2457:                                             $old_course_desc{'description'},
 2458:                                             $old_course_desc{'num'},
 2459:                                             $old_course_desc{'domain'}).
 2460:                                         '</span></h3>';
 2461:                                 } else {
 2462:                                     $similar .=
 2463:                                         '<h3><span class="LC_warning">'.
 2464:                                         &mt('Essay is [_1]% similar to an essay by [_2] in an unknown course',
 2465:                                             $osim,
 2466:                                             &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
 2467:                                         '</span></h3>';
 2468:                                 }
 2469:                             }
 2470:                             $similar .= '<blockquote><i>'.
 2471:                                         &keywords_highlight($oessay).
 2472:                                         '</i></blockquote><hr />';
 2473:                         }
 2474: 	            }
 2475: 		}
 2476: 		my $order=&get_order($partid,$respid,$symb,$uname,$udom,
 2477:                                      undef,$type,$trial,$rndseed);
 2478:                 if ($env{'form.lastSub'} eq 'lastonly' || $env{'form.lastSub'} eq 'datesub' || $env{'form.lastSub'} =~ /^(last|all)$/ || ($env{'form.lastSub'} eq 'hdgrade' && 
 2479: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2480: 		    my $display_part=&get_display_part($partid,$symb);
 2481:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
 2482:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2483:                         ' <span class="LC_internal_info">'.
 2484:                         '('.&mt('Response ID: [_1]',$respid).')'.
 2485:                         '</span>&nbsp; &nbsp;';
 2486: 		    my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2487:                         
 2488: 		    if (@$files) {
 2489:                         if ($hide eq 'anon') {
 2490:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2491:                         } else {
 2492:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
 2493:                                         .'<br /><span class="LC_warning">';
 2494:                             if(@$files == 1) {
 2495:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
 2496:                             } else {
 2497:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
 2498:                             }
 2499:                             $lastsubonly .= '</span>';                         
 2500:                             foreach my $file (@$files) {
 2501:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2502:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
 2503:                             }
 2504:                         }
 2505: 			$lastsubonly.='<br />';
 2506:                     }
 2507:                     if ($hide eq 'anon') {
 2508:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
 2509:                     } else {
 2510:              	        $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
 2511:                         if ($draft) {
 2512:                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
 2513:                         }
 2514:                         $subval =
 2515: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
 2516: 					 $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
 2517:                         if ($responsetype eq 'essay') {
 2518:                             $subval =~ s{\n}{<br />}g;
 2519:                         }
 2520:                         $lastsubonly.=$subval."\n";
 2521:                     }
 2522: 	            if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2523: 		    $lastsubonly.='</div>';
 2524: 		}
 2525:             }
 2526: 	}
 2527: 	$lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2528:     }
 2529:     $request->print($lastsubonly);
 2530:     if ($env{'form.lastSub'} eq 'datesub') {
 2531:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2532: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2533:   
 2534:     } 
 2535:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2536:         my $identifier = (&canmodify($usec)? $counter : '');
 2537:         $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2538: 								 $env{'request.course.id'},
 2539: 								 $last,'.submission',
 2540: 								 'Apache::grades::keywords_highlight',
 2541:                                                                  $usec,$identifier));
 2542:     }
 2543:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2544: 	.$udom.'" />'."\n");
 2545:     # return if view submission with no grading option
 2546:     if (!&canmodify($usec)) {
 2547: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
 2548: 	return;
 2549:     } else {
 2550: 	$request->print('</div>'."\n");
 2551:     }
 2552: 
 2553:     # essay grading message center
 2554: #    if ($env{'form.handgrade'} eq 'yes') {
 2555:     if (1) {
 2556: 	my $result='<div class="LC_grade_message_center">';
 2557:     
 2558: 	$result.='<div class="LC_grade_message_center_header">'.
 2559: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2560: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2561: 	my $msgfor = $givenn.' '.$lastname;
 2562: 	if (scalar(@$col_fullnames) > 0) {
 2563: 	    my $lastone = pop(@$col_fullnames);
 2564: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2565: 	}
 2566: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2567: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2568: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2569: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2570: 	    ',\''.$msgfor.'\');" target="_self">'.
 2571: 	    &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
 2572: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2573: 	    ' <img src="'.$request->dir_config('lonIconsURL').
 2574: 	    '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
 2575: 	    '<br />&nbsp;('.
 2576: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2577: 	$result.='</div></div>';
 2578: 	$request->print($result);
 2579:     }
 2580: 
 2581:     my %seen = ();
 2582:     my @partlist;
 2583:     my @gradePartRespid;
 2584:     my @part_response_id;
 2585:     if ($is_tool) {
 2586:         @part_response_id = ([0,'']);
 2587:     } else {
 2588:         @part_response_id = &flatten_responseType($responseType);
 2589:     }
 2590:     $request->print(
 2591:         '<div class="LC_Box">'
 2592:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2593:     );
 2594:     $request->print(&gradeBox_start());
 2595:     foreach my $part_response_id (@part_response_id) {
 2596:     	my ($partid,$respid) = @{ $part_response_id };
 2597: 	my $part_resp = join('_',@{ $part_response_id });
 2598: 	next if ($seen{$partid} > 0);
 2599: 	$seen{$partid}++;
 2600: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2601: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2602: 	push(@partlist,$partid);
 2603: 	push(@gradePartRespid,$partid.'.'.$respid);
 2604: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2605:     }
 2606:     $request->print(&gradeBox_end()); # </div>
 2607:     $request->print('</div>');
 2608: 
 2609:     $request->print('<div class="LC_grade_info_links">');
 2610:     $request->print('</div>');
 2611: 
 2612:     $result='<input type="hidden" name="partlist'.$counter.
 2613: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2614:     $result.='<input type="hidden" name="gradePartRespid'.
 2615: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2616:     my $ctr = 0;
 2617:     while ($ctr < scalar(@partlist)) {
 2618: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2619: 	    $partlist[$ctr].'" />'."\n";
 2620: 	$ctr++;
 2621:     }
 2622:     $request->print($result.''."\n");
 2623: 
 2624: # Done with printing info for one student
 2625: 
 2626:     $request->print('</div>');#LC_grade_show_user
 2627: 
 2628: 
 2629:     # print end of form
 2630:     if ($counter == $total) {
 2631:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2632: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2633: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2634: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2635: 	my $ntstu ='<select name="NTSTU">'.
 2636: 	    '<option>1</option><option>2</option>'.
 2637: 	    '<option>3</option><option>5</option>'.
 2638: 	    '<option>7</option><option>10</option></select>'."\n";
 2639: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2640: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2641:         $endform.=&mt('[_1]student(s)',$ntstu);
 2642: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2643: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2644: 	    '<input type="button" value="'.&mt('Next').'" '.
 2645: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2646:         $endform.='<span class="LC_warning">'.
 2647:                   &mt('(Next and Previous (student) do not save the scores.)').
 2648:                   '</span>'."\n" ;
 2649:         $endform.="<input type='hidden' value='".&get_increment().
 2650:             "' name='increment' />";
 2651: 	$endform.='</td></tr></table></form>';
 2652: 	$request->print($endform);
 2653:     }
 2654:     return '';
 2655: }
 2656: 
 2657: sub check_collaborators {
 2658:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2659:     my ($result,@col_fullnames);
 2660:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2661:     foreach my $part (keys(%$handgrade)) {
 2662: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2663: 					'.maxcollaborators',
 2664: 					$symb,$udom,$uname);
 2665: 	next if ($ncol <= 0);
 2666: 	$part =~ s/\_/\./g;
 2667: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2668: 	my (@good_collaborators, @bad_collaborators);
 2669: 	foreach my $possible_collaborator
 2670: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2671: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2672: 	    next if ($possible_collaborator eq '');
 2673: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
 2674: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2675: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2676: 	    # Doing this grep allows 'fuzzy' specification
 2677: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2678: 			       keys(%$classlist));
 2679: 	    if (! scalar(@matches)) {
 2680: 		push(@bad_collaborators, $possible_collaborator);
 2681: 	    } else {
 2682: 		push(@good_collaborators, @matches);
 2683: 	    }
 2684: 	}
 2685: 	if (scalar(@good_collaborators) != 0) {
 2686: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
 2687: 	    foreach my $name (@good_collaborators) {
 2688: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2689: 		push(@col_fullnames, $givenn.' '.$lastname);
 2690: 		$result.='<li>'.$fullname->{$name}.'</li>';
 2691: 	    }
 2692: 	    $result.='</ol><br />'."\n";
 2693: 	    my ($part)=split(/\./,$part);
 2694: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2695: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2696: 		"\n";
 2697: 	}
 2698: 	if (scalar(@bad_collaborators) > 0) {
 2699: 	    $result.='<div class="LC_warning">';
 2700: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2701: 	    $result .= '</div>';
 2702: 	}         
 2703: 	if (scalar(@bad_collaborators > $ncol)) {
 2704: 	    $result .= '<div class="LC_warning">';
 2705: 	    $result .= &mt('This student has submitted too many '.
 2706: 		'collaborators.  Maximum is [_1].',$ncol);
 2707: 	    $result .= '</div>';
 2708: 	}
 2709:     }
 2710:     return ($result,$fullname,\@col_fullnames);
 2711: }
 2712: 
 2713: #--- Retrieve the last submission for all the parts
 2714: sub get_last_submission {
 2715:     my ($returnhash,$is_tool)=@_;
 2716:     my (@string,$timestamp,%lasthidden);
 2717:     if ($$returnhash{'version'}) {
 2718: 	my %lasthash=();
 2719: 	my ($version);
 2720: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2721: 	    foreach my $key (sort(split(/\:/,
 2722: 					$$returnhash{$version.':keys'}))) {
 2723: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2724: 		$timestamp = 
 2725: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2726: 	    }
 2727: 	}
 2728:         my (%typeparts,%randombytry);
 2729:         my $showsurv = 
 2730:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2731:         foreach my $key (sort(keys(%lasthash))) {
 2732:             if ($key =~ /\.type$/) {
 2733:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2734:                     ($lasthash{$key} eq 'anonsurveycred') ||
 2735:                     ($lasthash{$key} eq 'randomizetry')) {
 2736:                     my ($ign,@parts) = split(/\./,$key);
 2737:                     pop(@parts);
 2738:                     my $id = join('.',@parts);
 2739:                     if ($lasthash{$key} eq 'randomizetry') {
 2740:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
 2741:                     } else {
 2742:                         unless ($showsurv) {
 2743:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2744:                         }
 2745:                     }
 2746:                     delete($lasthash{$key});
 2747:                 }
 2748:             }
 2749:         }
 2750:         my @hidden = keys(%typeparts);
 2751:         my @randomize = keys(%randombytry);
 2752: 	foreach my $key (keys(%lasthash)) {
 2753: 	    next if ($key !~ /\.submission$/);
 2754:             my $hide;
 2755:             if (@hidden) {
 2756:                 foreach my $id (@hidden) {
 2757:                     if ($key =~ /^\Q$id\E/) {
 2758:                         $hide = 'anon';
 2759:                         last;
 2760:                     }
 2761:                 }
 2762:             }
 2763:             unless ($hide) {
 2764:                 if (@randomize) {
 2765:                     foreach my $id (@randomize) {
 2766:                         if ($key =~ /^\Q$id\E/) {
 2767:                             $hide = 'rand';
 2768:                             last;
 2769:                         }
 2770:                     }
 2771:                 }
 2772:             }
 2773: 	    my ($partid,$foo) = split(/submission$/,$key);
 2774: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
 2775:             push(@string, join(':', $key, $hide, $draft, (
 2776:                 ref($lasthash{$key}) eq 'ARRAY' ?
 2777:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
 2778: 	}
 2779:     }
 2780:     if (!@string) {
 2781:         my $msg;
 2782:         if ($is_tool) {
 2783:             $msg = &mt('No grade passed back.');
 2784:         } else {
 2785:             $msg = &mt('Nothing submitted - no attempts.');
 2786:         }
 2787: 	$string[0] =
 2788: 	    '<span class="LC_warning">'.$msg.'</span>';
 2789:     }
 2790:     return (\@string,\$timestamp);
 2791: }
 2792: 
 2793: #--- High light keywords, with style choosen by user.
 2794: sub keywords_highlight {
 2795:     my $string    = shift;
 2796:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2797:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2798:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2799:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2800:     foreach my $keyword (@keylist) {
 2801: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2802:     }
 2803:     return $string;
 2804: }
 2805: 
 2806: # For Tasks provide a mechanism to display previous version for one specific student
 2807: 
 2808: sub show_previous_task_version {
 2809:     my ($request,$symb) = @_;
 2810:     if ($symb eq '') {
 2811:         $request->print(
 2812:             '<span class="LC_error">'.
 2813:             &mt('Unable to handle ambiguous references.').
 2814:             '</span>');
 2815:         return '';
 2816:     }
 2817:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
 2818:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2819:     if (!&canview($usec)) {
 2820:         $request->print(
 2821:             '<span class="LC_warning">'.
 2822:             &mt('Unable to view previous version for requested student.').
 2823:             ' '.&mt('([_1] in section [_2] in course id [_3])',
 2824:                     $uname.':'.$udom,$usec,$env{'request.course.id'}).
 2825:             '</span>');
 2826:         return;
 2827:     }
 2828:     my $mode = 'both';
 2829:     my $isTask = ($symb =~/\.task$/);
 2830:     if ($isTask) {
 2831:         if ($env{'form.previousversion'} =~ /^\d+$/) {
 2832:             if ($env{'form.fullname'} eq '') {
 2833:                 $env{'form.fullname'} =
 2834:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
 2835:             }
 2836:             my $probtitle=&Apache::lonnet::gettitle($symb);
 2837:             $request->print("\n\n".
 2838:                             '<div class="LC_grade_show_user">'.
 2839:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 2840:                             '</h2>'."\n");
 2841:             &Apache::lonxml::clear_problem_counter();
 2842:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
 2843:                             {'previousversion' => $env{'form.previousversion'} }));
 2844:             $request->print("\n</div>");
 2845:         }
 2846:     }
 2847:     return;
 2848: }
 2849: 
 2850: sub choose_task_version_form {
 2851:     my ($symb,$uname,$udom,$nomenu) = @_;
 2852:     my $isTask = ($symb =~/\.task$/);
 2853:     my ($current,$version,$result,$js,$displayed,$rowtitle);
 2854:     if ($isTask) {
 2855:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 2856:                                               $udom,$uname);
 2857:         if (($record{'resource.0.version'} eq '') ||
 2858:             ($record{'resource.0.version'} < 2)) {
 2859:             return ($record{'resource.0.version'},
 2860:                     $record{'resource.0.version'},$result,$js);
 2861:         } else {
 2862:             $current = $record{'resource.0.version'};
 2863:         }
 2864:         if ($env{'form.previousversion'}) {
 2865:             $displayed = $env{'form.previousversion'};
 2866:             $rowtitle = &mt('Choose another version:')
 2867:         } else {
 2868:             $displayed = $current;
 2869:             $rowtitle = &mt('Show earlier version:');
 2870:         }
 2871:         $result = '<div class="LC_left_float">';
 2872:         my $list;
 2873:         my $numversions = 0;
 2874:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
 2875:             if ($i == $current) {
 2876:                 if (!$env{'form.previousversion'} || $nomenu) {
 2877:                     next;
 2878:                 } else {
 2879:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
 2880:                     $numversions ++;
 2881:                 }
 2882:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
 2883:                 unless ($i == $env{'form.previousversion'}) {
 2884:                     $numversions ++;
 2885:                 }
 2886:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
 2887:             }
 2888:         }
 2889:         if ($numversions) {
 2890:             $symb = &HTML::Entities::encode($symb,'<>"&');
 2891:             $result .=
 2892:                 '<form name="getprev" method="post" action=""'.
 2893:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
 2894:                 &Apache::loncommon::start_data_table().
 2895:                 &Apache::loncommon::start_data_table_row().
 2896:                 '<th align="left">'.$rowtitle.'</th>'.
 2897:                 '<td><select name="version">'.
 2898:                 '<option>'.&mt('Select').'</option>'.
 2899:                 $list.
 2900:                 '</select></td>'.
 2901:                 &Apache::loncommon::end_data_table_row();
 2902:             unless ($nomenu) {
 2903:                 $result .= &Apache::loncommon::start_data_table_row().
 2904:                 '<th align="left">'.&mt('Open in new window').'</th>'.
 2905:                 '<td><span class="LC_nobreak">'.
 2906:                 '<label><input type="radio" name="prevwin" value="1" />'.
 2907:                 &mt('Yes').'</label>'.
 2908:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
 2909:                 '</span></td>'.
 2910:                 &Apache::loncommon::end_data_table_row();
 2911:             }
 2912:             $result .=
 2913:                 &Apache::loncommon::start_data_table_row().
 2914:                 '<th align="left">&nbsp;</th>'.
 2915:                 '<td>'.
 2916:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
 2917:                 '</td>'.
 2918:                 &Apache::loncommon::end_data_table_row().
 2919:                 &Apache::loncommon::end_data_table().
 2920:                 '</form>';
 2921:             $js = &previous_display_javascript($nomenu,$current);
 2922:         } elsif ($displayed && $nomenu) {
 2923:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
 2924:         } else {
 2925:             $result .= &mt('No previous versions to show for this student');
 2926:         }
 2927:         $result .= '</div>';
 2928:     }
 2929:     return ($current,$displayed,$result,$js);
 2930: }
 2931: 
 2932: sub previous_display_javascript {
 2933:     my ($nomenu,$current) = @_;
 2934:     my $js = <<"JSONE";
 2935: <script type="text/javascript">
 2936: // <![CDATA[
 2937: function previousVersion(uname,udom,symb) {
 2938:     var current = '$current';
 2939:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
 2940:     var prevstr = new RegExp("^\\\\d+\$");
 2941:     if (!prevstr.test(version)) {
 2942:         return false;
 2943:     }
 2944:     var url = '';
 2945:     if (version == current) {
 2946:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
 2947:     } else {
 2948:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
 2949:     }
 2950: JSONE
 2951:     if ($nomenu) {
 2952:         $js .= <<"JSTWO";
 2953:     document.location.href = url;
 2954: JSTWO
 2955:     } else {
 2956:         $js .= <<"JSTHREE";
 2957:     var newwin = 0;
 2958:     for (var i=0; i<document.getprev.prevwin.length; i++) {
 2959:         if (document.getprev.prevwin[i].checked == true) {
 2960:             newwin = document.getprev.prevwin[i].value;
 2961:         }
 2962:     }
 2963:     if (newwin == 1) {
 2964:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
 2965:         url = url+'&inhibitmenu=yes';
 2966:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
 2967:             previousWin = window.open(url,'',options,1);
 2968:         } else {
 2969:             previousWin.location.href = url;
 2970:         }
 2971:         previousWin.focus();
 2972:         return false;
 2973:     } else {
 2974:         document.location.href = url;
 2975:         return false;
 2976:     }
 2977: JSTHREE
 2978:     }
 2979:     $js .= <<"ENDJS";
 2980:     return false;
 2981: }
 2982: // ]]>
 2983: </script>
 2984: ENDJS
 2985: 
 2986: }
 2987: 
 2988: #--- Called from submission routine
 2989: sub processHandGrade {
 2990:     my ($request,$symb) = @_;
 2991:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2992:     my $button = $env{'form.gradeOpt'};
 2993:     my $ngrade = $env{'form.NCT'};
 2994:     my $ntstu  = $env{'form.NTSTU'};
 2995:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2996:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2997: 
 2998:     if ($button eq 'Save & Next') {
 2999: 	my $ctr = 0;
 3000: 	while ($ctr < $ngrade) {
 3001: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 3002: 	    my ($errorflag,$pts,$wgt,$numhidden) = 
 3003:                 &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 3004: 	    if ($errorflag eq 'no_score') {
 3005: 		$ctr++;
 3006: 		next;
 3007: 	    }
 3008: 	    if ($errorflag eq 'not_allowed') {
 3009: 		$request->print(
 3010:                     '<span class="LC_error">'
 3011:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
 3012:                    .'</span>');
 3013: 		$ctr++;
 3014: 		next;
 3015: 	    }
 3016:             if ($numhidden) {
 3017:                 $request->print(
 3018:                     '<span class="LC_info">'
 3019:                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
 3020:                    .'</span><br />');
 3021:             }
 3022: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 3023: 	    my ($subject,$message,$msgstatus) = ('','','');
 3024: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 3025:             my ($feedurl,$showsymb) =
 3026: 		&get_feedurl_and_symb($symb,$uname,$udom);
 3027: 	    my $messagetail;
 3028: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 3029: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 3030: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 3031: 		$subject.=' ['.$restitle.']';
 3032: 		my (@msgnum) = split(/,/,$includemsg);
 3033: 		foreach (@msgnum) {
 3034: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 3035: 		}
 3036: 		$message =&Apache::lonfeedback::clear_out_html($message);
 3037: 		if ($env{'form.withgrades'.$ctr}) {
 3038: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 3039: 		    $messagetail = " for <a href=\"".
 3040: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
 3041: 		}
 3042: 		$msgstatus = 
 3043:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 3044: 						     $message.$messagetail,
 3045:                                                      undef,$feedurl,undef,
 3046:                                                      undef,undef,$showsymb,
 3047:                                                      $restitle);
 3048: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 3049: 				$msgstatus.'<br />');
 3050: 	    }
 3051: 	    if ($env{'form.collaborator'.$ctr}) {
 3052: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 3053: 		foreach my $collabstr (@collabstrs) {
 3054: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 3055: 		    foreach my $collaborator (@collaborators) {
 3056: 			my ($errorflag,$pts,$wgt) = 
 3057: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 3058: 					   $env{'form.unamedom'.$ctr},$part);
 3059: 			if ($errorflag eq 'not_allowed') {
 3060: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 3061: 			    next;
 3062: 			} elsif ($message ne '') {
 3063: 			    my ($baseurl,$showsymb) = 
 3064: 				&get_feedurl_and_symb($symb,$collaborator,
 3065: 						      $udom);
 3066: 			    if ($env{'form.withgrades'.$ctr}) {
 3067: 				$messagetail = " for <a href=\"".
 3068:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
 3069: 			    }
 3070: 			    $msgstatus = 
 3071: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 3072: 			}
 3073: 		    }
 3074: 		}
 3075: 	    }
 3076: 	    $ctr++;
 3077: 	}
 3078:     }
 3079: 
 3080: #    if ($env{'form.handgrade'} eq 'yes') {
 3081:     if (1) {
 3082: 	# Keywords sorted in alphabatical order
 3083: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 3084: 	my %keyhash = ();
 3085: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 3086: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 3087: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 3088: 	$env{'form.keywords'} = join(' ',@keywords);
 3089: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 3090: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 3091: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 3092: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 3093: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 3094: 
 3095: 	# message center - Order of message gets changed. Blank line is eliminated.
 3096: 	# New messages are saved in env for the next student.
 3097: 	# All messages are saved in nohist_handgrade.db
 3098: 	my ($ctr,$idx) = (1,1);
 3099: 	while ($ctr <= $env{'form.savemsgN'}) {
 3100: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 3101: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 3102: 		$idx++;
 3103: 	    }
 3104: 	    $ctr++;
 3105: 	}
 3106: 	$ctr = 0;
 3107: 	while ($ctr < $ngrade) {
 3108: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 3109: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 3110: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 3111: 		$idx++;
 3112: 	    }
 3113: 	    $ctr++;
 3114: 	}
 3115: 	$env{'form.savemsgN'} = --$idx;
 3116: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 3117: 	my $putresult = &Apache::lonnet::put
 3118: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 3119:     }
 3120:     # Called by Save & Refresh from Highlight Attribute Window
 3121:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3122:     if ($env{'form.refresh'} eq 'on') {
 3123: 	my ($ctr,$total) = (0,0);
 3124: 	while ($ctr < $ngrade) {
 3125: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 3126: 	    $ctr++;
 3127: 	}
 3128: 	$env{'form.NTSTU'}=$ngrade;
 3129: 	$ctr = 0;
 3130: 	while ($ctr < $total) {
 3131: 	    my $processUser = $env{'form.unamedom'.$ctr};
 3132: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 3133: 	    $env{'form.fullname'} = $$fullname{$processUser};
 3134: 	    &submission($request,$ctr,$total-1,$symb);
 3135: 	    $ctr++;
 3136: 	}
 3137: 	return '';
 3138:     }
 3139: 
 3140:     # Get the next/previous one or group of students
 3141:     my $firststu = $env{'form.unamedom0'};
 3142:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 3143:     my $ctr = 2;
 3144:     while ($laststu eq '') {
 3145: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 3146: 	$ctr++;
 3147: 	$laststu = $firststu if ($ctr > $ngrade);
 3148:     }
 3149: 
 3150:     my (@parsedlist,@nextlist);
 3151:     my ($nextflg) = 0;
 3152:     foreach my $item (sort 
 3153: 	     {
 3154: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3155: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3156: 		 }
 3157: 		 return $a cmp $b;
 3158: 	     } (keys(%$fullname))) {
 3159: # FIXME: this is fishy, looks like the button label
 3160: 	if ($nextflg == 1 && $button =~ /Next$/) {
 3161: 	    push(@parsedlist,$item);
 3162: 	}
 3163: 	$nextflg = 1 if ($item eq $laststu);
 3164: 	if ($button eq 'Previous') {
 3165: 	    last if ($item eq $firststu);
 3166: 	    push(@parsedlist,$item);
 3167: 	}
 3168:     }
 3169:     $ctr = 0;
 3170: # FIXME: this is fishy, looks like the button label
 3171:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 3172:     my $res_error;
 3173:     my ($partlist) = &response_type($symb,\$res_error);
 3174:     if ($res_error) {
 3175:         $request->print(&navmap_errormsg());
 3176:         return;
 3177:     }
 3178:     foreach my $student (@parsedlist) {
 3179: 	my $submitonly=$env{'form.submitonly'};
 3180: 	my ($uname,$udom) = split(/:/,$student);
 3181: 	
 3182: 	if ($submitonly eq 'queued') {
 3183: 	    my %queue_status = 
 3184: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 3185: 							$udom,$uname);
 3186: 	    next if (!defined($queue_status{'gradingqueue'}));
 3187: 	}
 3188: 
 3189: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 3190: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 3191: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 3192: 	    my $submitted = 0;
 3193: 	    my $ungraded = 0;
 3194: 	    my $incorrect = 0;
 3195: 	    foreach my $item (keys(%status)) {
 3196: 		$submitted = 1 if ($status{$item} ne 'nothing');
 3197: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 3198: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 3199: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 3200: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 3201: 		    $submitted = 0;
 3202: 		}
 3203: 	    }
 3204: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 3205: 				     $submitonly eq 'incorrect' ||
 3206: 				     $submitonly eq 'graded'));
 3207: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 3208: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 3209: 	}
 3210: 	push(@nextlist,$student) if ($ctr < $ntstu);
 3211: 	last if ($ctr == $ntstu);
 3212: 	$ctr++;
 3213:     }
 3214: 
 3215:     $ctr = 0;
 3216:     my $total = scalar(@nextlist)-1;
 3217: 
 3218:     foreach (sort(@nextlist)) {
 3219: 	my ($uname,$udom,$submitter) = split(/:/);
 3220: 	$env{'form.student'}  = $uname;
 3221: 	$env{'form.userdom'}  = $udom;
 3222: 	$env{'form.fullname'} = $$fullname{$_};
 3223: 	&submission($request,$ctr,$total,$symb);
 3224: 	$ctr++;
 3225:     }
 3226:     if ($total < 0) {
 3227: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
 3228: 	$request->print($the_end);
 3229:     }
 3230:     return '';
 3231: }
 3232: 
 3233: #---- Save the score and award for each student, if changed
 3234: sub saveHandGrade {
 3235:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 3236:     my @version_parts;
 3237:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 3238: 					   $env{'request.course.id'});
 3239:     if (!&canmodify($usec)) { return('not_allowed'); }
 3240:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 3241:     my @parts_graded;
 3242:     my %newrecord  = ();
 3243:     my ($pts,$wgt,$totchg) = ('','',0);
 3244:     my %aggregate = ();
 3245:     my $aggregateflag = 0;
 3246:     if ($env{'form.HIDE'.$newflg}) {
 3247:         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
 3248:         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
 3249:         $totchg += $numchgs;
 3250:     }
 3251:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 3252:     foreach my $new_part (@parts) {
 3253: 	#collaborator ($submi may vary for different parts
 3254: 	if ($submitter && $new_part ne $part) { next; }
 3255: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 3256: 	if ($dropMenu eq 'excused') {
 3257: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 3258: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 3259: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 3260: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 3261: 		}
 3262: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3263: 	    }
 3264: 	} elsif ($dropMenu eq 'reset status'
 3265: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 3266: 	    foreach my $key (keys(%record)) {
 3267: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 3268: 	    }
 3269: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3270: 		"$env{'user.name'}:$env{'user.domain'}";
 3271:             my $totaltries = $record{'resource.'.$part.'.tries'};
 3272: 
 3273:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 3274: 					       [$new_part]);
 3275:             my $aggtries =$totaltries;
 3276:             if ($last_resets{$new_part}) {
 3277:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 3278: 					   $new_part);
 3279:             }
 3280: 
 3281:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 3282:             if ($aggtries > 0) {
 3283:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3284:                 $aggregateflag = 1;
 3285:             }
 3286: 	} elsif ($dropMenu eq '') {
 3287: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 3288: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 3289: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 3290: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 3291: 		next;
 3292: 	    }
 3293: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 3294: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 3295: 	    my $partial= $pts/$wgt;
 3296: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 3297: 		#do not update score for part if not changed.
 3298:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 3299: 		next;
 3300: 	    } else {
 3301: 	        push(@parts_graded,$new_part);
 3302: 	    }
 3303: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 3304: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 3305: 	    }
 3306: 	    my $reckey = 'resource.'.$new_part.'.solved';
 3307: 	    if ($partial == 0) {
 3308: 		if ($record{$reckey} ne 'incorrect_by_override') {
 3309: 		    $newrecord{$reckey} = 'incorrect_by_override';
 3310: 		}
 3311: 	    } else {
 3312: 		if ($record{$reckey} ne 'correct_by_override') {
 3313: 		    $newrecord{$reckey} = 'correct_by_override';
 3314: 		}
 3315: 	    }	    
 3316: 	    if ($submitter && 
 3317: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 3318: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 3319: 	    }
 3320: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3321: 		"$env{'user.name'}:$env{'user.domain'}";
 3322: 	}
 3323: 	# unless problem has been graded, set flag to version the submitted files
 3324: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 3325: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 3326: 	        $dropMenu eq 'reset status')
 3327: 	   {
 3328: 	    push(@version_parts,$new_part);
 3329: 	}
 3330:     }
 3331:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3332:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3333: 
 3334:     if (%newrecord) {
 3335:         if (@version_parts) {
 3336:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 3337:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 3338: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 3339: 	    foreach my $new_part (@version_parts) {
 3340: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 3341: 				$new_part,\%newrecord);
 3342: 	    }
 3343:         }
 3344: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 3345: 				$env{'request.course.id'},$domain,$stuname);
 3346: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 3347: 				     $cdom,$cnum,$domain,$stuname);
 3348:     }
 3349:     if ($aggregateflag) {
 3350:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3351: 			      $cdom,$cnum);
 3352:     }
 3353:     return ('',$pts,$wgt,$totchg);
 3354: }
 3355: 
 3356: sub makehidden {
 3357:     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
 3358:     return unless (ref($record) eq 'HASH');
 3359:     my %modified;
 3360:     my $numchanged = 0;
 3361:     if (exists($record->{$version.':keys'})) {
 3362:         my $partsregexp = $parts;
 3363:         $partsregexp =~ s/,/|/g;
 3364:         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
 3365:             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
 3366:                  my $item = $1;
 3367:                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
 3368:                      $modified{$key} = $record->{$version.':'.$key};
 3369:                  }
 3370:             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
 3371:                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
 3372:             } elsif ($key =~ /^(ip|timestamp|host)$/) {
 3373:                 $modified{$key} = $record->{$version.':'.$key};
 3374:             }
 3375:         }
 3376:         if (keys(%modified)) {
 3377:             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
 3378:                                           $domain,$stuname,$tolog) eq 'ok') {
 3379:                 $numchanged ++;
 3380:             }
 3381:         }
 3382:     }
 3383:     return $numchanged;
 3384: }
 3385: 
 3386: sub check_and_remove_from_queue {
 3387:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 3388:     my @ungraded_parts;
 3389:     foreach my $part (@{$parts}) {
 3390: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 3391: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 3392: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 3393: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 3394: 		) {
 3395: 	    push(@ungraded_parts, $part);
 3396: 	}
 3397:     }
 3398:     if ( !@ungraded_parts ) {
 3399: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 3400: 					       $cnum,$domain,$stuname);
 3401:     }
 3402: }
 3403: 
 3404: sub handback_files {
 3405:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 3406:     my $portfolio_root = '/userfiles/portfolio';
 3407:     my $res_error;
 3408:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3409:     if ($res_error) {
 3410:         $request->print('<br />'.&navmap_errormsg().'<br />');
 3411:         return;
 3412:     }
 3413:     my @handedback;
 3414:     my $file_msg;
 3415:     my @part_response_id = &flatten_responseType($responseType);
 3416:     foreach my $part_response_id (@part_response_id) {
 3417:     	my ($part_id,$resp_id) = @{ $part_response_id };
 3418: 	my $part_resp = join('_',@{ $part_response_id });
 3419:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
 3420:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
 3421:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
 3422:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
 3423:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
 3424:                     my ($directory,$answer_file) = 
 3425:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
 3426:                     my ($answer_name,$answer_ver,$answer_ext) =
 3427: 		        &Apache::lonnet::file_name_version_ext($answer_file);
 3428: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 3429:                     my $getpropath = 1;
 3430:                     my ($dir_list,$listerror) = 
 3431:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
 3432:                                                  $domain,$stuname,$getpropath);
 3433: 		    my $version = &Apache::lonnet::get_next_version($answer_name,$answer_ext,$dir_list);
 3434:                     # fix filename
 3435:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 3436:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 3437:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
 3438:             	                                $save_file_name);
 3439:                     if ($result !~ m|^/uploaded/|) {
 3440:                         $request->print('<br /><span class="LC_error">'.
 3441:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 3442:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
 3443:                                         '</span>');
 3444:                     } else {
 3445:                         # mark the file as read only
 3446:                         push(@handedback,$save_file_name);
 3447: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 3448: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 3449: 			}
 3450:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 3451: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
 3452:                     }
 3453:                     $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>'));
 3454:                 }
 3455:             }
 3456:         }
 3457:     }
 3458:     if (@handedback > 0) {
 3459:         $request->print('<br />');
 3460:         my @what = ($symb,$env{'request.course.id'},'handback');
 3461:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
 3462:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
 3463:         my ($subject,$message);
 3464:         if (scalar(@handedback) == 1) {
 3465:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
 3466:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
 3467:         } else {
 3468:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
 3469:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
 3470:         }
 3471:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
 3472:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
 3473:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
 3474:         my ($feedurl,$showsymb) =
 3475:             &get_feedurl_and_symb($symb,$domain,$stuname);
 3476:         my $restitle = &Apache::lonnet::gettitle($symb);
 3477:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
 3478:         my $msgstatus =
 3479:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
 3480:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
 3481:                  $restitle);
 3482:         if ($msgstatus) {
 3483:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
 3484:         }
 3485:     }
 3486:     return;
 3487: }
 3488: 
 3489: sub get_feedurl_and_symb {
 3490:     my ($symb,$uname,$udom) = @_;
 3491:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3492:     $url = &Apache::lonnet::clutter($url);
 3493:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 3494: 					$symb,$udom,$uname);
 3495:     if ($encrypturl =~ /^yes$/i) {
 3496: 	&Apache::lonenc::encrypted(\$url,1);
 3497: 	&Apache::lonenc::encrypted(\$symb,1);
 3498:     }
 3499:     return ($url,$symb);
 3500: }
 3501: 
 3502: sub get_submitted_files {
 3503:     my ($udom,$uname,$partid,$respid,$record) = @_;
 3504:     my @files;
 3505:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 3506:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 3507:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 3508:     	    push(@files,$file_url.$file);
 3509:         }
 3510:     }
 3511:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 3512:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 3513:     }
 3514:     return (\@files);
 3515: }
 3516: 
 3517: # ----------- Provides number of tries since last reset.
 3518: sub get_num_tries {
 3519:     my ($record,$last_reset,$part) = @_;
 3520:     my $timestamp = '';
 3521:     my $num_tries = 0;
 3522:     if ($$record{'version'}) {
 3523:         for (my $version=$$record{'version'};$version>=1;$version--) {
 3524:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 3525:                 $timestamp = $$record{$version.':timestamp'};
 3526:                 if ($timestamp > $last_reset) {
 3527:                     $num_tries ++;
 3528:                 } else {
 3529:                     last;
 3530:                 }
 3531:             }
 3532:         }
 3533:     }
 3534:     return $num_tries;
 3535: }
 3536: 
 3537: # ----------- Determine decrements required in aggregate totals 
 3538: sub decrement_aggs {
 3539:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 3540:     my %decrement = (
 3541:                         attempts => 0,
 3542:                         users => 0,
 3543:                         correct => 0
 3544:                     );
 3545:     $decrement{'attempts'} = $aggtries;
 3546:     if ($solvedstatus =~ /^correct/) {
 3547:         $decrement{'correct'} = 1;
 3548:     }
 3549:     if ($aggtries == $totaltries) {
 3550:         $decrement{'users'} = 1;
 3551:     }
 3552:     foreach my $type (keys(%decrement)) {
 3553:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 3554:     }
 3555:     return;
 3556: }
 3557: 
 3558: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3559: sub get_last_resets {
 3560:     my ($symb,$courseid,$partids) =@_;
 3561:     my %last_resets;
 3562:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3563:     my $cname = $env{'course.'.$courseid.'.num'};
 3564:     my @keys;
 3565:     foreach my $part (@{$partids}) {
 3566: 	push(@keys,"$symb\0$part\0resettime");
 3567:     }
 3568:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3569: 				     $cdom,$cname);
 3570:     foreach my $part (@{$partids}) {
 3571: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3572:     }
 3573:     return %last_resets;
 3574: }
 3575: 
 3576: # ----------- Handles creating versions for portfolio files as answers
 3577: sub version_portfiles {
 3578:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3579:     my $version_parts = join('|',@$v_flag);
 3580:     my @returned_keys;
 3581:     my $parts = join('|', @$parts_graded);
 3582:     foreach my $key (keys(%$record)) {
 3583:         my $new_portfiles;
 3584:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3585:             my @versioned_portfiles;
 3586:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3587:             if (@portfiles) {
 3588:                 &Apache::lonnet::portfiles_versioning($symb,$domain,$stu_name,\@portfiles,
 3589:                                                       \@versioned_portfiles);
 3590:             }
 3591:             $$record{$key} = join(',',@versioned_portfiles);
 3592:             push(@returned_keys,$key);
 3593:         }
 3594:     } 
 3595:     return (@returned_keys);   
 3596: }
 3597: 
 3598: #--------------------------------------------------------------------------------------
 3599: #
 3600: #-------------------------- Next few routines handles grading by section or whole class
 3601: #
 3602: #--- Javascript to handle grading by section or whole class
 3603: sub viewgrades_js {
 3604:     my ($request) = shift;
 3605: 
 3606:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3607:     &js_escape(\$alertmsg);
 3608:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
 3609:    function writePoint(partid,weight,point) {
 3610: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3611: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3612: 	if (point == "textval") {
 3613: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3614: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3615: 		alert("$alertmsg"+parseFloat(point));
 3616: 		var resetbox = false;
 3617: 		for (var i=0; i<radioButton.length; i++) {
 3618: 		    if (radioButton[i].checked) {
 3619: 			textbox.value = i;
 3620: 			resetbox = true;
 3621: 		    }
 3622: 		}
 3623: 		if (!resetbox) {
 3624: 		    textbox.value = "";
 3625: 		}
 3626: 		return;
 3627: 	    }
 3628: 	    if (parseFloat(point) > parseFloat(weight)) {
 3629: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3630: 				   ") greater than the weight for the part. Accept?");
 3631: 		if (resp == false) {
 3632: 		    textbox.value = "";
 3633: 		    return;
 3634: 		}
 3635: 	    }
 3636: 	    for (var i=0; i<radioButton.length; i++) {
 3637: 		radioButton[i].checked=false;
 3638: 		if (parseFloat(point) == i) {
 3639: 		    radioButton[i].checked=true;
 3640: 		}
 3641: 	    }
 3642: 
 3643: 	} else {
 3644: 	    textbox.value = parseFloat(point);
 3645: 	}
 3646: 	for (i=0;i<document.classgrade.total.value;i++) {
 3647: 	    var user = document.classgrade["ctr"+i].value;
 3648: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3649: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3650: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3651: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3652: 	    if (saveval != "correct") {
 3653: 		scorename.value = point;
 3654: 		if (selname[0].selected != true) {
 3655: 		    selname[0].selected = true;
 3656: 		}
 3657: 	    }
 3658: 	}
 3659: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3660:     }
 3661: 
 3662:     function writeRadText(partid,weight) {
 3663: 	var selval   = document.classgrade["SELVAL_"+partid];
 3664: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3665:         var override = document.classgrade["FORCE_"+partid].checked;
 3666: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3667: 	if (selval[1].selected || selval[2].selected) {
 3668: 	    for (var i=0; i<radioButton.length; i++) {
 3669: 		radioButton[i].checked=false;
 3670: 
 3671: 	    }
 3672: 	    textbox.value = "";
 3673: 
 3674: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3675: 		var user = document.classgrade["ctr"+i].value;
 3676: 		user = user.replace(new RegExp(':', 'g'),"_");
 3677: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3678: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3679: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3680: 		if ((saveval != "correct") || override) {
 3681: 		    scorename.value = "";
 3682: 		    if (selval[1].selected) {
 3683: 			selname[1].selected = true;
 3684: 		    } else {
 3685: 			selname[2].selected = true;
 3686: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3687: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3688: 		    }
 3689: 		}
 3690: 	    }
 3691: 	} else {
 3692: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3693: 		var user = document.classgrade["ctr"+i].value;
 3694: 		user = user.replace(new RegExp(':', 'g'),"_");
 3695: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3696: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3697: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3698: 		if ((saveval != "correct") || override) {
 3699: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3700: 		    selname[0].selected = true;
 3701: 		}
 3702: 	    }
 3703: 	}	    
 3704:     }
 3705: 
 3706:     function changeSelect(partid,user) {
 3707: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3708: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3709: 	var point  = textbox.value;
 3710: 	var weight = document.classgrade["weight_"+partid].value;
 3711: 
 3712: 	if (isNaN(point) || parseFloat(point) < 0) {
 3713: 	    alert("$alertmsg"+parseFloat(point));
 3714: 	    textbox.value = "";
 3715: 	    return;
 3716: 	}
 3717: 	if (parseFloat(point) > parseFloat(weight)) {
 3718: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3719: 			       ") greater than the weight of the part. Accept?");
 3720: 	    if (resp == false) {
 3721: 		textbox.value = "";
 3722: 		return;
 3723: 	    }
 3724: 	}
 3725: 	selval[0].selected = true;
 3726:     }
 3727: 
 3728:     function changeOneScore(partid,user) {
 3729: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3730: 	if (selval[1].selected || selval[2].selected) {
 3731: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3732: 	    if (selval[2].selected) {
 3733: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3734: 	    }
 3735:         }
 3736:     }
 3737: 
 3738:     function resetEntry(numpart) {
 3739: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3740: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3741: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3742: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3743: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3744: 	    for (var i=0; i<radioButton.length; i++) {
 3745: 		radioButton[i].checked=false;
 3746: 
 3747: 	    }
 3748: 	    textbox.value = "";
 3749: 	    selval[0].selected = true;
 3750: 
 3751: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3752: 		var user = document.classgrade["ctr"+i].value;
 3753: 		user = user.replace(new RegExp(':', 'g'),"_");
 3754: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3755: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3756: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3757: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3758: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3759: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3760: 		if (saveselval == "excused") {
 3761: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3762: 		} else {
 3763: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3764: 		}
 3765: 	    }
 3766: 	}
 3767:     }
 3768: 
 3769: VIEWJAVASCRIPT
 3770: }
 3771: 
 3772: #--- show scores for a section or whole class w/ option to change/update a score
 3773: sub viewgrades {
 3774:     my ($request,$symb) = @_;
 3775:     my ($is_tool,$toolsymb);
 3776:     if ($symb =~ /ext\.tool$/) {
 3777:         $is_tool = 1;
 3778:         $toolsymb = $symb;
 3779:     }
 3780:     &viewgrades_js($request);
 3781: 
 3782:     #need to make sure we have the correct data for later EXT calls, 
 3783:     #thus invalidate the cache
 3784:     &Apache::lonnet::devalidatecourseresdata(
 3785:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3786:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3787:     &Apache::lonnet::clear_EXT_cache_status();
 3788: 
 3789:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3790: 
 3791:     #view individual student submission form - called using Javascript viewOneStudent
 3792:     $result.=&jscriptNform($symb);
 3793: 
 3794:     #beginning of class grading form
 3795:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3796:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3797: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3798: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3799: 	&build_section_inputs().
 3800: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3801: 
 3802:     #retrieve selected groups
 3803:     my (@groups,$group_display);
 3804:     @groups = &Apache::loncommon::get_env_multiple('form.group');
 3805:     if (grep(/^all$/,@groups)) {
 3806:         @groups = ('all');
 3807:     } elsif (grep(/^none$/,@groups)) {
 3808:         @groups = ('none');
 3809:     } elsif (@groups > 0) {
 3810:         $group_display = join(', ',@groups);
 3811:     }
 3812: 
 3813:     my ($common_header,$specific_header,@sections,$section_display);
 3814:     @sections = &Apache::loncommon::get_env_multiple('form.section');
 3815:     if (grep(/^all$/,@sections)) {
 3816:         @sections = ('all');
 3817:         if ($group_display) {
 3818:             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
 3819:             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
 3820:         } elsif (grep(/^none$/,@groups)) {
 3821:             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
 3822:             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
 3823:         } else {
 3824: 	    $common_header = &mt('Assign Common Grade to Class');
 3825:             $specific_header = &mt('Assign Grade to Specific Students in Class');
 3826:         }
 3827:     } elsif (grep(/^none$/,@sections)) {
 3828:         @sections = ('none');
 3829:         if ($group_display) {
 3830:             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
 3831:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
 3832:         } elsif (grep(/^none$/,@groups)) {
 3833:             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
 3834:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
 3835:         } else {
 3836:             $common_header = &mt('Assign Common Grade to Students in no Section');
 3837: 	    $specific_header = &mt('Assign Grade to Specific Students in no Section');
 3838:         }
 3839:     } else {
 3840:         $section_display = join (", ",@sections);
 3841:         if ($group_display) {
 3842:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
 3843:                                  $section_display,$group_display);
 3844:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
 3845:                                    $section_display,$group_display);
 3846:         } elsif (grep(/^none$/,@groups)) {
 3847:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
 3848:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
 3849:         } else {
 3850:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3851: 	    $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3852:         }
 3853:     }
 3854:     my %submit_types = &substatus_options();
 3855:     my $submission_status = $submit_types{$env{'form.submitonly'}};
 3856: 
 3857:     if ($env{'form.submitonly'} eq 'all') {
 3858:         $result.= '<h3>'.$common_header.'</h3>';
 3859:     } else {
 3860:         my $text;
 3861:         if ($is_tool) {
 3862:             $text = &mt('(transaction status: "[_1]")',$submission_status);
 3863:         } else {
 3864:             $text = &mt('(submission status: "[_1]")',$submission_status);
 3865:         }
 3866:         $result.= '<h3>'.$common_header.'&nbsp;'.$text.'</h3>';
 3867:     }
 3868:     $result .= &Apache::loncommon::start_data_table();
 3869:     #radio buttons/text box for assigning points for a section or class.
 3870:     #handles different parts of a problem
 3871:     my $res_error;
 3872:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3873:     if ($res_error) {
 3874:         return &navmap_errormsg();
 3875:     }
 3876:     my %weight = ();
 3877:     my $ctsparts = 0;
 3878:     my %seen = ();
 3879:     my @part_response_id;
 3880:     if ($is_tool) {
 3881:         @part_response_id = ([0,'']);
 3882:     } else {
 3883:         @part_response_id = &flatten_responseType($responseType);
 3884:     }
 3885:     foreach my $part_response_id (@part_response_id) {
 3886:     	my ($partid,$respid) = @{ $part_response_id };
 3887: 	my $part_resp = join('_',@{ $part_response_id });
 3888: 	next if $seen{$partid};
 3889: 	$seen{$partid}++;
 3890: #	my $handgrade=$$handgrade{$part_resp};
 3891: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3892: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3893: 
 3894: 	my $display_part=&get_display_part($partid,$symb);
 3895: 	my $radio.='<table border="0"><tr>';  
 3896: 	my $ctr = 0;
 3897: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3898: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3899: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3900: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3901: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3902: 	    $ctr++;
 3903: 	}
 3904: 	$radio.='</tr></table>';
 3905: 	my $line = '<input type="text" name="TEXTVAL_'.
 3906: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 3907: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3908: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3909:         $line.= '<td><b>'.&mt('Grade Status').':</b>'.
 3910:             '<select name="SELVAL_'.$partid.'" '.
 3911:             'onchange="javascript:writeRadText(\''.$partid.'\','.
 3912:                 $weight{$partid}.')"> '.
 3913: 	    '<option selected="selected"> </option>'.
 3914: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3915: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3916: 	    '</select></td>'.
 3917:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3918: 	$line.='<input type="hidden" name="partid_'.
 3919: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3920: 	$line.='<input type="hidden" name="weight_'.
 3921: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3922: 
 3923: 	$result.=
 3924: 	    &Apache::loncommon::start_data_table_row()."\n".
 3925: 	    '<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>'.
 3926: 	    &Apache::loncommon::end_data_table_row()."\n";
 3927: 	$ctsparts++;
 3928:     }
 3929:     $result.=&Apache::loncommon::end_data_table()."\n".
 3930: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3931:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3932: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 3933: 
 3934:     #table listing all the students in a section/class
 3935:     #header of table
 3936:     if ($env{'form.submitonly'} eq 'all') {
 3937:         $result.= '<h3>'.$specific_header.'</h3>';
 3938:     } else {
 3939:         my $text;
 3940:         if ($is_tool) {
 3941:             $text = &mt('(transaction status: "[_1]")',$submission_status);
 3942:         } else {
 3943:             $text = &mt('(submission status: "[_1]")',$submission_status);
 3944:         }
 3945:         $result.= '<h3>'.$specific_header.'&nbsp;'.$text.'</h3>';
 3946:     }
 3947:     $result.= &Apache::loncommon::start_data_table().
 3948: 	      &Apache::loncommon::start_data_table_header_row().
 3949: 	      '<th>'.&mt('No.').'</th>'.
 3950: 	      '<th>'.&nameUserString('header')."</th>\n";
 3951:     my $partserror;
 3952:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3953:     if ($partserror) {
 3954:         return &navmap_errormsg();
 3955:     }
 3956:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3957:     my @partids = ();
 3958:     foreach my $part (@parts) {
 3959: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
 3960:         my $narrowtext = &mt('Tries');
 3961: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3962: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name',$toolsymb); }
 3963: 	my ($partid) = &split_part_type($part);
 3964:         push(@partids,$partid);
 3965: #
 3966: # FIXME: Looks like $display looks at English text
 3967: #
 3968: 	my $display_part=&get_display_part($partid,$symb);
 3969: 	if ($display =~ /^Partial Credit Factor/) {
 3970: 	    $result.='<th>'.
 3971: 		&mt('Score Part: [_1][_2](weight = [_3])',
 3972: 		    $display_part,'<br />',$weight{$partid}).'</th>'."\n";
 3973: 	    next;
 3974: 	    
 3975: 	} else {
 3976: 	    if ($display =~ /Problem Status/) {
 3977: 		my $grade_status_mt = &mt('Grade Status');
 3978: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3979: 	    }
 3980: 	    my $part_mt = &mt('Part:');
 3981: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3982: 	}
 3983: 
 3984: 	$result.='<th>'.$display.'</th>'."\n";
 3985:     }
 3986:     $result.=&Apache::loncommon::end_data_table_header_row();
 3987: 
 3988:     my %last_resets = 
 3989: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3990: 
 3991:     #get info for each student
 3992:     #list all the students - with points and grade status
 3993:     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
 3994:     my $ctr = 0;
 3995:     foreach (sort 
 3996: 	     {
 3997: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3998: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3999: 		 }
 4000: 		 return $a cmp $b;
 4001: 	     } (keys(%$fullname))) {
 4002: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 4003: 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets,$is_tool);
 4004:     }
 4005:     $result.=&Apache::loncommon::end_data_table();
 4006:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 4007:     $result.='<input type="button" value="'.&mt('Save').'" '.
 4008: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 4009:     if ($ctr == 0) {
 4010:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 4011:         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
 4012:                 '<span class="LC_warning">';
 4013:         if ($env{'form.submitonly'} eq 'all') {
 4014:             if (grep(/^all$/,@sections)) {
 4015:                 if (grep(/^all$/,@groups)) {
 4016:                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
 4017:                                    $stu_status);
 4018:                 } elsif (grep(/^none$/,@groups)) {
 4019:                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
 4020:                                    $stu_status); 
 4021:                 } else {
 4022:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
 4023:                                    $group_display,$stu_status);
 4024:                 }
 4025:             } elsif (grep(/^none$/,@sections)) {
 4026:                 if (grep(/^all$/,@groups)) {
 4027:                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
 4028:                                    $stu_status);
 4029:                 } elsif (grep(/^none$/,@groups)) {
 4030:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
 4031:                                    $stu_status);
 4032:                 } else {
 4033:                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
 4034:                                    $group_display,$stu_status);
 4035:                 }
 4036:             } else {
 4037:                 if (grep(/^all$/,@groups)) {
 4038:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 4039:                                    $section_display,$stu_status);
 4040:                 } elsif (grep(/^none$/,@groups)) {
 4041:                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
 4042:                                    $section_display,$stu_status);
 4043:                 } else {
 4044:                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
 4045:                                    $section_display,$group_display,$stu_status);
 4046:                 }
 4047:             }
 4048:         } else {
 4049:             if (grep(/^all$/,@sections)) {
 4050:                 if (grep(/^all$/,@groups)) {
 4051:                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4052:                                    $stu_status,$submission_status);
 4053:                 } elsif (grep(/^none$/,@groups)) {
 4054:                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4055:                                    $stu_status,$submission_status);
 4056:                 } else {
 4057:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 4058:                                    $group_display,$stu_status,$submission_status);
 4059:                 }
 4060:             } elsif (grep(/^none$/,@sections)) {
 4061:                 if (grep(/^all$/,@groups)) {
 4062:                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4063:                                    $stu_status,$submission_status);
 4064:                 } elsif (grep(/^none$/,@groups)) {
 4065:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4066:                                    $stu_status,$submission_status);
 4067:                 } else {
 4068:                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 4069:                                    $group_display,$stu_status,$submission_status);
 4070:                 }
 4071:             } else {
 4072:                 if (grep(/^all$/,@groups)) {
 4073: 	            $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 4074: 	                           $section_display,$stu_status,$submission_status);
 4075:                 } elsif (grep(/^none$/,@groups)) {
 4076:                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 4077:                                    $section_display,$stu_status,$submission_status);
 4078:                 } else {
 4079:                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] and submission status "[_4]" to modify or grade.',
 4080:                                    $section_display,$group_display,$stu_status,$submission_status);
 4081:                 }
 4082:             }
 4083:         }
 4084: 	$result .= '</span><br />';
 4085:     }
 4086:     return $result;
 4087: }
 4088: 
 4089: #--- call by previous routine to display each student who satisfies submission filter. 
 4090: sub viewstudentgrade {
 4091:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets,$is_tool) = @_;
 4092:     my ($uname,$udom) = split(/:/,$student);
 4093:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 4094:     my $submitonly = $env{'form.submitonly'};
 4095:     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
 4096:         my %partstatus = ();
 4097:         if (ref($parts) eq 'ARRAY') {
 4098:             foreach my $apart (@{$parts}) {
 4099:                 my ($part,$type) = &split_part_type($apart);
 4100:                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
 4101:                 $status = 'nothing' if ($status eq '');
 4102:                 $partstatus{$part}      = $status;
 4103:                 my $subkey = "resource.$part.submitted_by";
 4104:                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
 4105:             }
 4106:             my $submitted = 0;
 4107:             my $graded = 0;
 4108:             my $incorrect = 0;
 4109:             foreach my $key (keys(%partstatus)) {
 4110:                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
 4111:                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
 4112:                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
 4113: 
 4114:                 my $partid = (split(/\./,$key))[1];
 4115:                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
 4116:                     $submitted = 0;
 4117:                 }
 4118:             }
 4119:             return if (!$submitted && ($submitonly eq 'yes' ||
 4120:                                        $submitonly eq 'incorrect' ||
 4121:                                        $submitonly eq 'graded'));
 4122:             return if (!$graded && ($submitonly eq 'graded'));
 4123:             return if (!$incorrect && $submitonly eq 'incorrect');
 4124:         }
 4125:     }
 4126:     if ($submitonly eq 'queued') {
 4127:         my ($cdom,$cnum) = split(/_/,$courseid);
 4128:         my %queue_status =
 4129:             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 4130:                                                     $udom,$uname);
 4131:         return if (!defined($queue_status{'gradingqueue'}));
 4132:     }
 4133:     $$ctr++;
 4134:     my %aggregates = ();
 4135:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 4136: 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
 4137: 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
 4138: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 4139: 	'\');" target="_self">'.$fullname.'</a> '.
 4140: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 4141:     $student=~s/:/_/; # colon doen't work in javascript for names
 4142:     foreach my $apart (@$parts) {
 4143: 	my ($part,$type) = &split_part_type($apart);
 4144: 	my $score=$record{"resource.$part.$type"};
 4145:         $result.='<td align="center">';
 4146:         my ($aggtries,$totaltries);
 4147:         unless (exists($aggregates{$part})) {
 4148: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 4149: 	    $aggtries = $totaltries;
 4150:             if ($$last_resets{$part}) {  
 4151:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 4152: 					   $part);
 4153:             }
 4154:             $result.='<input type="hidden" name="'.
 4155:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 4156:             $result.='<input type="hidden" name="'.
 4157:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 4158:             $aggregates{$part} = 1;
 4159:         }
 4160: 	if ($type eq 'awarded') {
 4161: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 4162: 	    $result.='<input type="hidden" name="'.
 4163: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 4164: 	    $result.='<input type="text" name="'.
 4165: 		'GD_'.$student.'_'.$part.'_awarded" '.
 4166:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 4167: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 4168: 	} elsif ($type eq 'solved') {
 4169: 	    my ($status,$foo)=split(/_/,$score,2);
 4170: 	    $status = 'nothing' if ($status eq '');
 4171: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 4172: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 4173: 	    $result.='&nbsp;<select name="'.
 4174: 		'GD_'.$student.'_'.$part.'_solved" '.
 4175:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 4176: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 4177: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 4178: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 4179: 	    $result.="</select>&nbsp;</td>\n";
 4180: 	} else {
 4181: 	    $result.='<input type="hidden" name="'.
 4182: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 4183: 		    "\n";
 4184: 	    $result.='<input type="text" name="'.
 4185: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 4186: 		'value="'.$score.'" size="4" /></td>'."\n";
 4187: 	}
 4188:     }
 4189:     $result.=&Apache::loncommon::end_data_table_row();
 4190:     return $result;
 4191: }
 4192: 
 4193: #--- change scores for all the students in a section/class
 4194: #    record does not get update if unchanged
 4195: sub editgrades {
 4196:     my ($request,$symb) = @_;
 4197:     my $toolsymb;
 4198:     if ($symb =~ /ext\.tool$/) {
 4199:         $toolsymb = $symb;
 4200:     }
 4201: 
 4202:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 4203:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 4204:     $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
 4205: 
 4206:     my $result= &Apache::loncommon::start_data_table().
 4207: 	&Apache::loncommon::start_data_table_header_row().
 4208: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 4209: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 4210:     my %scoreptr = (
 4211: 		    'correct'  =>'correct_by_override',
 4212: 		    'incorrect'=>'incorrect_by_override',
 4213: 		    'excused'  =>'excused',
 4214: 		    'ungraded' =>'ungraded_attempted',
 4215:                     'credited' =>'credit_attempted',
 4216: 		    'nothing'  => '',
 4217: 		    );
 4218:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 4219: 
 4220:     my (@partid);
 4221:     my %weight = ();
 4222:     my %columns = ();
 4223:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 4224: 
 4225:     my $partserror;
 4226:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 4227:     if ($partserror) {
 4228:         return &navmap_errormsg();
 4229:     }
 4230:     my $header;
 4231:     while ($ctr < $env{'form.totalparts'}) {
 4232: 	my $partid = $env{'form.partid_'.$ctr};
 4233: 	push(@partid,$partid);
 4234: 	$weight{$partid} = $env{'form.weight_'.$partid};
 4235: 	$ctr++;
 4236:     }
 4237:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4238:     my $totcolspan = 0;
 4239:     foreach my $partid (@partid) {
 4240: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 4241: 	    '<th align="center">'.&mt('New Score').'</th>';
 4242: 	$columns{$partid}=2;
 4243: 	foreach my $stores (@parts) {
 4244: 	    my ($part,$type) = &split_part_type($stores);
 4245: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 4246: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 4247: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display',$toolsymb);
 4248: 	    $display =~ s/\[Part: \Q$part\E\]//;
 4249:             my $narrowtext = &mt('Tries');
 4250: 	    $display =~ s/Number of Attempts/$narrowtext/;
 4251: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 4252: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 4253: 	    $columns{$partid}+=2;
 4254: 	}
 4255:         $totcolspan += $columns{$partid};
 4256:     }
 4257:     foreach my $partid (@partid) {
 4258: 	my $display_part=&get_display_part($partid,$symb);
 4259: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 4260: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 4261: 	    '</th>';
 4262: 
 4263:     }
 4264:     $result .= &Apache::loncommon::end_data_table_header_row().
 4265: 	&Apache::loncommon::start_data_table_header_row().
 4266: 	$header.
 4267: 	&Apache::loncommon::end_data_table_header_row();
 4268:     my @noupdate;
 4269:     my ($updateCtr,$noupdateCtr) = (1,1);
 4270:     for ($i=0; $i<$env{'form.total'}; $i++) {
 4271: 	my $user = $env{'form.ctr'.$i};
 4272: 	my ($uname,$udom)=split(/:/,$user);
 4273: 	my %newrecord;
 4274: 	my $updateflag = 0;
 4275: 	my $usec=$classlist->{"$uname:$udom"}[5];
 4276: 	my $canmodify = &canmodify($usec);
 4277: 	my $line = '<td'.($canmodify?'':' colspan="2"').'>'.
 4278: 		   &nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 4279: 	if (!$canmodify) {
 4280: 	    push(@noupdate,
 4281: 		 $line."<td colspan=\"$totcolspan\"><span class=\"LC_warning\">".
 4282: 		 &mt('Not allowed to modify student')."</span></td>");
 4283: 	    next;
 4284: 	}
 4285:         my %aggregate = ();
 4286:         my $aggregateflag = 0;
 4287: 	$user=~s/:/_/; # colon doen't work in javascript for names
 4288: 	foreach (@partid) {
 4289: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 4290: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 4291: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 4292: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 4293: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 4294: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 4295: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 4296: 	    my $score;
 4297: 	    if ($partial eq '') {
 4298: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 4299: 	    } elsif ($partial > 0) {
 4300: 		$score = 'correct_by_override';
 4301: 	    } elsif ($partial == 0) {
 4302: 		$score = 'incorrect_by_override';
 4303: 	    }
 4304: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 4305: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 4306: 
 4307: 	    $newrecord{'resource.'.$_.'.regrader'}=
 4308: 		"$env{'user.name'}:$env{'user.domain'}";
 4309: 	    if ($dropMenu eq 'reset status' &&
 4310: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 4311: 		$newrecord{'resource.'.$_.'.tries'} = '';
 4312: 		$newrecord{'resource.'.$_.'.solved'} = '';
 4313: 		$newrecord{'resource.'.$_.'.award'} = '';
 4314: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 4315: 		$updateflag = 1;
 4316:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 4317:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 4318:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 4319:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 4320:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4321:                     $aggregateflag = 1;
 4322:                 }
 4323: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 4324: 		$updateflag = 1;
 4325: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 4326: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 4327: 		$rec_update++;
 4328: 	    }
 4329: 
 4330: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4331: 		'<td align="center">'.$awarded.
 4332: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 4333: 
 4334: 
 4335: 	    my $partid=$_;
 4336: 	    foreach my $stores (@parts) {
 4337: 		my ($part,$type) = &split_part_type($stores);
 4338: 		if ($part !~ m/^\Q$partid\E/) { next;}
 4339: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 4340: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 4341: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 4342: 		if ($awarded ne '' && $awarded ne $old_aw) {
 4343: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 4344: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 4345: 		    $updateflag=1;
 4346: 		}
 4347: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4348: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 4349: 	    }
 4350: 	}
 4351: 	$line.="\n";
 4352: 
 4353: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4354: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4355: 
 4356: 	if ($updateflag) {
 4357: 	    $count++;
 4358: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 4359: 				    $udom,$uname);
 4360: 
 4361: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 4362: 					      $cnum,$udom,$uname)) {
 4363: 		# need to figure out if should be in queue.
 4364: 		my %record =  
 4365: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 4366: 					     $udom,$uname);
 4367: 		my $all_graded = 1;
 4368: 		my $none_graded = 1;
 4369: 		foreach my $part (@parts) {
 4370: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 4371: 			$all_graded = 0;
 4372: 		    } else {
 4373: 			$none_graded = 0;
 4374: 		    }
 4375: 		}
 4376: 
 4377: 		if ($all_graded || $none_graded) {
 4378: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 4379: 							   $symb,$cdom,$cnum,
 4380: 							   $udom,$uname);
 4381: 		}
 4382: 	    }
 4383: 
 4384: 	    $result.=&Apache::loncommon::start_data_table_row().
 4385: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 4386: 		&Apache::loncommon::end_data_table_row();
 4387: 	    $updateCtr++;
 4388: 	} else {
 4389: 	    push(@noupdate,
 4390: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 4391: 	    $noupdateCtr++;
 4392: 	}
 4393:         if ($aggregateflag) {
 4394:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4395: 				  $cdom,$cnum);
 4396:         }
 4397:     }
 4398:     if (@noupdate) {
 4399:         my $numcols=$totcolspan+2;
 4400: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 4401: 	    '<td align="center" colspan="'.$numcols.'">'.
 4402: 	    &mt('No Changes Occurred For the Students Below').
 4403: 	    '</td>'.
 4404: 	    &Apache::loncommon::end_data_table_row();
 4405: 	foreach my $line (@noupdate) {
 4406: 	    $result.=
 4407: 		&Apache::loncommon::start_data_table_row().
 4408: 		$line.
 4409: 		&Apache::loncommon::end_data_table_row();
 4410: 	}
 4411:     }
 4412:     $result .= &Apache::loncommon::end_data_table();
 4413:     my $msg = '<p><b>'.
 4414: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 4415: 	    $rec_update,$count).'</b><br />'.
 4416: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 4417: 	'</b></p>';
 4418:     return $title.$msg.$result;
 4419: }
 4420: 
 4421: sub split_part_type {
 4422:     my ($partstr) = @_;
 4423:     my ($temp,@allparts)=split(/_/,$partstr);
 4424:     my $type=pop(@allparts);
 4425:     my $part=join('_',@allparts);
 4426:     return ($part,$type);
 4427: }
 4428: 
 4429: #------------- end of section for handling grading by section/class ---------
 4430: #
 4431: #----------------------------------------------------------------------------
 4432: 
 4433: 
 4434: #----------------------------------------------------------------------------
 4435: #
 4436: #-------------------------- Next few routines handles grading by csv upload
 4437: #
 4438: #--- Javascript to handle csv upload
 4439: sub csvupload_javascript_reverse_associate {
 4440:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
 4441:     my $error2=&mt('You need to specify at least one grading field');
 4442:   &js_escape(\$error1);
 4443:   &js_escape(\$error2);
 4444:   return(<<ENDPICK);
 4445:   function verify(vf) {
 4446:     var foundsomething=0;
 4447:     var founduname=0;
 4448:     var foundID=0;
 4449:     var foundclicker=0;
 4450:     for (i=0;i<=vf.nfields.value;i++) {
 4451:       tw=eval('vf.f'+i+'.selectedIndex');
 4452:       if (i==0 && tw!=0) { foundID=1; }
 4453:       if (i==1 && tw!=0) { founduname=1; }
 4454:       if (i==2 && tw!=0) { foundclicker=1; }
 4455:       if (i!=0 && i!=1 && i!=2 && i!=3 && tw!=0) { foundsomething=1; }
 4456:     }
 4457:     if (founduname==0 && foundID==0 && foundclicker==0) {
 4458: 	alert('$error1');
 4459: 	return;
 4460:     }
 4461:     if (foundsomething==0) {
 4462: 	alert('$error2');
 4463: 	return;
 4464:     }
 4465:     vf.submit();
 4466:   }
 4467:   function flip(vf,tf) {
 4468:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4469:     var i;
 4470:     for (i=0;i<=vf.nfields.value;i++) {
 4471:       //can not pick the same destination field for both name and domain
 4472:       if (((i ==0)||(i ==1)) && 
 4473:           ((tf==0)||(tf==1)) && 
 4474:           (i!=tf) &&
 4475:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4476:         eval('vf.f'+i+'.selectedIndex=0;')
 4477:       }
 4478:     }
 4479:   }
 4480: ENDPICK
 4481: }
 4482: 
 4483: sub csvupload_javascript_forward_associate {
 4484:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
 4485:     my $error2=&mt('You need to specify at least one grading field');
 4486:   &js_escape(\$error1);
 4487:   &js_escape(\$error2);
 4488:   return(<<ENDPICK);
 4489:   function verify(vf) {
 4490:     var foundsomething=0;
 4491:     var founduname=0;
 4492:     var foundID=0;
 4493:     var foundclicker=0;
 4494:     for (i=0;i<=vf.nfields.value;i++) {
 4495:       tw=eval('vf.f'+i+'.selectedIndex');
 4496:       if (tw==1) { foundID=1; }
 4497:       if (tw==2) { founduname=1; }
 4498:       if (tw==3) { foundclicker=1; }
 4499:       if (tw>4) { foundsomething=1; }
 4500:     }
 4501:     if (founduname==0 && foundID==0 && Æ’oundclicker==0) {
 4502: 	alert('$error1');
 4503: 	return;
 4504:     }
 4505:     if (foundsomething==0) {
 4506: 	alert('$error2');
 4507: 	return;
 4508:     }
 4509:     vf.submit();
 4510:   }
 4511:   function flip(vf,tf) {
 4512:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4513:     var i;
 4514:     //can not pick the same destination field twice
 4515:     for (i=0;i<=vf.nfields.value;i++) {
 4516:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4517:         eval('vf.f'+i+'.selectedIndex=0;')
 4518:       }
 4519:     }
 4520:   }
 4521: ENDPICK
 4522: }
 4523: 
 4524: sub csvuploadmap_header {
 4525:     my ($request,$symb,$datatoken,$distotal)= @_;
 4526:     my $javascript;
 4527:     if ($env{'form.upfile_associate'} eq 'reverse') {
 4528: 	$javascript=&csvupload_javascript_reverse_associate();
 4529:     } else {
 4530: 	$javascript=&csvupload_javascript_forward_associate();
 4531:     }
 4532: 
 4533:     $symb = &Apache::lonenc::check_encrypt($symb);
 4534:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
 4535:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
 4536:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
 4537:     my $reverse=&mt("Reverse Association");
 4538:     $request->print(<<ENDPICK);
 4539: <br />
 4540: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 4541: <input type="hidden" name="associate"  value="" />
 4542: <input type="hidden" name="phase"      value="three" />
 4543: <input type="hidden" name="datatoken"  value="$datatoken" />
 4544: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 4545: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 4546: <input type="hidden" name="upfile_associate" 
 4547:                                        value="$env{'form.upfile_associate'}" />
 4548: <input type="hidden" name="symb"       value="$symb" />
 4549: <input type="hidden" name="command"    value="csvuploadoptions" />
 4550: <hr />
 4551: ENDPICK
 4552:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
 4553:     return '';
 4554: 
 4555: }
 4556: 
 4557: sub csvupload_fields {
 4558:     my ($symb,$errorref) = @_;
 4559:     my $toolsymb;
 4560:     if ($symb =~ /ext\.tool$/) {
 4561:         $toolsymb = $symb;
 4562:     }
 4563:     my (@parts) = &getpartlist($symb,$errorref);
 4564:     if (ref($errorref)) {
 4565:         if ($$errorref) {
 4566:             return;
 4567:         }
 4568:     }
 4569: 
 4570:     my @fields=(['ID','Student/Employee ID'],
 4571: 		['username','Student Username'],
 4572: 		['clicker','Clicker ID'],
 4573: 		['domain','Student Domain']);
 4574:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4575:     foreach my $part (sort(@parts)) {
 4576: 	my @datum;
 4577: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
 4578: 	my $name=$part;
 4579: 	if (!$display) { $display = $name; }
 4580: 	@datum=($name,$display);
 4581: 	if ($name=~/^stores_(.*)_awarded/) {
 4582: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 4583: 	}
 4584: 	push(@fields,\@datum);
 4585:     }
 4586:     return (@fields);
 4587: }
 4588: 
 4589: sub csvuploadmap_footer {
 4590:     my ($request,$i,$keyfields) =@_;
 4591:     my $buttontext = &mt('Assign Grades');
 4592:     $request->print(<<ENDPICK);
 4593: </table>
 4594: <input type="hidden" name="nfields" value="$i" />
 4595: <input type="hidden" name="keyfields" value="$keyfields" />
 4596: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
 4597: </form>
 4598: ENDPICK
 4599: }
 4600: 
 4601: sub checkforfile_js {
 4602:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 4603:     &js_escape(\$alertmsg);
 4604:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
 4605:     function checkUpload(formname) {
 4606: 	if (formname.upfile.value == "") {
 4607: 	    alert("$alertmsg");
 4608: 	    return false;
 4609: 	}
 4610: 	formname.submit();
 4611:     }
 4612: CSVFORMJS
 4613:     return $result;
 4614: }
 4615: 
 4616: sub upcsvScores_form {
 4617:     my ($request,$symb) = @_;
 4618:     if (!$symb) {return '';}
 4619:     my $result=&checkforfile_js();
 4620:     $result.=&Apache::loncommon::start_data_table().
 4621:              &Apache::loncommon::start_data_table_header_row().
 4622:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
 4623:              &Apache::loncommon::end_data_table_header_row().
 4624:              &Apache::loncommon::start_data_table_row().'<td>';
 4625:     my $upload=&mt("Upload Scores");
 4626:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 4627:     my $ignore=&mt('Ignore First Line');
 4628:     $symb = &Apache::lonenc::check_encrypt($symb);
 4629:     $result.=<<ENDUPFORM;
 4630: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4631: <input type="hidden" name="symb" value="$symb" />
 4632: <input type="hidden" name="command" value="csvuploadmap" />
 4633: $upfile_select
 4634: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 4635: </form>
 4636: ENDUPFORM
 4637:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 4638:                            &mt("How do I create a CSV file from a spreadsheet")).
 4639:              '</td>'.
 4640:             &Apache::loncommon::end_data_table_row().
 4641:             &Apache::loncommon::end_data_table();
 4642:     return $result;
 4643: }
 4644: 
 4645: 
 4646: sub csvuploadmap {
 4647:     my ($request,$symb) = @_;
 4648:     if (!$symb) {return '';}
 4649: 
 4650:     my $datatoken;
 4651:     if (!$env{'form.datatoken'}) {
 4652: 	$datatoken=&Apache::loncommon::upfile_store($request);
 4653:     } else {
 4654: 	$datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
 4655:         if ($datatoken ne '') {
 4656: 	    &Apache::loncommon::load_tmp_file($request,$datatoken);
 4657:         }
 4658:     }
 4659:     my @records=&Apache::loncommon::upfile_record_sep();
 4660:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 4661:     my ($i,$keyfields);
 4662:     if (@records) {
 4663:         my $fieldserror;
 4664: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 4665:         if ($fieldserror) {
 4666:             $request->print(&navmap_errormsg());
 4667:             return;
 4668:         }
 4669: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 4670: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 4671: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 4672: 							  \@fields);
 4673: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 4674: 	    chop($keyfields);
 4675: 	} else {
 4676: 	    unshift(@fields,['none','']);
 4677: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 4678: 							    \@fields);
 4679:             foreach my $rec (@records) {
 4680:                 my %temp = &Apache::loncommon::record_sep($rec);
 4681:                 if (%temp) {
 4682:                     $keyfields=join(',',sort(keys(%temp)));
 4683:                     last;
 4684:                 }
 4685:             }
 4686: 	}
 4687:     }
 4688:     &csvuploadmap_footer($request,$i,$keyfields);
 4689: 
 4690:     return '';
 4691: }
 4692: 
 4693: sub csvuploadoptions {
 4694:     my ($request,$symb)= @_;
 4695:     my $overwrite=&mt('Overwrite any existing score');
 4696:     $request->print(<<ENDPICK);
 4697: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4698: <input type="hidden" name="command"    value="csvuploadassign" />
 4699: <p>
 4700: <label>
 4701:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4702:    $overwrite
 4703: </label>
 4704: </p>
 4705: ENDPICK
 4706:     my %fields=&get_fields();
 4707:     if (!defined($fields{'domain'})) {
 4708: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4709: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
 4710:     }
 4711:     foreach my $key (sort(keys(%env))) {
 4712: 	if ($key !~ /^form\.(.*)$/) { next; }
 4713: 	my $cleankey=$1;
 4714: 	if ($cleankey eq 'command') { next; }
 4715: 	$request->print('<input type="hidden" name="'.$cleankey.
 4716: 			'"  value="'.$env{$key}.'" />'."\n");
 4717:     }
 4718:     # FIXME do a check for any duplicated user ids...
 4719:     # FIXME do a check for any invalid user ids?...
 4720:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
 4721: <hr /></form>'."\n");
 4722:     return '';
 4723: }
 4724: 
 4725: sub get_fields {
 4726:     my %fields;
 4727:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4728:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4729: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4730: 	    if ($env{'form.f'.$i} ne 'none') {
 4731: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4732: 	    }
 4733: 	} else {
 4734: 	    if ($env{'form.f'.$i} ne 'none') {
 4735: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4736: 	    }
 4737: 	}
 4738:     }
 4739:     return %fields;
 4740: }
 4741: 
 4742: sub csvuploadassign {
 4743:     my ($request,$symb) = @_;
 4744:     if (!$symb) {return '';}
 4745:     my $error_msg = '';
 4746:     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
 4747:     if ($datatoken ne '') { 
 4748:         &Apache::loncommon::load_tmp_file($request,$datatoken);
 4749:     }
 4750:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4751:     my %fields=&get_fields();
 4752:     my $courseid=$env{'request.course.id'};
 4753:     my ($classlist) = &getclasslist('all',0);
 4754:     my @notallowed;
 4755:     my @skipped;
 4756:     my @warnings;
 4757:     my $countdone=0;
 4758:     foreach my $grade (@gradedata) {
 4759: 	my %entries=&Apache::loncommon::record_sep($grade);
 4760: 	my $domain;
 4761: 	if ($entries{$fields{'domain'}}) {
 4762: 	    $domain=$entries{$fields{'domain'}};
 4763: 	} else {
 4764: 	    $domain=$env{'form.default_domain'};
 4765: 	}
 4766: 	$domain=~s/\s//g;
 4767: 	my $username=$entries{$fields{'username'}};
 4768: 	$username=~s/\s//g;
 4769: 	if (!$username) {
 4770: 	    my $id=$entries{$fields{'ID'}};
 4771: 	    $id=~s/\s//g;
 4772:             if ($id ne '') {
 4773: 	        my %ids=&Apache::lonnet::idget($domain,[$id]);
 4774: 	        $username=$ids{$id};
 4775:             } else {
 4776:                 if ($entries{$fields{'clicker'}}) {
 4777:                     my $clicker = $entries{$fields{'clicker'}};
 4778:                     $clicker=~s/\s//g;
 4779:                     if ($clicker ne '') {
 4780:                         my %clickers = &Apache::lonnet::idget($domain,[$clicker],'clickers');
 4781:                         if ($clickers{$clicker} ne '') {  
 4782:                             my $match = 0;
 4783:                             my @inclass;
 4784:                             foreach my $poss (split(/,/,$clickers{$clicker})) {
 4785:                                 if (exists($$classlist{"$poss:$domain"})) {
 4786:                                     $username = $poss;
 4787:                                     push(@inclass,$poss);
 4788:                                     $match ++;
 4789:                                     
 4790:                                 }
 4791:                             }
 4792:                             if ($match > 1) {
 4793:                                 undef($username); 
 4794:                                 $request->print('<p class="LC_warning">'.
 4795:                                                 &mt('Score not saved for clicker: [_1] (matched multiple usernames: [_2])',
 4796:                                                 $clicker,join(', ',@inclass)).'</p>');
 4797:                             }
 4798:                         }
 4799:                     }
 4800:                 }
 4801:             }
 4802: 	}
 4803: 	if (!exists($$classlist{"$username:$domain"})) {
 4804: 	    my $id=$entries{$fields{'ID'}};
 4805: 	    $id=~s/\s//g;
 4806:             my $clicker = $entries{$fields{'clicker'}};
 4807:             $clicker=~s/\s//g;
 4808:             if ($clicker) {
 4809:                 push(@skipped,"$clicker:$domain");
 4810: 	    } elsif ($id) {
 4811: 		push(@skipped,"$id:$domain");
 4812: 	    } else {
 4813: 		push(@skipped,"$username:$domain");
 4814: 	    }
 4815: 	    next;
 4816: 	}
 4817: 	my $usec=$classlist->{"$username:$domain"}[5];
 4818: 	if (!&canmodify($usec)) {
 4819: 	    push(@notallowed,"$username:$domain");
 4820: 	    next;
 4821: 	}
 4822: 	my %points;
 4823: 	my %grades;
 4824: 	foreach my $dest (keys(%fields)) {
 4825: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4826: 		$dest eq 'domain') { next; }
 4827: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4828: 	    if ($dest=~/stores_(.*)_points/) {
 4829: 		my $part=$1;
 4830: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4831: 					      $symb,$domain,$username);
 4832:                 if ($wgt) {
 4833:                     $entries{$fields{$dest}}=~s/\s//g;
 4834:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4835:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4836:                                           : 'correct_by_override';
 4837:                     if ($pcr>1) {
 4838:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
 4839:                     }
 4840:                     $grades{"resource.$part.awarded"}=$pcr;
 4841:                     $grades{"resource.$part.solved"}=$award;
 4842:                     $points{$part}=1;
 4843:                 } else {
 4844:                     $error_msg = "<br />" .
 4845:                         &mt("Some point values were assigned"
 4846:                             ." for problems with a weight "
 4847:                             ."of zero. These values were "
 4848:                             ."ignored.");
 4849:                 }
 4850: 	    } else {
 4851: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4852: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4853: 		my $store_key=$dest;
 4854: 		$store_key=~s/^stores/resource/;
 4855: 		$store_key=~s/_/\./g;
 4856: 		$grades{$store_key}=$entries{$fields{$dest}};
 4857: 	    }
 4858: 	}
 4859: 	if (! %grades) {
 4860:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4861:         } else {
 4862: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4863: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4864: 					   $env{'request.course.id'},
 4865: 					   $domain,$username);
 4866: 	   if ($result eq 'ok') {
 4867: # Successfully stored
 4868: 	      $request->print('.');
 4869: # Remove from grading queue
 4870:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
 4871:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
 4872:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
 4873:                                              $domain,$username);
 4874:               $countdone++;
 4875:            } else {
 4876: 	      $request->print("<p><span class=\"LC_error\">".
 4877:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4878:                                   "$username:$domain",$result)."</span></p>");
 4879: 	   }
 4880: 	   $request->rflush();
 4881:         }
 4882:     }
 4883:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 4884:     if (@warnings) {
 4885:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
 4886:         $request->print(join(', ',@warnings));
 4887:     }
 4888:     if (@skipped) {
 4889: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 4890:         $request->print(join(', ',@skipped));
 4891:     }
 4892:     if (@notallowed) {
 4893: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 4894: 	$request->print(join(', ',@notallowed));
 4895:     }
 4896:     $request->print("<br />\n");
 4897:     return $error_msg;
 4898: }
 4899: #------------- end of section for handling csv file upload ---------
 4900: #
 4901: #-------------------------------------------------------------------
 4902: #
 4903: #-------------- Next few routines handle grading by page/sequence
 4904: #
 4905: #--- Select a page/sequence and a student to grade
 4906: sub pickStudentPage {
 4907:     my ($request,$symb) = @_;
 4908: 
 4909:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4910:     &js_escape(\$alertmsg);
 4911:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
 4912: 
 4913: function checkPickOne(formname) {
 4914:     if (radioSelection(formname.student) == null) {
 4915: 	alert("$alertmsg");
 4916: 	return;
 4917:     }
 4918:     ptr = pullDownSelection(formname.selectpage);
 4919:     formname.page.value = formname["page"+ptr].value;
 4920:     formname.title.value = formname["title"+ptr].value;
 4921:     formname.submit();
 4922: }
 4923: 
 4924: LISTJAVASCRIPT
 4925:     &commonJSfunctions($request);
 4926: 
 4927:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4928:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4929:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4930:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
 4931: 
 4932:     my $result='<h3><span class="LC_info">&nbsp;'.
 4933: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4934: 
 4935:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4936:     my $map_error;
 4937:     my ($titles,$symbx) = &getSymbMap($map_error);
 4938:     if ($map_error) {
 4939:         $request->print(&navmap_errormsg());
 4940:         return; 
 4941:     }
 4942:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4943: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4944: #    my $type=($curpage =~ /\.(page|sequence)/);
 4945: 
 4946:     # Collection of hidden fields
 4947:     my $ctr=0;
 4948:     foreach (@$titles) {
 4949:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4950:         $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4951:         $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4952:         $ctr++;
 4953:     }
 4954:     $result.='<input type="hidden" name="page" />'."\n".
 4955:         '<input type="hidden" name="title" />'."\n";
 4956: 
 4957:     $result.=&build_section_inputs();
 4958:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4959:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4960: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4961: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 4962: 
 4963:     # Show grading options
 4964:     $result.=&Apache::lonhtmlcommon::start_pick_box();
 4965:     my $select = '<select name="selectpage">'."\n";
 4966:     $ctr=0;
 4967:     foreach (@$titles) {
 4968: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4969: 	$select.='<option value="'.$ctr.'"'.
 4970: 	    ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
 4971: 	    '>'.$showtitle.'</option>'."\n";
 4972: 	$ctr++;
 4973:     }
 4974:     $select.= '</select>';
 4975: 
 4976:     $result.=
 4977:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
 4978:        .$select
 4979:        .&Apache::lonhtmlcommon::row_closure();
 4980: 
 4981:     $result.=
 4982:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
 4983:        .'<label><input type="radio" name="vProb" value="no"'
 4984:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
 4985:        .'<label><input type="radio" name="vProb" value="yes" />'
 4986:            .&mt('yes').'</label>'."\n"
 4987:        .&Apache::lonhtmlcommon::row_closure();
 4988: 
 4989:     $result.=
 4990:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
 4991:        .'<label><input type="radio" name="lastSub" value="none" /> '
 4992:            .&mt('none').' </label>'."\n"
 4993:        .'<label><input type="radio" name="lastSub" value="datesub"'
 4994:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
 4995:        .'<label><input type="radio" name="lastSub" value="all" /> '
 4996:            .&mt('all submissions with details').' </label>'
 4997:        .&Apache::lonhtmlcommon::row_closure();
 4998:     
 4999:     $result.=
 5000:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
 5001:        .'<input type="text" name="CODE" value="" />'
 5002:        .&Apache::lonhtmlcommon::row_closure(1)
 5003:        .&Apache::lonhtmlcommon::end_pick_box();
 5004: 
 5005:     # Show list of students to select for grading
 5006:     $result.='<br /><input type="button" '.
 5007:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 5008: 
 5009:     $request->print($result);
 5010: 
 5011:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 5012: 	&Apache::loncommon::start_data_table().
 5013: 	&Apache::loncommon::start_data_table_header_row().
 5014: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 5015: 	'<th>'.&nameUserString('header').'</th>'.
 5016: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 5017: 	'<th>'.&nameUserString('header').'</th>'.
 5018: 	&Apache::loncommon::end_data_table_header_row();
 5019:  
 5020:     my (undef,undef,$fullname) = &getclasslist($getsec,'1',$getgroup);
 5021:     my $ptr = 1;
 5022:     foreach my $student (sort 
 5023: 			 {
 5024: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 5025: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 5026: 			     }
 5027: 			     return $a cmp $b;
 5028: 			 } (keys(%$fullname))) {
 5029: 	my ($uname,$udom) = split(/:/,$student);
 5030: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 5031:                                   : '</td>');
 5032: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 5033: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 5034: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 5035: 	$studentTable.=
 5036: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 5037:                          : '');
 5038: 	$ptr++;
 5039:     }
 5040:     if ($ptr%2 == 0) {
 5041: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 5042: 	    &Apache::loncommon::end_data_table_row();
 5043:     }
 5044:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 5045:     $studentTable.='<input type="button" '.
 5046:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 5047: 
 5048:     $request->print($studentTable);
 5049: 
 5050:     return '';
 5051: }
 5052: 
 5053: sub getSymbMap {
 5054:     my ($map_error) = @_;
 5055:     my $navmap = Apache::lonnavmaps::navmap->new();
 5056:     unless (ref($navmap)) {
 5057:         if (ref($map_error)) {
 5058:             $$map_error = 'navmap';
 5059:         }
 5060:         return;
 5061:     }
 5062:     my %symbx = ();
 5063:     my @titles = ();
 5064:     my $minder = 0;
 5065: 
 5066:     # Gather every sequence that has problems.
 5067:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 5068: 					       1,0,1);
 5069:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 5070: 	if ($navmap->hasResource($sequence, sub { shift->is_gradable(); }, 0) ) {
 5071: 	    my $title = $minder.'.'.
 5072: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 5073: 	    push(@titles, $title); # minder in case two titles are identical
 5074: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 5075: 	    $minder++;
 5076: 	}
 5077:     }
 5078:     return \@titles,\%symbx;
 5079: }
 5080: 
 5081: #
 5082: #--- Displays a page/sequence w/wo problems, w/wo submissions
 5083: sub displayPage {
 5084:     my ($request,$symb) = @_;
 5085:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5086:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5087:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5088:     my $pageTitle = $env{'form.page'};
 5089:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5090:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5091:     my $usec=$classlist->{$env{'form.student'}}[5];
 5092: 
 5093:     #need to make sure we have the correct data for later EXT calls, 
 5094:     #thus invalidate the cache
 5095:     &Apache::lonnet::devalidatecourseresdata(
 5096:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 5097:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 5098:     &Apache::lonnet::clear_EXT_cache_status();
 5099: 
 5100:     if (!&canview($usec)) {
 5101:         $request->print(
 5102:             '<span class="LC_warning">'.
 5103:             &mt('Unable to view requested student. ([_1])',
 5104:                     $env{'form.student'}).
 5105:             '</span>');
 5106:         return;
 5107:     }
 5108:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5109:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 5110: 	'</h3>'."\n";
 5111:     $env{'form.CODE'} = uc($env{'form.CODE'});
 5112:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 5113: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 5114:     } else {
 5115: 	delete($env{'form.CODE'});
 5116:     }
 5117:     &sub_page_js($request);
 5118:     $request->print($result);
 5119: 
 5120:     my $navmap = Apache::lonnavmaps::navmap->new();
 5121:     unless (ref($navmap)) {
 5122:         $request->print(&navmap_errormsg());
 5123:         return;
 5124:     }
 5125:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 5126:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5127:     if (!$map) {
 5128: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 5129: 	return; 
 5130:     }
 5131:     my $iterator = $navmap->getIterator($map->map_start(),
 5132: 					$map->map_finish());
 5133: 
 5134:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 5135: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 5136: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 5137: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 5138: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 5139: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 5140: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 5141: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
 5142: 
 5143:     if (defined($env{'form.CODE'})) {
 5144: 	$studentTable.=
 5145: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 5146:     }
 5147:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 5148: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 5149: 
 5150:     $studentTable.='&nbsp;<span class="LC_info">'.
 5151:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 5152:         '</span>'."\n".
 5153: 	&Apache::loncommon::start_data_table().
 5154: 	&Apache::loncommon::start_data_table_header_row().
 5155: 	'<th>'.&mt('Prob.').'</th>'.
 5156: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 5157: 	&Apache::loncommon::end_data_table_header_row();
 5158: 
 5159:     &Apache::lonxml::clear_problem_counter();
 5160:     my ($depth,$question,$prob) = (1,1,1);
 5161:     $iterator->next(); # skip the first BEGIN_MAP
 5162:     my $curRes = $iterator->next(); # for "current resource"
 5163:     while ($depth > 0) {
 5164:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5165:         if($curRes == $iterator->END_MAP) { $depth--; }
 5166: 
 5167:         if (ref($curRes) && $curRes->is_gradable()) {
 5168: 	    my $parts = $curRes->parts();
 5169:             my $title = $curRes->compTitle();
 5170: 	    my $symbx = $curRes->symb();
 5171:             my $is_tool = ($symbx =~ /ext\.tool$/);
 5172: 	    $studentTable.=
 5173: 		&Apache::loncommon::start_data_table_row().
 5174: 		'<td align="center" valign="top" >'.$prob.
 5175: 		(scalar(@{$parts}) == 1 ? '' 
 5176: 		                        : '<br />('.&mt('[_1]parts',
 5177: 							scalar(@{$parts}).'&nbsp;').')'
 5178: 		 ).
 5179: 		 '</td>';
 5180: 	    $studentTable.='<td valign="top">';
 5181: 	    my %form = ('CODE' => $env{'form.CODE'},);
 5182:             if ($is_tool) {
 5183:                 $studentTable.='&nbsp;<b>'.$title.'</b><br />';
 5184:             } else {
 5185: 	        if ($env{'form.vProb'} eq 'yes' ) {
 5186: 		    $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 5187: 					         undef,'both',\%form);
 5188: 	        } else {
 5189: 		    my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 5190: 		    $companswer =~ s|<form(.*?)>||g;
 5191: 		    $companswer =~ s|</form>||g;
 5192: #		    while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 5193: #		        $companswer =~ s/$1/ /ms;
 5194: #		        $request->print('match='.$1."<br />\n");
 5195: #		    }
 5196: #		    $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 5197: 		    $studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 5198: 		}
 5199: 	    }
 5200: 
 5201: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 5202: 
 5203: 	    if ($env{'form.lastSub'} eq 'datesub') {
 5204: 		if ($record{'version'} eq '') {
 5205:                     my $msg = &mt('No recorded submission for this problem.');
 5206:                     if ($is_tool) {
 5207:                         $msg = &mt('No recorded transactions for this external tool');
 5208:                     }
 5209: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.$msg.'</span><br />';
 5210: 		} else {
 5211: 		    my %responseType = ();
 5212: 		    foreach my $partid (@{$parts}) {
 5213: 			my @responseIds =$curRes->responseIds($partid);
 5214: 			my @responseType =$curRes->responseType($partid);
 5215: 			my %responseIds;
 5216: 			for (my $i=0;$i<=$#responseIds;$i++) {
 5217: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 5218: 			}
 5219: 			$responseType{$partid} = \%responseIds;
 5220: 		    }
 5221: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 5222: 		}
 5223: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 5224: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 5225:                 my $identifier = (&canmodify($usec)? $prob : ''); 
 5226: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 5227: 									$env{'request.course.id'},
 5228: 									'','.submission',undef,
 5229:                                                                         $usec,$identifier);
 5230:  
 5231: 	    }
 5232: 	    if (&canmodify($usec)) {
 5233:             $studentTable.=&gradeBox_start();
 5234: 		foreach my $partid (@{$parts}) {
 5235: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 5236: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 5237: 		    $question++;
 5238: 		}
 5239:             $studentTable.=&gradeBox_end();
 5240: 		$prob++;
 5241: 	    }
 5242: 	    $studentTable.='</td></tr>';
 5243: 
 5244: 	}
 5245:         $curRes = $iterator->next();
 5246:     }
 5247: 
 5248:     $studentTable.=
 5249:         '</table>'."\n".
 5250:         '<input type="button" value="'.&mt('Save').'" '.
 5251:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 5252:         '</form>'."\n";
 5253:     $request->print($studentTable);
 5254: 
 5255:     return '';
 5256: }
 5257: 
 5258: sub displaySubByDates {
 5259:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 5260:     my $isCODE=0;
 5261:     my $isTask = ($symb =~/\.task$/);
 5262:     my $is_tool = ($symb =~/\.tool$/);
 5263:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 5264:     my $studentTable=&Apache::loncommon::start_data_table().
 5265: 	&Apache::loncommon::start_data_table_header_row().
 5266: 	'<th>'.&mt('Date/Time').'</th>'.
 5267: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 5268:         ($isTask?'<th>'.&mt('Version').'</th>':'').
 5269: 	'<th>'.($is_tool?&mt('Grade'):&mt('Submission')).'</th>'.
 5270: 	'<th>'.&mt('Status').'</th>'.
 5271: 	&Apache::loncommon::end_data_table_header_row();
 5272:     my ($version);
 5273:     my %mark;
 5274:     my %orders;
 5275:     $mark{'correct_by_student'} = $checkIcon;
 5276:     if (!exists($$record{'1:timestamp'})) {
 5277:         if ($is_tool) {
 5278:             return '<br />&nbsp;<span class="LC_warning">'.&mt('No grade passed back.').'</span><br />';
 5279:         } else {
 5280:             return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 5281:         }
 5282:     }
 5283: 
 5284:     my $interaction;
 5285:     my $no_increment = 1;
 5286:     my (%lastrndseed,%lasttype);
 5287:     for ($version=1;$version<=$$record{'version'};$version++) {
 5288: 	my $timestamp = 
 5289: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 5290: 	if (exists($$record{$version.':resource.0.version'})) {
 5291: 	    $interaction = $$record{$version.':resource.0.version'};
 5292: 	}
 5293:         if ($isTask && $env{'form.previousversion'}) {
 5294:             next unless ($interaction == $env{'form.previousversion'});
 5295:         }
 5296: 	my $where = ($isTask ? "$version:resource.$interaction"
 5297: 		             : "$version:resource");
 5298: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 5299: 	    '<td>'.$timestamp.'</td>';
 5300: 	if ($isCODE) {
 5301: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 5302: 	}
 5303:         if ($isTask) {
 5304:             $studentTable.='<td>'.$interaction.'</td>';
 5305:         }
 5306: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 5307: 	my @displaySub = ();
 5308: 	foreach my $partid (@{$parts}) {
 5309:             my ($hidden,$type);
 5310:             $type = $$record{$version.':resource.'.$partid.'.type'};
 5311:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
 5312:                 $hidden = 1;
 5313:             }
 5314:             my @matchKey;
 5315:             if ($isTask) {
 5316:                 @matchKey = sort(grep(/^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys));
 5317:             } elsif ($is_tool) {
 5318:                 @matchKey = sort(grep(/^resource\.\Q$partid\E\.awarded$/,@versionKeys));
 5319:             } else {
 5320:                 @matchKey = sort(grep(/^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 5321:             }
 5322: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 5323: 	    my $display_part=&get_display_part($partid,$symb);
 5324: 	    foreach my $matchKey (@matchKey) {
 5325: 		if (exists($$record{$version.':'.$matchKey}) &&
 5326: 		    $$record{$version.':'.$matchKey} ne '') {
 5327:                     if ($is_tool) {
 5328:                         $displaySub[0].=$$record{"$version:resource.$partid.awarded"};
 5329:                     } else {
 5330: 		        my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 5331: 				                   : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 5332:                         $displaySub[0].='<span class="LC_nobreak">';
 5333:                         $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 5334:                                        .' <span class="LC_internal_info">'
 5335:                                        .'('.&mt('Response ID: [_1]',$responseId).')'
 5336:                                        .'</span>'
 5337:                                        .' <b>';
 5338:                         if ($hidden) {
 5339:                             $displaySub[0].= &mt('Anonymous Survey').'</b>';
 5340:                         } else {
 5341:                             my ($trial,$rndseed,$newvariation);
 5342:                             if ($type eq 'randomizetry') {
 5343:                                 $trial = $$record{"$where.$partid.tries"};
 5344:                                 $rndseed = $$record{"$where.$partid.rndseed"};
 5345:                             }
 5346: 		            if ($$record{"$where.$partid.tries"} eq '') {
 5347: 			        $displaySub[0].=&mt('Trial not counted');
 5348: 		            } else {
 5349: 			        $displaySub[0].=&mt('Trial: [_1]',
 5350: 					        $$record{"$where.$partid.tries"});
 5351:                                 if (($rndseed ne '') && ($lastrndseed{$partid} ne '')) {
 5352:                                     if (($rndseed ne $lastrndseed{$partid}) &&
 5353:                                         (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
 5354:                                         $newvariation = '&nbsp;('.&mt('New variation this try').')';
 5355:                                     }
 5356:                                 }
 5357:                                 $lastrndseed{$partid} = $rndseed;
 5358:                                 $lasttype{$partid} = $type;
 5359: 		            }
 5360: 		            my $responseType=($isTask ? 'Task'
 5361:                                               : $responseType->{$partid}->{$responseId});
 5362: 		            if (!exists($orders{$partid})) { $orders{$partid}={}; }
 5363: 		            if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
 5364: 			        $orders{$partid}->{$responseId}=
 5365: 			            &get_order($partid,$responseId,$symb,$uname,$udom,
 5366:                                                $no_increment,$type,$trial,$rndseed);
 5367: 		            }
 5368: 		            $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
 5369: 		            $displaySub[0].='&nbsp; '.
 5370: 			        &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
 5371:                         }
 5372:                     }
 5373: 		}
 5374: 	    }
 5375: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 5376: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 5377: 				    $$record{"$where.$partid.checkedin"},
 5378: 				    $$record{"$where.$partid.checkedin.slot"}).
 5379: 					'<br />';
 5380: 	    }
 5381: 	    if (exists $$record{"$where.$partid.award"}) {
 5382: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 5383: 		    lc($$record{"$where.$partid.award"}).' '.
 5384: 		    $mark{$$record{"$where.$partid.solved"}}.
 5385: 		    '<br />';
 5386: 	    } elsif (($is_tool) && (exists($$record{"$version:resource.$partid.solved"}))) {
 5387: 		if ($$record{"$version:resource.$partid.solved"} =~ /^(in|)correct_by_passback$/) {
 5388: 		    $displaySub[1].=&mt('Grade passed back by external tool');
 5389: 		}
 5390: 	    }
 5391: 	    if (exists $$record{"$where.$partid.regrader"}) {
 5392: 		$displaySub[2].=$$record{"$where.$partid.regrader"};
 5393: 		unless ($is_tool) {
 5394: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5395: 		}
 5396: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 5397: 		$displaySub[2].=
 5398: 		    $$record{"$version:resource.$partid.regrader"};
 5399:                 unless ($is_tool) {
 5400: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5401:                 }
 5402: 	    }
 5403: 	}
 5404: 	# needed because old essay regrader has not parts info
 5405: 	if (exists $$record{"$version:resource.regrader"}) {
 5406: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 5407: 	}
 5408: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 5409: 	if ($displaySub[2]) {
 5410: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 5411: 	}
 5412: 	$studentTable.='&nbsp;</td>'.
 5413: 	    &Apache::loncommon::end_data_table_row();
 5414:     }
 5415:     $studentTable.=&Apache::loncommon::end_data_table();
 5416:     return $studentTable;
 5417: }
 5418: 
 5419: sub updateGradeByPage {
 5420:     my ($request,$symb) = @_;
 5421: 
 5422:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5423:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5424:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5425:     my $pageTitle = $env{'form.page'};
 5426:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5427:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5428:     my $usec=$classlist->{$env{'form.student'}}[5];
 5429:     if (!&canmodify($usec)) {
 5430: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 5431: 	return;
 5432:     }
 5433:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5434:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 5435: 	'</h3>'."\n";
 5436: 
 5437:     $request->print($result);
 5438: 
 5439: 
 5440:     my $navmap = Apache::lonnavmaps::navmap->new();
 5441:     unless (ref($navmap)) {
 5442:         $request->print(&navmap_errormsg());
 5443:         return;
 5444:     }
 5445:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 5446:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5447:     if (!$map) {
 5448: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 5449: 	return; 
 5450:     }
 5451:     my $iterator = $navmap->getIterator($map->map_start(),
 5452: 					$map->map_finish());
 5453: 
 5454:     my $studentTable=
 5455: 	&Apache::loncommon::start_data_table().
 5456: 	&Apache::loncommon::start_data_table_header_row().
 5457: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 5458: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 5459: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 5460: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 5461: 	&Apache::loncommon::end_data_table_header_row();
 5462: 
 5463:     $iterator->next(); # skip the first BEGIN_MAP
 5464:     my $curRes = $iterator->next(); # for "current resource"
 5465:     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
 5466:     while ($depth > 0) {
 5467:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5468:         if($curRes == $iterator->END_MAP) { $depth--; }
 5469: 
 5470:         if (ref($curRes) && $curRes->is_problem()) {
 5471: 	    my $parts = $curRes->parts();
 5472:             my $title = $curRes->compTitle();
 5473: 	    my $symbx = $curRes->symb();
 5474: 	    $studentTable.=
 5475: 		&Apache::loncommon::start_data_table_row().
 5476: 		'<td align="center" valign="top" >'.$prob.
 5477: 		(scalar(@{$parts}) == 1 ? '' 
 5478:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
 5479: 		.')').'</td>';
 5480: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 5481: 
 5482: 	    my %newrecord=();
 5483: 	    my @displayPts=();
 5484:             my %aggregate = ();
 5485:             my $aggregateflag = 0;
 5486:             if ($env{'form.HIDE'.$prob}) {
 5487:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 5488:                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
 5489:                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
 5490:                 $hideflag += $numchgs;
 5491:             }
 5492: 	    foreach my $partid (@{$parts}) {
 5493: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 5494: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 5495: 
 5496: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 5497: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 5498: 		my $partial = $newpts/$wgt;
 5499: 		my $score;
 5500: 		if ($partial > 0) {
 5501: 		    $score = 'correct_by_override';
 5502: 		} elsif ($newpts ne '') { #empty is taken as 0
 5503: 		    $score = 'incorrect_by_override';
 5504: 		}
 5505: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 5506: 		if ($dropMenu eq 'excused') {
 5507: 		    $partial = '';
 5508: 		    $score = 'excused';
 5509: 		} elsif ($dropMenu eq 'reset status'
 5510: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 5511: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 5512: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 5513: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 5514: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 5515: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 5516: 		    $changeflag++;
 5517: 		    $newpts = '';
 5518:                     
 5519:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 5520:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 5521:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 5522:                     if ($aggtries > 0) {
 5523:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 5524:                         $aggregateflag = 1;
 5525:                     }
 5526: 		}
 5527: 		my $display_part=&get_display_part($partid,$curRes->symb());
 5528: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 5529: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5530: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 5531: 		    '&nbsp;<br />';
 5532: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5533: 		     (($score eq 'excused') ? 'excused' : $newpts).
 5534: 		    '&nbsp;<br />';
 5535: 		$question++;
 5536: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 5537: 
 5538: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 5539: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 5540: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 5541: 		    if (scalar(keys(%newrecord)) > 0);
 5542: 
 5543: 		$changeflag++;
 5544: 	    }
 5545: 	    if (scalar(keys(%newrecord)) > 0) {
 5546: 		my %record = 
 5547: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 5548: 					     $udom,$uname);
 5549: 
 5550: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 5551: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 5552: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 5553: 		    $newrecord{'resource.CODE'} = '';
 5554: 		}
 5555: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 5556: 					$udom,$uname);
 5557: 		%record = &Apache::lonnet::restore($symbx,
 5558: 						   $env{'request.course.id'},
 5559: 						   $udom,$uname);
 5560: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 5561: 					     $cdom,$cnum,$udom,$uname);
 5562: 	    }
 5563: 	    
 5564:             if ($aggregateflag) {
 5565:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 5566:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 5567:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 5568:             }
 5569: 
 5570: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 5571: 		'<td valign="top">'.$displayPts[1].'</td>'.
 5572: 		&Apache::loncommon::end_data_table_row();
 5573: 
 5574: 	    $prob++;
 5575: 	}
 5576:         $curRes = $iterator->next();
 5577:     }
 5578: 
 5579:     $studentTable.=&Apache::loncommon::end_data_table();
 5580:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 5581: 		  &mt('The scores were changed for [quant,_1,problem].',
 5582: 		  $changeflag).'<br />');
 5583:     my $hidemsg=($hideflag == 0 ? '' :
 5584:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
 5585:                      $hideflag).'<br />');
 5586:     $request->print($hidemsg.$grademsg.$studentTable);
 5587: 
 5588:     return '';
 5589: }
 5590: 
 5591: #-------- end of section for handling grading by page/sequence ---------
 5592: #
 5593: #-------------------------------------------------------------------
 5594: 
 5595: #-------------------- Bubblesheet (Scantron) Grading -------------------
 5596: #
 5597: #------ start of section for handling grading by page/sequence ---------
 5598: 
 5599: =pod
 5600: 
 5601: =head1 Bubble sheet grading routines
 5602: 
 5603:   For this documentation:
 5604: 
 5605:    'scanline' refers to the full line of characters
 5606:    from the file that we are parsing that represents one entire sheet
 5607: 
 5608:    'bubble line' refers to the data
 5609:    representing the line of bubbles that are on the physical bubblesheet
 5610: 
 5611: 
 5612: The overall process is that a scanned in bubblesheet data is uploaded
 5613: into a course. When a user wants to grade, they select a
 5614: sequence/folder of resources, a file of bubblesheet info, and pick
 5615: one of the predefined configurations for what each scanline looks
 5616: like.
 5617: 
 5618: Next each scanline is checked for any errors of either 'missing
 5619: bubbles' (it's an error because it may have been mis-scanned
 5620: because too light bubbling), 'double bubble' (each bubble line should
 5621: have no more than one letter picked), invalid or duplicated CODE,
 5622: invalid student/employee ID
 5623: 
 5624: If the CODE option is used that determines the randomization of the
 5625: homework problems, either way the student/employee ID is looked up into a
 5626: username:domain.
 5627: 
 5628: During the validation phase the instructor can choose to skip scanlines. 
 5629: 
 5630: After the validation phase, there are now 3 bubblesheet files
 5631: 
 5632:   scantron_original_filename (unmodified original file)
 5633:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 5634:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 5635: 
 5636: Also there is a separate hash nohist_scantrondata that contains extra
 5637: correction information that isn't representable in the bubblesheet
 5638: file (see &scantron_getfile() for more information)
 5639: 
 5640: After all scanlines are either valid, marked as valid or skipped, then
 5641: foreach line foreach problem in the picked sequence, an ssi request is
 5642: made that simulates a user submitting their selected letter(s) against
 5643: the homework problem.
 5644: 
 5645: =over 4
 5646: 
 5647: 
 5648: 
 5649: =item defaultFormData
 5650: 
 5651:   Returns html hidden inputs used to hold context/default values.
 5652: 
 5653:  Arguments:
 5654:   $symb - $symb of the current resource 
 5655: 
 5656: =cut
 5657: 
 5658: sub defaultFormData {
 5659:     my ($symb)=@_;
 5660:     return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />';
 5661: }
 5662: 
 5663: 
 5664: =pod 
 5665: 
 5666: =item getSequenceDropDown
 5667: 
 5668:    Return html dropdown of possible sequences to grade
 5669:  
 5670:  Arguments:
 5671:    $symb - $symb of the current resource
 5672:    $map_error - ref to scalar which will container error if
 5673:                 $navmap object is unavailable in &getSymbMap().
 5674: 
 5675: =cut
 5676: 
 5677: sub getSequenceDropDown {
 5678:     my ($symb,$map_error)=@_;
 5679:     my $result='<select name="selectpage">'."\n";
 5680:     my ($titles,$symbx) = &getSymbMap($map_error);
 5681:     if (ref($map_error)) {
 5682:         return if ($$map_error);
 5683:     }
 5684:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 5685:     my $ctr=0;
 5686:     foreach (@$titles) {
 5687: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5688: 	$result.='<option value="'.$$symbx{$_}.'" '.
 5689: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 5690: 	    '>'.$showtitle.'</option>'."\n";
 5691: 	$ctr++;
 5692:     }
 5693:     $result.= '</select>';
 5694:     return $result;
 5695: }
 5696: 
 5697: my %bubble_lines_per_response;     # no. bubble lines for each response.
 5698:                                    # key is zero-based index - 0, 1, 2 ...
 5699: 
 5700: my %first_bubble_line;             # First bubble line no. for each bubble.
 5701: 
 5702: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 5703:                                    # matchresponse or rankresponse, where 
 5704:                                    # an individual response can have multiple 
 5705:                                    # lines
 5706: 
 5707: my %responsetype_per_response;     # responsetype for each response
 5708: 
 5709: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
 5710:                                    # numbered response. Needed when randomorder
 5711:                                    # or randompick are in use. Key is ID, value 
 5712:                                    # is response number.
 5713: 
 5714: # Save and restore the bubble lines array to the form env.
 5715: 
 5716: 
 5717: sub save_bubble_lines {
 5718:     foreach my $line (keys(%bubble_lines_per_response)) {
 5719: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 5720: 	$env{"form.scantron.first_bubble_line.$line"} =
 5721: 	    $first_bubble_line{$line};
 5722:         $env{"form.scantron.sub_bubblelines.$line"} = 
 5723:             $subdivided_bubble_lines{$line};
 5724:         $env{"form.scantron.responsetype.$line"} =
 5725:             $responsetype_per_response{$line};
 5726:     }
 5727:     foreach my $resid (keys(%masterseq_id_responsenum)) {
 5728:         my $line = $masterseq_id_responsenum{$resid};
 5729:         $env{"form.scantron.residpart.$line"} = $resid;
 5730:     }
 5731: }
 5732: 
 5733: 
 5734: sub restore_bubble_lines {
 5735:     my $line = 0;
 5736:     %bubble_lines_per_response = ();
 5737:     %masterseq_id_responsenum = ();
 5738:     while ($env{"form.scantron.bubblelines.$line"}) {
 5739: 	my $value = $env{"form.scantron.bubblelines.$line"};
 5740: 	$bubble_lines_per_response{$line} = $value;
 5741: 	$first_bubble_line{$line}  =
 5742: 	    $env{"form.scantron.first_bubble_line.$line"};
 5743:         $subdivided_bubble_lines{$line} =
 5744:             $env{"form.scantron.sub_bubblelines.$line"};
 5745:         $responsetype_per_response{$line} =
 5746:             $env{"form.scantron.responsetype.$line"};
 5747:         my $id = $env{"form.scantron.residpart.$line"};
 5748:         $masterseq_id_responsenum{$id} = $line;
 5749: 	$line++;
 5750:     }
 5751: }
 5752: 
 5753: =pod 
 5754: 
 5755: =item scantron_filenames
 5756: 
 5757:    Returns a list of the scantron files in the current course 
 5758: 
 5759: =cut
 5760: 
 5761: sub scantron_filenames {
 5762:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5763:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5764:     my $getpropath = 1;
 5765:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
 5766:                                                         $cname,$getpropath);
 5767:     my @possiblenames;
 5768:     if (ref($dirlist) eq 'ARRAY') {
 5769:         foreach my $filename (sort(@{$dirlist})) {
 5770: 	    ($filename)=split(/&/,$filename);
 5771: 	    if ($filename!~/^scantron_orig_/) { next ; }
 5772: 	    $filename=~s/^scantron_orig_//;
 5773: 	    push(@possiblenames,$filename);
 5774:         }
 5775:     }
 5776:     return @possiblenames;
 5777: }
 5778: 
 5779: =pod 
 5780: 
 5781: =item scantron_uploads
 5782: 
 5783:    Returns  html drop-down list of scantron files in current course.
 5784: 
 5785:  Arguments:
 5786:    $file2grade - filename to set as selected in the dropdown
 5787: 
 5788: =cut
 5789: 
 5790: sub scantron_uploads {
 5791:     my ($file2grade) = @_;
 5792:     my $result=	'<select name="scantron_selectfile">';
 5793:     $result.="<option></option>";
 5794:     foreach my $filename (sort(&scantron_filenames())) {
 5795: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 5796:     }
 5797:     $result.="</select>";
 5798:     return $result;
 5799: }
 5800: 
 5801: =pod 
 5802: 
 5803: =item scantron_scantab
 5804: 
 5805:   Returns html drop down of the scantron formats in the scantronformat.tab
 5806:   file.
 5807: 
 5808: =cut
 5809: 
 5810: sub scantron_scantab {
 5811:     my $result='<select name="scantron_format">'."\n";
 5812:     $result.='<option></option>'."\n";
 5813:     my @lines = &Apache::lonnet::get_scantronformat_file();
 5814:     if (@lines > 0) {
 5815:         foreach my $line (@lines) {
 5816:             next if (($line =~ /^\#/) || ($line eq ''));
 5817: 	    my ($name,$descrip)=split(/:/,$line);
 5818: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 5819:         }
 5820:     }
 5821:     $result.='</select>'."\n";
 5822:     return $result;
 5823: }
 5824: 
 5825: =pod 
 5826: 
 5827: =item scantron_CODElist
 5828: 
 5829:   Returns html drop down of the saved CODE lists from current course,
 5830:   generated from earlier printings.
 5831: 
 5832: =cut
 5833: 
 5834: sub scantron_CODElist {
 5835:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5836:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5837:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5838:     my $namechoice='<option></option>';
 5839:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5840: 	if ($name =~ /^error: 2 /) { next; }
 5841: 	if ($name =~ /^type\0/) { next; }
 5842: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5843:     }
 5844:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5845:     return $namechoice;
 5846: }
 5847: 
 5848: =pod 
 5849: 
 5850: =item scantron_CODEunique
 5851: 
 5852:   Returns the html for "Each CODE to be used once" radio.
 5853: 
 5854: =cut
 5855: 
 5856: sub scantron_CODEunique {
 5857:     my $result='<span class="LC_nobreak">
 5858:                  <label><input type="radio" name="scantron_CODEunique"
 5859:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5860:                 </span>
 5861:                 <span class="LC_nobreak">
 5862:                  <label><input type="radio" name="scantron_CODEunique"
 5863:                         value="no" />'.&mt('No').' </label>
 5864:                 </span>';
 5865:     return $result;
 5866: }
 5867: 
 5868: =pod 
 5869: 
 5870: =item scantron_selectphase
 5871: 
 5872:   Generates the initial screen to start the bubblesheet process.
 5873:   Allows for - starting a grading run.
 5874:              - downloading existing scan data (original, corrected
 5875:                                                 or skipped info)
 5876: 
 5877:              - uploading new scan data
 5878: 
 5879:  Arguments:
 5880:   $r          - The Apache request object
 5881:   $file2grade - name of the file that contain the scanned data to score
 5882: 
 5883: =cut
 5884: 
 5885: sub scantron_selectphase {
 5886:     my ($r,$file2grade,$symb) = @_;
 5887:     if (!$symb) {return '';}
 5888:     my $map_error;
 5889:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 5890:     if ($map_error) {
 5891:         $r->print('<br />'.&navmap_errormsg().'<br />');
 5892:         return;
 5893:     }
 5894:     my $default_form_data=&defaultFormData($symb);
 5895:     my $file_selector=&scantron_uploads($file2grade);
 5896:     my $format_selector=&scantron_scantab();
 5897:     my $CODE_selector=&scantron_CODElist();
 5898:     my $CODE_unique=&scantron_CODEunique();
 5899:     my $result;
 5900: 
 5901:     $ssi_error = 0;
 5902: 
 5903:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'}) {
 5904: 
 5905: 	# Chunk of form to prompt for a scantron file upload.
 5906: 
 5907:         $r->print('
 5908:     <br />');
 5909:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5910:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5911:     my $csec= $env{'request.course.sec'};
 5912:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 5913:     &js_escape(\$alertmsg);
 5914:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($cdom);
 5915:     $r->print(&Apache::lonhtmlcommon::scripttag('
 5916:     function checkUpload(formname) {
 5917: 	if (formname.upfile.value == "") {
 5918: 	    alert("'.$alertmsg.'");
 5919: 	    return false;
 5920: 	}
 5921: 	formname.submit();
 5922:     }'."\n".$formatjs));
 5923:     $r->print('
 5924:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5925:                 '.$default_form_data.'
 5926:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5927:                 <input name="coursesec" type="hidden" value="'.$csec.'" />
 5928:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5929:                 <input name="command" value="scantronupload_save" type="hidden" />
 5930:               '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5931:               '.&Apache::loncommon::start_data_table_header_row().'
 5932:                 <th>
 5933:                 &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 5934:                 </th>
 5935:               '.&Apache::loncommon::end_data_table_header_row().'
 5936:               '.&Apache::loncommon::start_data_table_row().'
 5937:             <td>
 5938:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'<br />'."\n");
 5939:     if ($formatoptions) {
 5940:         $r->print('</td>
 5941:                  '.&Apache::loncommon::end_data_table_row().'
 5942:                  '.&Apache::loncommon::start_data_table_row().'
 5943:                  <td>'.$formattitle.('&nbsp;'x2).$formatoptions.'
 5944:                  </td>
 5945:                  '.&Apache::loncommon::end_data_table_row().'
 5946:                  '.&Apache::loncommon::start_data_table_row().'
 5947:                  <td>'
 5948:         );
 5949:     } else {
 5950:         $r->print(' <br />');
 5951:     }
 5952:     $r->print('<input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 5953:               </td>
 5954:              '.&Apache::loncommon::end_data_table_row().'
 5955:              '.&Apache::loncommon::end_data_table().'
 5956:              </form>'
 5957:     );
 5958: 
 5959:     }
 5960: 
 5961:     # Chunk of form to prompt for a file to grade and how:
 5962: 
 5963:     $result.= '
 5964:     <br />
 5965:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5966:     <input type="hidden" name="command" value="scantron_warning" />
 5967:     '.$default_form_data.'
 5968:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5969:        '.&Apache::loncommon::start_data_table_header_row().'
 5970:             <th colspan="2">
 5971:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5972:             </th>
 5973:        '.&Apache::loncommon::end_data_table_header_row().'
 5974:        '.&Apache::loncommon::start_data_table_row().'
 5975:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5976:        '.&Apache::loncommon::end_data_table_row().'
 5977:        '.&Apache::loncommon::start_data_table_row().'
 5978:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 5979:        '.&Apache::loncommon::end_data_table_row().'
 5980:        '.&Apache::loncommon::start_data_table_row().'
 5981:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 5982:        '.&Apache::loncommon::end_data_table_row().'
 5983:        '.&Apache::loncommon::start_data_table_row().'
 5984:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5985:        '.&Apache::loncommon::end_data_table_row().'
 5986:        '.&Apache::loncommon::start_data_table_row().'
 5987:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5988:        '.&Apache::loncommon::end_data_table_row().'
 5989:        '.&Apache::loncommon::start_data_table_row().'
 5990: 	    <td> '.&mt('Options:').' </td>
 5991:             <td>
 5992: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5993:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5994:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5995: 	    </td>
 5996:        '.&Apache::loncommon::end_data_table_row().'
 5997:        '.&Apache::loncommon::start_data_table_row().'
 5998:             <td colspan="2">
 5999:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 6000:             </td>
 6001:        '.&Apache::loncommon::end_data_table_row().'
 6002:     '.&Apache::loncommon::end_data_table().'
 6003:     </form>
 6004: ';
 6005:    
 6006:     $r->print($result);
 6007: 
 6008:     # Chunk of the form that prompts to view a scoring office file,
 6009:     # corrected file, skipped records in a file.
 6010: 
 6011:     $r->print('
 6012:    <br />
 6013:    <form action="/adm/grades" name="scantron_download">
 6014:      '.$default_form_data.'
 6015:      <input type="hidden" name="command" value="scantron_download" />
 6016:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 6017:        '.&Apache::loncommon::start_data_table_header_row().'
 6018:               <th>
 6019:                 &nbsp;'.&mt('Download a scoring office file').'
 6020:               </th>
 6021:        '.&Apache::loncommon::end_data_table_header_row().'
 6022:        '.&Apache::loncommon::start_data_table_row().'
 6023:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 6024:                 <br />
 6025:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 6026:        '.&Apache::loncommon::end_data_table_row().'
 6027:      '.&Apache::loncommon::end_data_table().'
 6028:    </form>
 6029:    <br />
 6030: ');
 6031: 
 6032:     &Apache::lonpickcode::code_list($r,2);
 6033: 
 6034:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
 6035:              $default_form_data."\n".
 6036:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 6037:              &Apache::loncommon::start_data_table_header_row()."\n".
 6038:              '<th colspan="2">
 6039:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 6040:              '</th>'."\n".
 6041:               &Apache::loncommon::end_data_table_header_row()."\n".
 6042:               &Apache::loncommon::start_data_table_row()."\n".
 6043:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 6044:               '<td> '.$sequence_selector.' </td>'.
 6045:               &Apache::loncommon::end_data_table_row()."\n".
 6046:               &Apache::loncommon::start_data_table_row()."\n".
 6047:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 6048:               '<td> '.$file_selector.' </td>'."\n".
 6049:               &Apache::loncommon::end_data_table_row()."\n".
 6050:               &Apache::loncommon::start_data_table_row()."\n".
 6051:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 6052:               '<td> '.$format_selector.' </td>'."\n".
 6053:               &Apache::loncommon::end_data_table_row()."\n".
 6054:               &Apache::loncommon::start_data_table_row()."\n".
 6055:               '<td> '.&mt('Options').' </td>'."\n".
 6056:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 6057:               &Apache::loncommon::end_data_table_row()."\n".
 6058:               &Apache::loncommon::start_data_table_row()."\n".
 6059:               '<td colspan="2">'."\n".
 6060:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 6061:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 6062:               '</td>'."\n".
 6063:               &Apache::loncommon::end_data_table_row()."\n".
 6064:               &Apache::loncommon::end_data_table()."\n".
 6065:               '</form><br />');
 6066:     return;
 6067: }
 6068: 
 6069: =pod 
 6070: 
 6071: =item username_to_idmap
 6072: 
 6073:     creates a hash keyed by student/employee ID with values of the corresponding
 6074:     student username:domain. If a single ID occurs for more than one student,
 6075:     the status of the student is checked, and if Active, the value in the hash
 6076:     will be set to the Active student.
 6077: 
 6078:   Arguments:
 6079: 
 6080:     $classlist - reference to the class list hash. This is a hash
 6081:                  keyed by student name:domain  whose elements are references
 6082:                  to arrays containing various chunks of information
 6083:                  about the student. (See loncoursedata for more info).
 6084: 
 6085:   Returns
 6086:     %idmap - the constructed hash
 6087: 
 6088: =cut
 6089: 
 6090: sub username_to_idmap {
 6091:     my ($classlist)= @_;
 6092:     my %idmap;
 6093:     foreach my $student (keys(%$classlist)) {
 6094:         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
 6095:         unless ($id eq '') {
 6096:             if (!exists($idmap{$id})) {
 6097:                 $idmap{$id} = $student;
 6098:             } else {
 6099:                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
 6100:                 if ($status eq 'Active') {
 6101:                     $idmap{$id} = $student;
 6102:                 }
 6103:             }
 6104:         }
 6105:     }
 6106:     return %idmap;
 6107: }
 6108: 
 6109: =pod
 6110: 
 6111: =item scantron_fixup_scanline
 6112: 
 6113:    Process a requested correction to a scanline.
 6114: 
 6115:   Arguments:
 6116:     $scantron_config   - hash from &Apache::lonnet::get_scantron_config()
 6117:     $scan_data         - hash of correction information 
 6118:                           (see &scantron_getfile())
 6119:     $line              - existing scanline
 6120:     $whichline         - line number of the passed in scanline
 6121:     $field             - type of change to process 
 6122:                          (either 
 6123:                           'ID'     -> correct the student/employee ID
 6124:                           'CODE'   -> correct the CODE
 6125:                           'answer' -> fixup the submitted answers)
 6126:     
 6127:    $args               - hash of additional info,
 6128:                           - 'ID' 
 6129:                                'newid' -> studentID to use in replacement
 6130:                                           of existing one
 6131:                           - 'CODE' 
 6132:                                'CODE_ignore_dup' - set to true if duplicates
 6133:                                                    should be ignored.
 6134: 	                       'CODE' - is new code or 'use_unfound'
 6135:                                         if the existing unfound code should
 6136:                                         be used as is
 6137:                           - 'answer'
 6138:                                'response' - new answer or 'none' if blank
 6139:                                'question' - the bubble line to change
 6140:                                'questionnum' - the question identifier,
 6141:                                                may include subquestion. 
 6142: 
 6143:   Returns:
 6144:     $line - the modified scanline
 6145: 
 6146:   Side effects: 
 6147:     $scan_data - may be updated
 6148: 
 6149: =cut
 6150: 
 6151: 
 6152: sub scantron_fixup_scanline {
 6153:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 6154:     if ($field eq 'ID') {
 6155: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 6156: 	    return ($line,1,'New value too large');
 6157: 	}
 6158: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 6159: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 6160: 				     $args->{'newid'});
 6161: 	}
 6162: 	substr($line,$$scantron_config{'IDstart'}-1,
 6163: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 6164: 	if ($args->{'newid'}=~/^\s*$/) {
 6165: 	    &scan_data($scan_data,"$whichline.user",
 6166: 		       $args->{'username'}.':'.$args->{'domain'});
 6167: 	}
 6168:     } elsif ($field eq 'CODE') {
 6169: 	if ($args->{'CODE_ignore_dup'}) {
 6170: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 6171: 	}
 6172: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 6173: 	if ($args->{'CODE'} ne 'use_unfound') {
 6174: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 6175: 		return ($line,1,'New CODE value too large');
 6176: 	    }
 6177: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 6178: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 6179: 	    }
 6180: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 6181: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 6182: 	}
 6183:     } elsif ($field eq 'answer') {
 6184: 	my $length=$scantron_config->{'Qlength'};
 6185: 	my $off=$scantron_config->{'Qoff'};
 6186: 	my $on=$scantron_config->{'Qon'};
 6187: 	my $answer=${off}x$length;
 6188: 	if ($args->{'response'} eq 'none') {
 6189: 	    &scan_data($scan_data,
 6190: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 6191: 	} else {
 6192: 	    if ($on eq 'letter') {
 6193: 		my @alphabet=('A'..'Z');
 6194: 		$answer=$alphabet[$args->{'response'}];
 6195: 	    } elsif ($on eq 'number') {
 6196: 		$answer=$args->{'response'}+1;
 6197: 		if ($answer == 10) { $answer = '0'; }
 6198: 	    } else {
 6199: 		substr($answer,$args->{'response'},1)=$on;
 6200: 	    }
 6201: 	    &scan_data($scan_data,
 6202: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 6203: 	}
 6204: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 6205: 	substr($line,$where-1,$length)=$answer;
 6206:     }
 6207:     return $line;
 6208: }
 6209: 
 6210: =pod
 6211: 
 6212: =item scan_data
 6213: 
 6214:     Edit or look up  an item in the scan_data hash.
 6215: 
 6216:   Arguments:
 6217:     $scan_data  - The hash (see scantron_getfile)
 6218:     $key        - shorthand of the key to edit (actual key is
 6219:                   scantronfilename_key).
 6220:     $data        - New value of the hash entry.
 6221:     $delete      - If true, the entry is removed from the hash.
 6222: 
 6223:   Returns:
 6224:     The new value of the hash table field (undefined if deleted).
 6225: 
 6226: =cut
 6227: 
 6228: 
 6229: sub scan_data {
 6230:     my ($scan_data,$key,$value,$delete)=@_;
 6231:     my $filename=$env{'form.scantron_selectfile'};
 6232:     if (defined($value)) {
 6233: 	$scan_data->{$filename.'_'.$key} = $value;
 6234:     }
 6235:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 6236:     return $scan_data->{$filename.'_'.$key};
 6237: }
 6238: 
 6239: # ----- These first few routines are general use routines.----
 6240: 
 6241: # Return the number of occurences of a pattern in a string.
 6242: 
 6243: sub occurence_count {
 6244:     my ($string, $pattern) = @_;
 6245: 
 6246:     my @matches = ($string =~ /$pattern/g);
 6247: 
 6248:     return scalar(@matches);
 6249: }
 6250: 
 6251: 
 6252: # Take a string known to have digits and convert all the
 6253: # digits into letters in the range J,A..I.
 6254: 
 6255: sub digits_to_letters {
 6256:     my ($input) = @_;
 6257: 
 6258:     my @alphabet = ('J', 'A'..'I');
 6259: 
 6260:     my @input    = split(//, $input);
 6261:     my $output ='';
 6262:     for (my $i = 0; $i < scalar(@input); $i++) {
 6263: 	if ($input[$i] =~ /\d/) {
 6264: 	    $output .= $alphabet[$input[$i]];
 6265: 	} else {
 6266: 	    $output .= $input[$i];
 6267: 	}
 6268:     }
 6269:     return $output;
 6270: }
 6271: 
 6272: =pod 
 6273: 
 6274: =item scantron_parse_scanline
 6275: 
 6276:   Decodes a scanline from the selected bubblesheet file
 6277: 
 6278:  Arguments:
 6279:     line             - The text of the bubblesheet file line to process
 6280:     whichline        - Line number
 6281:     scantron_config  - Hash describing the format of the bubblesheet lines.
 6282:     scan_data        - Hash of extra information about the scanline
 6283:                        (see scantron_getfile for more information)
 6284:     just_header      - True if should not process question answers but only
 6285:                        the stuff to the left of the answers.
 6286:     randomorder      - True if randomorder in use
 6287:     randompick       - True if randompick in use
 6288:     sequence         - Exam folder URL
 6289:     master_seq       - Ref to array containing symbs in exam folder
 6290:     symb_to_resource - Ref to hash of symbs for resources in exam folder
 6291:                        (corresponding values are resource objects)
 6292:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
 6293:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
 6294:                        are refs to an array of resource objects, ordered
 6295:                        according to order used for CODE, when randomorder
 6296:                        and or randompick are in use.
 6297:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
 6298:                        for current line to question number used for same question
 6299:                         in "Master Sequence" (as seen by Course Coordinator).
 6300:     startline        - Ref to hash where key is question number (0 is first)
 6301:                        and value is number of first bubble line for current 
 6302:                        student or code-based randompick and/or randomorder.
 6303:     totalref         - Ref of scalar used to score total number of bubble
 6304:                        lines needed for responses in a scan line (used when
 6305:                        randompick in use. 
 6306:     
 6307:  Returns:
 6308:    Hash containing the result of parsing the scanline
 6309: 
 6310:    Keys are all proceeded by the string 'scantron.'
 6311: 
 6312:        CODE    - the CODE in use for this scanline
 6313:        useCODE - 1 if the CODE is invalid but it usage has been forced
 6314:                  by the operator
 6315:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 6316:                             CODEs were selected, but the usage has been
 6317:                             forced by the operator
 6318:        ID  - student/employee ID
 6319:        PaperID - if used, the ID number printed on the sheet when the 
 6320:                  paper was scanned
 6321:        FirstName - first name from the sheet
 6322:        LastName  - last name from the sheet
 6323: 
 6324:      if just_header was not true these key may also exist
 6325: 
 6326:        missingerror - a list of bubble ranges that are considered to be answers
 6327:                       to a single question that don't have any bubbles filled in.
 6328:                       Of the form questionnumber:firstbubblenumber:count.
 6329:        doubleerror  - a list of bubble ranges that are considered to be answers
 6330:                       to a single question that have more than one bubble filled in.
 6331:                       Of the form questionnumber::firstbubblenumber:count
 6332:    
 6333:                 In the above, count is the number of bubble responses in the
 6334:                 input line needed to represent the possible answers to the question.
 6335:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 6336:                 per line would have count = 2.
 6337: 
 6338:        maxquest     - the number of the last bubble line that was parsed
 6339: 
 6340:        (<number> starts at 1)
 6341:        <number>.answer - zero or more letters representing the selected
 6342:                          letters from the scanline for the bubble line 
 6343:                          <number>.
 6344:                          if blank there was either no bubble or there where
 6345:                          multiple bubbles, (consult the keys missingerror and
 6346:                          doubleerror if this is an error condition)
 6347: 
 6348: =cut
 6349: 
 6350: sub scantron_parse_scanline {
 6351:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
 6352:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
 6353:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
 6354: 
 6355:     my %record;
 6356:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
 6357:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 6358: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 6359: 	if ($$scantron_config{'CODElocation'} < 0 ||
 6360: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 6361: 	    $$scantron_config{'CODElocation'} eq 'number') {
 6362: 	    $record{'scantron.CODE'}=substr($data,
 6363: 					    $$scantron_config{'CODEstart'}-1,
 6364: 					    $$scantron_config{'CODElength'});
 6365: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 6366: 		$record{'scantron.useCODE'}=1;
 6367: 	    }
 6368: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 6369: 		$record{'scantron.CODE_ignore_dup'}=1;
 6370: 	    }
 6371: 	} else {
 6372: 	    #FIXME interpret first N questions
 6373: 	}
 6374:     }
 6375:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 6376: 				  $$scantron_config{'IDlength'});
 6377:     $record{'scantron.PaperID'}=
 6378: 	substr($data,$$scantron_config{'PaperID'}-1,
 6379: 	       $$scantron_config{'PaperIDlength'});
 6380:     $record{'scantron.FirstName'}=
 6381: 	substr($data,$$scantron_config{'FirstName'}-1,
 6382: 	       $$scantron_config{'FirstNamelength'});
 6383:     $record{'scantron.LastName'}=
 6384: 	substr($data,$$scantron_config{'LastName'}-1,
 6385: 	       $$scantron_config{'LastNamelength'});
 6386:     if ($just_header) { return \%record; }
 6387: 
 6388:     my @alphabet=('A'..'Z');
 6389:     my $questnum=0;
 6390:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 6391: 
 6392:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 6393:     if ($randompick || $randomorder) {
 6394:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
 6395:                                          $master_seq,$symb_to_resource,
 6396:                                          $partids_by_symb,$orderedforcode,
 6397:                                          $respnumlookup,$startline);
 6398:         if ($total) {
 6399:             $lastpos = $total*$$scantron_config{'Qlength'}; 
 6400:         }
 6401:         if (ref($totalref)) {
 6402:             $$totalref = $total;
 6403:         }
 6404:     }
 6405:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 6406:     chomp($questions);		# Get rid of any trailing \n.
 6407:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 6408:     while (length($questions)) {
 6409:         my $answers_needed;
 6410:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6411:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
 6412:         } else {
 6413: 	    $answers_needed = $bubble_lines_per_response{$questnum};
 6414:         }
 6415:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 6416:                              || 1;
 6417:         $questnum++;
 6418:         my $quest_id = $questnum;
 6419:         my $currentquest = substr($questions,0,$answer_length);
 6420:         $questions       = substr($questions,$answer_length);
 6421:         if (length($currentquest) < $answer_length) { next; }
 6422: 
 6423:         my $subdivided;
 6424:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6425:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
 6426:         } else {
 6427:             $subdivided = $subdivided_bubble_lines{$questnum-1};
 6428:         }
 6429:         if ($subdivided =~ /,/) {
 6430:             my $subquestnum = 1;
 6431:             my $subquestions = $currentquest;
 6432:             my @subanswers_needed = split(/,/,$subdivided);
 6433:             foreach my $subans (@subanswers_needed) {
 6434:                 my $subans_length =
 6435:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 6436:                 my $currsubquest = substr($subquestions,0,$subans_length);
 6437:                 $subquestions   = substr($subquestions,$subans_length);
 6438:                 $quest_id = "$questnum.$subquestnum";
 6439:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 6440:                     ($$scantron_config{'Qon'} eq 'number')) {
 6441:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 6442:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6443:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6444:                         $randomorder,$randompick,$respnumlookup);
 6445:                 } else {
 6446:                     $ansnum = &scantron_validator_positional($ansnum,
 6447:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6448:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6449:                         $randomorder,$randompick,$respnumlookup);
 6450:                 }
 6451:                 $subquestnum ++;
 6452:             }
 6453:         } else {
 6454:             if (($$scantron_config{'Qon'} eq 'letter') ||
 6455:                 ($$scantron_config{'Qon'} eq 'number')) {
 6456:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 6457:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6458:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6459:                     $randomorder,$randompick,$respnumlookup);
 6460:             } else {
 6461:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 6462:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6463:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6464:                     $randomorder,$randompick,$respnumlookup);
 6465:             }
 6466:         }
 6467:     }
 6468:     $record{'scantron.maxquest'}=$questnum;
 6469:     return \%record;
 6470: }
 6471: 
 6472: sub get_master_seq {
 6473:     my ($resources,$master_seq,$symb_to_resource) = @_;
 6474:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') && 
 6475:                    (ref($symb_to_resource) eq 'HASH'));
 6476:     my $resource_error;
 6477:     foreach my $resource (@{$resources}) {
 6478:         my $ressymb;
 6479:         if (ref($resource)) {
 6480:             $ressymb = $resource->symb();
 6481:             push(@{$master_seq},$ressymb);
 6482:             $symb_to_resource->{$ressymb} = $resource;
 6483:         } else {
 6484:             $resource_error = 1;
 6485:             last;
 6486:         }
 6487:     }
 6488:     return $resource_error;
 6489: }
 6490: 
 6491: sub get_respnum_lookups {
 6492:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
 6493:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
 6494:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
 6495:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
 6496:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
 6497:                    (ref($startline) eq 'HASH'));
 6498:     my ($user,$scancode);
 6499:     if ((exists($record->{'scantron.CODE'})) &&
 6500:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
 6501:         $scancode = $record->{'scantron.CODE'};
 6502:     } else {
 6503:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
 6504:     }
 6505:     my @mapresources =
 6506:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
 6507:                      $orderedforcode);
 6508:     my $total = 0;
 6509:     my $count = 0;
 6510:     foreach my $resource (@mapresources) {
 6511:         my $id = $resource->id();
 6512:         my $symb = $resource->symb();
 6513:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
 6514:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
 6515:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
 6516:                 if ($respnum ne '') {
 6517:                     $respnumlookup->{$count} = $respnum;
 6518:                     $startline->{$count} = $total;
 6519:                     $total += $bubble_lines_per_response{$respnum};
 6520:                     $count ++;
 6521:                 }
 6522:             }
 6523:         }
 6524:     }
 6525:     return $total;
 6526: }
 6527: 
 6528: sub scantron_validator_lettnum {
 6529:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 6530:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
 6531:         $randompick,$respnumlookup) = @_;
 6532: 
 6533:     # Qon 'letter' implies for each slot in currquest we have:
 6534:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 6535:     #    about anything else (esp. a value of Qoff) for missing
 6536:     #    bubbles.
 6537:     #
 6538:     # Qon 'number' implies each slot gives a digit that indexes the
 6539:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 6540:     #    and * or ? for double bubbles on a single line.
 6541:     #
 6542: 
 6543:     my $matchon;
 6544:     if ($$scantron_config{'Qon'} eq 'letter') {
 6545:         $matchon = '[A-Z]';
 6546:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 6547:         $matchon = '\d';
 6548:     }
 6549:     my $occurrences = 0;
 6550:     my $responsenum = $questnum-1;
 6551:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6552:        $responsenum = $respnumlookup->{$questnum-1} 
 6553:     }
 6554:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6555:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6556:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6557:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6558:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6559:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6560:         my @singlelines = split('',$currquest);
 6561:         foreach my $entry (@singlelines) {
 6562:             $occurrences = &occurence_count($entry,$matchon);
 6563:             if ($occurrences > 1) {
 6564:                 last;
 6565:             }
 6566:         }
 6567:     } else {
 6568:         $occurrences = &occurence_count($currquest,$matchon); 
 6569:     }
 6570:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 6571:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6572:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6573:             my $bubble = substr($currquest,$ans,1);
 6574:             if ($bubble =~ /$matchon/ ) {
 6575:                 if ($$scantron_config{'Qon'} eq 'number') {
 6576:                     if ($bubble == 0) {
 6577:                         $bubble = 10; 
 6578:                     }
 6579:                     $record->{"scantron.$ansnum.answer"} = 
 6580:                         $alphabet->[$bubble-1];
 6581:                 } else {
 6582:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 6583:                 }
 6584:             } else {
 6585:                 $record->{"scantron.$ansnum.answer"}='';
 6586:             }
 6587:             $ansnum++;
 6588:         }
 6589:     } elsif (!defined($currquest)
 6590:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 6591:             || (&occurence_count($currquest,$matchon) == 0)) {
 6592:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6593:             $record->{"scantron.$ansnum.answer"}='';
 6594:             $ansnum++;
 6595:         }
 6596:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6597:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 6598:         }
 6599:     } else {
 6600:         if ($$scantron_config{'Qon'} eq 'number') {
 6601:             $currquest = &digits_to_letters($currquest);            
 6602:         }
 6603:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6604:             my $bubble = substr($currquest,$ans,1);
 6605:             $record->{"scantron.$ansnum.answer"} = $bubble;
 6606:             $ansnum++;
 6607:         }
 6608:     }
 6609:     return $ansnum;
 6610: }
 6611: 
 6612: sub scantron_validator_positional {
 6613:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 6614:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
 6615:         $randomorder,$randompick,$respnumlookup) = @_;
 6616: 
 6617:     # Otherwise there's a positional notation;
 6618:     # each bubble line requires Qlength items, and there are filled in
 6619:     # bubbles for each case where there 'Qon' characters.
 6620:     #
 6621: 
 6622:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 6623: 
 6624:     # If the split only gives us one element.. the full length of the
 6625:     # answer string, no bubbles are filled in:
 6626: 
 6627:     if ($answers_needed eq '') {
 6628:         return;
 6629:     }
 6630: 
 6631:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 6632:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6633:             $record->{"scantron.$ansnum.answer"}='';
 6634:             $ansnum++;
 6635:         }
 6636:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6637:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 6638:         }
 6639:     } elsif (scalar(@array) == 2) {
 6640:         my $location = length($array[0]);
 6641:         my $line_num = int($location / $$scantron_config{'Qlength'});
 6642:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 6643:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6644:             if ($ans eq $line_num) {
 6645:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 6646:             } else {
 6647:                 $record->{"scantron.$ansnum.answer"} = ' ';
 6648:             }
 6649:             $ansnum++;
 6650:          }
 6651:     } else {
 6652:         #  If there's more than one instance of a bubble character
 6653:         #  That's a double bubble; with positional notation we can
 6654:         #  record all the bubbles filled in as well as the
 6655:         #  fact this response consists of multiple bubbles.
 6656:         #
 6657:         my $responsenum = $questnum-1;
 6658:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6659:             $responsenum = $respnumlookup->{$questnum-1}
 6660:         }
 6661:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6662:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6663:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6664:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6665:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6666:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6667:             my $doubleerror = 0;
 6668:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 6669:                    (!$doubleerror)) {
 6670:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 6671:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 6672:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 6673:                if (length(@currarray) > 2) {
 6674:                    $doubleerror = 1;
 6675:                } 
 6676:             }
 6677:             if ($doubleerror) {
 6678:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6679:             }
 6680:         } else {
 6681:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6682:         }
 6683:         my $item = $ansnum;
 6684:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6685:             $record->{"scantron.$item.answer"} = '';
 6686:             $item ++;
 6687:         }
 6688: 
 6689:         my @ans=@array;
 6690:         my $i=0;
 6691:         my $increment = 0;
 6692:         while ($#ans) {
 6693:             $i+=length($ans[0]) + $increment;
 6694:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 6695:             my $bubble = $i%$$scantron_config{'Qlength'};
 6696:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 6697:             shift(@ans);
 6698:             $increment = 1;
 6699:         }
 6700:         $ansnum += $answers_needed;
 6701:     }
 6702:     return $ansnum;
 6703: }
 6704: 
 6705: =pod
 6706: 
 6707: =item scantron_add_delay
 6708: 
 6709:    Adds an error message that occurred during the grading phase to a
 6710:    queue of messages to be shown after grading pass is complete
 6711: 
 6712:  Arguments:
 6713:    $delayqueue  - arrary ref of hash ref of error messages
 6714:    $scanline    - the scanline that caused the error
 6715:    $errormesage - the error message
 6716:    $errorcode   - a numeric code for the error
 6717: 
 6718:  Side Effects:
 6719:    updates the $delayqueue to have a new hash ref of the error
 6720: 
 6721: =cut
 6722: 
 6723: sub scantron_add_delay {
 6724:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 6725:     push(@$delayqueue,
 6726: 	 {'line' => $scanline, 'emsg' => $errormessage,
 6727: 	  'ecode' => $errorcode }
 6728: 	 );
 6729: }
 6730: 
 6731: =pod
 6732: 
 6733: =item scantron_find_student
 6734: 
 6735:    Finds the username for the current scanline
 6736: 
 6737:   Arguments:
 6738:    $scantron_record - hash result from scantron_parse_scanline
 6739:    $scan_data       - hash of correction information 
 6740:                       (see &scantron_getfile() form more information)
 6741:    $idmap           - hash from &username_to_idmap()
 6742:    $line            - number of current scanline
 6743:  
 6744:   Returns:
 6745:    Either 'username:domain' or undef if unknown
 6746: 
 6747: =cut
 6748: 
 6749: sub scantron_find_student {
 6750:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 6751:     my $scanID=$$scantron_record{'scantron.ID'};
 6752:     if ($scanID =~ /^\s*$/) {
 6753:  	return &scan_data($scan_data,"$line.user");
 6754:     }
 6755:     foreach my $id (keys(%$idmap)) {
 6756:  	if (lc($id) eq lc($scanID)) {
 6757:  	    return $$idmap{$id};
 6758:  	}
 6759:     }
 6760:     return undef;
 6761: }
 6762: 
 6763: =pod
 6764: 
 6765: =item scantron_filter
 6766: 
 6767:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 6768:    hidden resources was selected
 6769: 
 6770: =cut
 6771: 
 6772: sub scantron_filter {
 6773:     my ($curres)=@_;
 6774: 
 6775:     if (ref($curres) && $curres->is_problem()) {
 6776: 	# if the user has asked to not have either hidden
 6777: 	# or 'randomout' controlled resources to be graded
 6778: 	# don't include them
 6779: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6780: 	    && $curres->randomout) {
 6781: 	    return 0;
 6782: 	}
 6783: 	return 1;
 6784:     }
 6785:     return 0;
 6786: }
 6787: 
 6788: =pod
 6789: 
 6790: =item scantron_process_corrections
 6791: 
 6792:    Gets correction information out of submitted form data and corrects
 6793:    the scanline
 6794: 
 6795: =cut
 6796: 
 6797: sub scantron_process_corrections {
 6798:     my ($r) = @_;
 6799:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 6800:     my ($scanlines,$scan_data)=&scantron_getfile();
 6801:     my $classlist=&Apache::loncoursedata::get_classlist();
 6802:     my $which=$env{'form.scantron_line'};
 6803:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 6804:     my ($skip,$err,$errmsg);
 6805:     if ($env{'form.scantron_skip_record'}) {
 6806: 	$skip=1;
 6807:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 6808: 	my $newstudent=$env{'form.scantron_username'}.':'.
 6809: 	    $env{'form.scantron_domain'};
 6810: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 6811: 	($line,$err,$errmsg)=
 6812: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6813: 				     'ID',{'newid'=>$newid,
 6814: 				    'username'=>$env{'form.scantron_username'},
 6815: 				    'domain'=>$env{'form.scantron_domain'}});
 6816:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 6817: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 6818: 	my $newCODE;
 6819: 	my %args;
 6820: 	if      ($resolution eq 'use_unfound') {
 6821: 	    $newCODE='use_unfound';
 6822: 	} elsif ($resolution eq 'use_found') {
 6823: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6824: 	} elsif ($resolution eq 'use_typed') {
 6825: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6826: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6827: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6828: 	}
 6829: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6830: 	    $args{'CODE_ignore_dup'}=1;
 6831: 	}
 6832: 	$args{'CODE'}=$newCODE;
 6833: 	($line,$err,$errmsg)=
 6834: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6835: 				     'CODE',\%args);
 6836:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6837: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6838: 	    ($line,$err,$errmsg)=
 6839: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6840: 					 $which,'answer',
 6841: 					 { 'question'=>$question,
 6842: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6843:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6844: 	    if ($err) { last; }
 6845: 	}
 6846:     }
 6847:     if ($err) {
 6848:         $r->print(
 6849:             '<p class="LC_error">'
 6850:            .&mt('Unable to accept last correction, an error occurred: [_1]',
 6851:                 $errmsg)
 6852:            .'</p>');
 6853:     } else {
 6854: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 6855: 	&scantron_putfile($scanlines,$scan_data);
 6856:     }
 6857: }
 6858: 
 6859: =pod
 6860: 
 6861: =item reset_skipping_status
 6862: 
 6863:    Forgets the current set of remember skipped scanlines (and thus
 6864:    reverts back to considering all lines in the
 6865:    scantron_skipped_<filename> file)
 6866: 
 6867: =cut
 6868: 
 6869: sub reset_skipping_status {
 6870:     my ($scanlines,$scan_data)=&scantron_getfile();
 6871:     &scan_data($scan_data,'remember_skipping',undef,1);
 6872:     &scantron_putfile(undef,$scan_data);
 6873: }
 6874: 
 6875: =pod
 6876: 
 6877: =item start_skipping
 6878: 
 6879:    Marks a scanline to be skipped. 
 6880: 
 6881: =cut
 6882: 
 6883: sub start_skipping {
 6884:     my ($scan_data,$i)=@_;
 6885:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6886:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6887: 	$remembered{$i}=2;
 6888:     } else {
 6889: 	$remembered{$i}=1;
 6890:     }
 6891:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6892: }
 6893: 
 6894: =pod
 6895: 
 6896: =item should_be_skipped
 6897: 
 6898:    Checks whether a scanline should be skipped.
 6899: 
 6900: =cut
 6901: 
 6902: sub should_be_skipped {
 6903:     my ($scanlines,$scan_data,$i)=@_;
 6904:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6905: 	# not redoing old skips
 6906: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6907: 	return 0;
 6908:     }
 6909:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6910: 
 6911:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6912: 	return 0;
 6913:     }
 6914:     return 1;
 6915: }
 6916: 
 6917: =pod
 6918: 
 6919: =item remember_current_skipped
 6920: 
 6921:    Discovers what scanlines are in the scantron_skipped_<filename>
 6922:    file and remembers them into scan_data for later use.
 6923: 
 6924: =cut
 6925: 
 6926: sub remember_current_skipped {
 6927:     my ($scanlines,$scan_data)=&scantron_getfile();
 6928:     my %to_remember;
 6929:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6930: 	if ($scanlines->{'skipped'}[$i]) {
 6931: 	    $to_remember{$i}=1;
 6932: 	}
 6933:     }
 6934: 
 6935:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6936:     &scantron_putfile(undef,$scan_data);
 6937: }
 6938: 
 6939: =pod
 6940: 
 6941: =item check_for_error
 6942: 
 6943:     Checks if there was an error when attempting to remove a specific
 6944:     scantron_.. bubblesheet data file. Prints out an error if
 6945:     something went wrong.
 6946: 
 6947: =cut
 6948: 
 6949: sub check_for_error {
 6950:     my ($r,$result)=@_;
 6951:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6952: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6953:     }
 6954: }
 6955: 
 6956: =pod
 6957: 
 6958: =item scantron_warning_screen
 6959: 
 6960:    Interstitial screen to make sure the operator has selected the
 6961:    correct options before we start the validation phase.
 6962: 
 6963: =cut
 6964: 
 6965: sub scantron_warning_screen {
 6966:     my ($button_text,$symb)=@_;
 6967:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6968:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 6969:     my $CODElist;
 6970:     if ($scantron_config{'CODElocation'} &&
 6971: 	$scantron_config{'CODEstart'} &&
 6972: 	$scantron_config{'CODElength'}) {
 6973: 	$CODElist=$env{'form.scantron_CODElist'};
 6974: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
 6975: 	$CODElist=
 6976: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6977: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6978:     }
 6979:     my $lastbubblepoints;
 6980:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 6981:         $lastbubblepoints =
 6982:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
 6983:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
 6984:     }
 6985:     return '
 6986: <p>
 6987: <span class="LC_warning">
 6988: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
 6989: </p>
 6990: <table>
 6991: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6992: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6993: '.$CODElist.$lastbubblepoints.'
 6994: </table>
 6995: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
 6996: '.&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>
 6997: ';
 6998: }
 6999: 
 7000: =pod
 7001: 
 7002: =item scantron_do_warning
 7003: 
 7004:    Check if the operator has picked something for all required
 7005:    fields. Error out if something is missing.
 7006: 
 7007: =cut
 7008: 
 7009: sub scantron_do_warning {
 7010:     my ($r,$symb)=@_;
 7011:     if (!$symb) {return '';}
 7012:     my $default_form_data=&defaultFormData($symb);
 7013:     $r->print(&scantron_form_start().$default_form_data);
 7014:     if ( $env{'form.selectpage'} eq '' ||
 7015: 	 $env{'form.scantron_selectfile'} eq '' ||
 7016: 	 $env{'form.scantron_format'} eq '' ) {
 7017: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
 7018: 	if ( $env{'form.selectpage'} eq '') {
 7019: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 7020: 	} 
 7021: 	if ( $env{'form.scantron_selectfile'} eq '') {
 7022: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
 7023: 	}
 7024: 	if ( $env{'form.scantron_format'} eq '') {
 7025: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
 7026: 	}
 7027:     } else {
 7028: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
 7029:         my ($checksec,@possibles) = &gradable_sections();
 7030:         my $gradesections;
 7031:         if ($checksec) {
 7032:             my $file=$env{'form.scantron_selectfile'};
 7033:             if (&valid_file($file)) {
 7034:                 my %bysec = &scantron_get_sections();
 7035:                 my $table;
 7036:                 if ((keys(%bysec) > 1) || ((keys(%bysec) == 1) && ((keys(%bysec))[0] ne $checksec))) {
 7037:                     $gradesections = &mt('Your current role is for section [_1].','<i>'.$checksec.'</i>').'<br />';
 7038:                     $table = &Apache::loncommon::start_data_table()."\n".
 7039:                              &Apache::loncommon::start_data_table_header_row().
 7040:                              '<th>'.&mt('Section').'</th><th>'.&mt('Number of records').'</th>'.
 7041:                               &Apache::loncommon::end_data_table_header_row()."\n";
 7042:                     if ($bysec{'none'}) {
 7043:                         $table .= &Apache::loncommon::start_data_table_row().
 7044:                                   '<td>'.&mt('None').'</td><td>'.$bysec{'none'}.'</td>'.
 7045:                                   &Apache::loncommon::end_data_table_row()."\n";
 7046:                     }
 7047:                     foreach my $sec (sort { $a <=> $b } keys(%bysec)) {
 7048:                         next if ($sec eq 'none');
 7049:                         $table .= &Apache::loncommon::start_data_table_row().
 7050:                                   '<td>'.$sec.'</td><td>'.$bysec{$sec}.'</td>'.
 7051:                                   &Apache::loncommon::end_data_table_row()."\n";
 7052:                     }
 7053:                     $table .= &Apache::loncommon::end_data_table()."\n";
 7054:                     $gradesections .= &mt('Sections represented in the bubblesheet data file (based on bubbled student IDs) are as follows:').
 7055:                                       '<p>'.$table.'</p>';
 7056:                     if (@possibles) {
 7057:                         $gradesections .= '<p>'.
 7058:                                           &mt('You have role(s) in [quant,_1,other section,other sections] with privileges to manage grades.',
 7059:                                               scalar(@possibles)).'<br />'.
 7060:                                           &mt('Check which of those section(s), in addition to section [_1], you wish to grade using this bubblesheet file:',
 7061:                                               '<i>'.$checksec.'</i>').' ';
 7062:                         foreach my $sec (sort {$a <=> $b } @possibles) {
 7063:                             $gradesections .= '<label><input type="checkbox" name="scantron_othersections" value="'.$sec.'" />'.$sec.'</label>'.('&nbsp;'x2);
 7064:                         }
 7065:                         $gradesections .= '</p>';
 7066:                     }
 7067:                 }
 7068:             } else {
 7069:                 $gradesections = '<p class="LC_error">'.&mt('The selected file is unavailable').'</p>';
 7070:             }
 7071:         }
 7072:         my $bubbledbyhand=&hand_bubble_option();
 7073: 	$r->print('
 7074: '.$warning.$gradesections.$bubbledbyhand.'
 7075: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 7076: <input type="hidden" name="command" value="scantron_validate" />
 7077: ');
 7078:     }
 7079:     $r->print("</form><br />");
 7080:     return '';
 7081: }
 7082: 
 7083: =pod
 7084: 
 7085: =item scantron_form_start
 7086: 
 7087:     html hidden input for remembering all selected grading options
 7088: 
 7089: =cut
 7090: 
 7091: sub scantron_form_start {
 7092:     my ($max_bubble)=@_;
 7093:     my $result= <<SCANTRONFORM;
 7094: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7095:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 7096:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 7097:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 7098:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 7099:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 7100:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 7101:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 7102:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 7103:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 7104: SCANTRONFORM
 7105: 
 7106:   my $line = 0;
 7107:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 7108:        my $chunk =
 7109: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 7110:        $chunk .=
 7111: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 7112:        $chunk .= 
 7113:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 7114:        $chunk .=
 7115:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 7116:        $chunk .=
 7117:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
 7118:        $result .= $chunk;
 7119:        $line++;
 7120:     }
 7121:     return $result;
 7122: }
 7123: 
 7124: =pod
 7125: 
 7126: =item scantron_validate_file
 7127: 
 7128:     Dispatch routine for doing validation of a bubblesheet data file.
 7129: 
 7130:     Also processes any necessary information resets that need to
 7131:     occur before validation begins (ignore previous corrections,
 7132:     restarting the skipped records processing)
 7133: 
 7134: =cut
 7135: 
 7136: sub scantron_validate_file {
 7137:     my ($r,$symb) = @_;
 7138:     if (!$symb) {return '';}
 7139:     my $default_form_data=&defaultFormData($symb);
 7140:     
 7141:     # do the detection of only doing skipped records first before we delete
 7142:     # them when doing the corrections reset
 7143:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 7144: 	&reset_skipping_status();
 7145:     }
 7146:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 7147: 	&remember_current_skipped();
 7148: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 7149:     }
 7150: 
 7151:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 7152: 	&check_for_error($r,&scantron_remove_file('corrected'));
 7153: 	&check_for_error($r,&scantron_remove_file('skipped'));
 7154: 	&check_for_error($r,&scantron_remove_scan_data());
 7155: 	$env{'form.scantron_options_ignore'}='done';
 7156:     }
 7157: 
 7158:     if ($env{'form.scantron_corrections'}) {
 7159: 	&scantron_process_corrections($r);
 7160:     }
 7161: 
 7162:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');
 7163:     my ($checksec,@gradable);
 7164:     if ($env{'request.course.sec'}) {
 7165:         ($checksec,my @possibles) = &gradable_sections();
 7166:         if ($checksec) {
 7167:             if (@possibles) {
 7168:                 my @chosensecs = &Apache::loncommon::get_env_multiple('form.scantron_othersections');
 7169:                 if (@chosensecs) {
 7170:                     foreach my $sec (@chosensecs) {
 7171:                         if (grep(/^\Q$sec\E$/,@possibles)) {
 7172:                             unless (grep(/^\Q$sec\E$/,@gradable)) {
 7173:                                 push(@gradable,$sec);
 7174:                             }
 7175:                         }
 7176:                     }
 7177:                 }
 7178:             }
 7179:             $r->print('<p><table>');
 7180:             if (@gradable) {
 7181:                 my @showsections = sort { $a <=> $b } (@gradable,$checksec);
 7182:                 $r->print(
 7183:                     '<tr><td><b>'.&mt('Sections to be Graded:').'</b></td><td>'.join(', ',@showsections).'</td></tr>');
 7184:             } else {
 7185:                 $r->print(
 7186:                     '<tr><td><b>'.&mt('Section to be Graded:').'</b></td><td>'.$checksec.'</td></tr>');
 7187:             }
 7188:             $r->print('</table></p>');
 7189:         }
 7190:     }
 7191:     $r->rflush();
 7192: 
 7193:     #get the student pick code ready
 7194:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 7195:     my $nav_error;
 7196:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7197:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 7198:     if ($nav_error) {
 7199:         $r->print(&navmap_errormsg());
 7200:         return '';
 7201:     }
 7202:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 7203:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 7204:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
 7205:     }
 7206:     $r->print($result);
 7207:     
 7208:     my @validate_phases=( 'sequence',
 7209: 			  'ID',
 7210: 			  'CODE',
 7211: 			  'doublebubble',
 7212: 			  'missingbubbles');
 7213:     if (!$env{'form.validatepass'}) {
 7214: 	$env{'form.validatepass'} = 0;
 7215:     }
 7216:     my $currentphase=$env{'form.validatepass'};
 7217:     my %skipbysec=();
 7218: 
 7219:     my $stop=0;
 7220:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 7221: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 7222: 	$r->rflush();
 7223:      
 7224: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 7225: 	{
 7226: 	    no strict 'refs';
 7227:             my @extras=();
 7228:             if ($validate_phases[$currentphase] eq 'ID') {
 7229:                 @extras = (\%skipbysec,$checksec,@gradable);
 7230:             }
 7231: 	    ($stop,$currentphase)=&$which($r,$currentphase,@extras);
 7232: 	}
 7233:     }
 7234:     if (!$stop) {
 7235: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
 7236:         my $secinfo;
 7237:         if (keys(%skipbysec) > 0) {
 7238:             my $seclist = '<ul>';
 7239:             foreach my $sec (sort { $a <=> $b } keys(%skipbysec)) {
 7240:                 $seclist .= '<li>'.&mt('section [_1]: [_2]',$sec,$skipbysec{$sec}).'</li>';
 7241:             }
 7242:             $seclist .= '</ul>';
 7243:             $secinfo = '<p class="LC_info">'.
 7244:                        &mt('Numbers of records for students in sections not being graded [_1]',
 7245:                            $seclist).
 7246:                        '</p>';
 7247:         }
 7248: 	$r->print(&mt('Validation process complete.').'<br />'.
 7249:                   $secinfo.$warning.
 7250:                   &mt('Perform verification for each student after storage of submissions?').
 7251:                   '&nbsp;<span class="LC_nobreak"><label>'.
 7252:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 7253:                   ('&nbsp;'x3).'<label>'.
 7254:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 7255:                   '</label></span><br />'.
 7256:                   &mt('Grading will take longer if you use verification.').'<br />'.
 7257:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
 7258:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 7259:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 7260:     } else {
 7261: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 7262: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 7263:     }
 7264:     if ($stop) {
 7265: 	if ($validate_phases[$currentphase] eq 'sequence') {
 7266: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 7267: 	    $r->print(' '.&mt('this error').' <br />');
 7268: 
 7269: 	    $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>');
 7270: 	} else {
 7271:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 7272: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 7273:             } else {
 7274:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 7275:             }
 7276: 	    $r->print(' '.&mt('using corrected info').' <br />');
 7277: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 7278: 	    $r->print(" ".&mt("this scanline saving it for later."));
 7279: 	}
 7280:     }
 7281:     $r->print(" </form><br />");
 7282:     return '';
 7283: }
 7284: 
 7285: 
 7286: =pod
 7287: 
 7288: =item scantron_remove_file
 7289: 
 7290:    Removes the requested bubblesheet data file, makes sure that
 7291:    scantron_original_<filename> is never removed
 7292: 
 7293: 
 7294: =cut
 7295: 
 7296: sub scantron_remove_file {
 7297:     my ($which)=@_;
 7298:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7299:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7300:     my $file='scantron_';
 7301:     if ($which eq 'corrected' || $which eq 'skipped') {
 7302: 	$file.=$which.'_';
 7303:     } else {
 7304: 	return 'refused';
 7305:     }
 7306:     $file.=$env{'form.scantron_selectfile'};
 7307:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 7308: }
 7309: 
 7310: 
 7311: =pod
 7312: 
 7313: =item scantron_remove_scan_data
 7314: 
 7315:    Removes all scan_data correction for the requested bubblesheet
 7316:    data file.  (In the case that both the are doing skipped records we need
 7317:    to remember the old skipped lines for the time being so that element
 7318:    persists for a while.)
 7319: 
 7320: =cut
 7321: 
 7322: sub scantron_remove_scan_data {
 7323:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7324:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7325:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 7326:     my @todelete;
 7327:     my $filename=$env{'form.scantron_selectfile'};
 7328:     foreach my $key (@keys) {
 7329: 	if ($key=~/^\Q$filename\E_/) {
 7330: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 7331: 		$key=~/remember_skipping/) {
 7332: 		next;
 7333: 	    }
 7334: 	    push(@todelete,$key);
 7335: 	}
 7336:     }
 7337:     my $result;
 7338:     if (@todelete) {
 7339: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 7340: 				       \@todelete,$cdom,$cname);
 7341:     } else {
 7342: 	$result = 'ok';
 7343:     }
 7344:     return $result;
 7345: }
 7346: 
 7347: 
 7348: =pod
 7349: 
 7350: =item scantron_getfile
 7351: 
 7352:     Fetches the requested bubblesheet data file (all 3 versions), and
 7353:     the scan_data hash
 7354:   
 7355:   Arguments:
 7356:     None
 7357: 
 7358:   Returns:
 7359:     2 hash references
 7360: 
 7361:      - first one has 
 7362:          orig      -
 7363:          corrected -
 7364:          skipped   -  each of which points to an array ref of the specified
 7365:                       file broken up into individual lines
 7366:          count     - number of scanlines
 7367:  
 7368:      - second is the scan_data hash possible keys are
 7369:        ($number refers to scanline numbered $number and thus the key affects
 7370:         only that scanline
 7371:         $bubline refers to the specific bubble line element and the aspects
 7372:         refers to that specific bubble line element)
 7373: 
 7374:        $number.user - username:domain to use
 7375:        $number.CODE_ignore_dup 
 7376:                     - ignore the duplicate CODE error 
 7377:        $number.useCODE
 7378:                     - use the CODE in the scanline as is
 7379:        $number.no_bubble.$bubline
 7380:                     - it is valid that there is no bubbled in bubble
 7381:                       at $number $bubline
 7382:        remember_skipping
 7383:                     - a frozen hash containing keys of $number and values
 7384:                       of either 
 7385:                         1 - we are on a 'do skipped records pass' and plan
 7386:                             on processing this line
 7387:                         2 - we are on a 'do skipped records pass' and this
 7388:                             scanline has been marked to skip yet again
 7389: 
 7390: =cut
 7391: 
 7392: sub scantron_getfile {
 7393:     #FIXME really would prefer a scantron directory
 7394:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7395:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7396:     my $lines;
 7397:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7398: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 7399:     my %scanlines;
 7400:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 7401:     my $temp=$scanlines{'orig'};
 7402:     $scanlines{'count'}=$#$temp;
 7403: 
 7404:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7405: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 7406:     if ($lines eq '-1') {
 7407: 	$scanlines{'corrected'}=[];
 7408:     } else {
 7409: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 7410:     }
 7411:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7412: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 7413:     if ($lines eq '-1') {
 7414: 	$scanlines{'skipped'}=[];
 7415:     } else {
 7416: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 7417:     }
 7418:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 7419:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 7420:     my %scan_data = @tmp;
 7421:     return (\%scanlines,\%scan_data);
 7422: }
 7423: 
 7424: =pod
 7425: 
 7426: =item lonnet_putfile
 7427: 
 7428:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 7429: 
 7430:  Arguments:
 7431:    $contents - data to store
 7432:    $filename - filename to store $contents into
 7433: 
 7434:  Returns:
 7435:    result value from &Apache::lonnet::finishuserfileupload
 7436: 
 7437: =cut
 7438: 
 7439: sub lonnet_putfile {
 7440:     my ($contents,$filename)=@_;
 7441:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7442:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7443:     $env{'form.sillywaytopassafilearound'}=$contents;
 7444:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 7445: 
 7446: }
 7447: 
 7448: =pod
 7449: 
 7450: =item scantron_putfile
 7451: 
 7452:     Stores the current version of the bubblesheet data files, and the
 7453:     scan_data hash. (Does not modify the original version only the
 7454:     corrected and skipped versions.
 7455: 
 7456:  Arguments:
 7457:     $scanlines - hash ref that looks like the first return value from
 7458:                  &scantron_getfile()
 7459:     $scan_data - hash ref that looks like the second return value from
 7460:                  &scantron_getfile()
 7461: 
 7462: =cut
 7463: 
 7464: sub scantron_putfile {
 7465:     my ($scanlines,$scan_data) = @_;
 7466:     #FIXME really would prefer a scantron directory
 7467:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7468:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7469:     if ($scanlines) {
 7470: 	my $prefix='scantron_';
 7471: # no need to update orig, shouldn't change
 7472: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 7473: #		    $env{'form.scantron_selectfile'});
 7474: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 7475: 			$prefix.'corrected_'.
 7476: 			$env{'form.scantron_selectfile'});
 7477: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 7478: 			$prefix.'skipped_'.
 7479: 			$env{'form.scantron_selectfile'});
 7480:     }
 7481:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 7482: }
 7483: 
 7484: =pod
 7485: 
 7486: =item scantron_get_line
 7487: 
 7488:    Returns the correct version of the scanline
 7489: 
 7490:  Arguments:
 7491:     $scanlines - hash ref that looks like the first return value from
 7492:                  &scantron_getfile()
 7493:     $scan_data - hash ref that looks like the second return value from
 7494:                  &scantron_getfile()
 7495:     $i         - number of the requested line (starts at 0)
 7496: 
 7497:  Returns:
 7498:    A scanline, (either the original or the corrected one if it
 7499:    exists), or undef if the requested scanline should be
 7500:    skipped. (Either because it's an skipped scanline, or it's an
 7501:    unskipped scanline and we are not doing a 'do skipped scanlines'
 7502:    pass.
 7503: 
 7504: =cut
 7505: 
 7506: sub scantron_get_line {
 7507:     my ($scanlines,$scan_data,$i)=@_;
 7508:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 7509:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 7510:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 7511:     return $scanlines->{'orig'}[$i]; 
 7512: }
 7513: 
 7514: =pod
 7515: 
 7516: =item scantron_todo_count
 7517: 
 7518:     Counts the number of scanlines that need processing.
 7519: 
 7520:  Arguments:
 7521:     $scanlines - hash ref that looks like the first return value from
 7522:                  &scantron_getfile()
 7523:     $scan_data - hash ref that looks like the second return value from
 7524:                  &scantron_getfile()
 7525: 
 7526:  Returns:
 7527:     $count - number of scanlines to process
 7528: 
 7529: =cut
 7530: 
 7531: sub get_todo_count {
 7532:     my ($scanlines,$scan_data)=@_;
 7533:     my $count=0;
 7534:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7535: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7536: 	if ($line=~/^[\s\cz]*$/) { next; }
 7537: 	$count++;
 7538:     }
 7539:     return $count;
 7540: }
 7541: 
 7542: =pod
 7543: 
 7544: =item scantron_put_line
 7545: 
 7546:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
 7547:     data file.
 7548: 
 7549:  Arguments:
 7550:     $scanlines - hash ref that looks like the first return value from
 7551:                  &scantron_getfile()
 7552:     $scan_data - hash ref that looks like the second return value from
 7553:                  &scantron_getfile()
 7554:     $i         - line number to update
 7555:     $newline   - contents of the updated scanline
 7556:     $skip      - if true make the line for skipping and update the
 7557:                  'skipped' file
 7558: 
 7559: =cut
 7560: 
 7561: sub scantron_put_line {
 7562:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 7563:     if ($skip) {
 7564: 	$scanlines->{'skipped'}[$i]=$newline;
 7565: 	&start_skipping($scan_data,$i);
 7566: 	return;
 7567:     }
 7568:     $scanlines->{'corrected'}[$i]=$newline;
 7569: }
 7570: 
 7571: =pod
 7572: 
 7573: =item scantron_clear_skip
 7574: 
 7575:    Remove a line from the 'skipped' file
 7576: 
 7577:  Arguments:
 7578:     $scanlines - hash ref that looks like the first return value from
 7579:                  &scantron_getfile()
 7580:     $scan_data - hash ref that looks like the second return value from
 7581:                  &scantron_getfile()
 7582:     $i         - line number to update
 7583: 
 7584: =cut
 7585: 
 7586: sub scantron_clear_skip {
 7587:     my ($scanlines,$scan_data,$i)=@_;
 7588:     if (exists($scanlines->{'skipped'}[$i])) {
 7589: 	undef($scanlines->{'skipped'}[$i]);
 7590: 	return 1;
 7591:     }
 7592:     return 0;
 7593: }
 7594: 
 7595: =pod
 7596: 
 7597: =item scantron_filter_not_exam
 7598: 
 7599:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 7600:    filter out resources that are not marked as 'exam' mode
 7601: 
 7602: =cut
 7603: 
 7604: sub scantron_filter_not_exam {
 7605:     my ($curres)=@_;
 7606:     
 7607:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 7608: 	# if the user has asked to not have either hidden
 7609: 	# or 'randomout' controlled resources to be graded
 7610: 	# don't include them
 7611: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 7612: 	    && $curres->randomout) {
 7613: 	    return 0;
 7614: 	}
 7615: 	return 1;
 7616:     }
 7617:     return 0;
 7618: }
 7619: 
 7620: =pod
 7621: 
 7622: =item scantron_validate_sequence
 7623: 
 7624:     Validates the selected sequence, checking for resource that are
 7625:     not set to exam mode.
 7626: 
 7627: =cut
 7628: 
 7629: sub scantron_validate_sequence {
 7630:     my ($r,$currentphase) = @_;
 7631: 
 7632:     my $navmap=Apache::lonnavmaps::navmap->new();
 7633:     unless (ref($navmap)) {
 7634:         $r->print(&navmap_errormsg());
 7635:         return (1,$currentphase);
 7636:     }
 7637:     my (undef,undef,$sequence)=
 7638: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7639: 
 7640:     my $map=$navmap->getResourceByUrl($sequence);
 7641: 
 7642:     $r->print('<input type="hidden" name="validate_sequence_exam"
 7643:                                     value="ignore" />');
 7644:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 7645: 	my @resources=
 7646: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 7647: 	if (@resources) {
 7648: 	    $r->print(
 7649:                 '<p class="LC_warning">'
 7650:                .&mt('Some resources in the sequence currently are not set to'
 7651:                    .' bubblesheet exam mode. Grading these resources currently may not'
 7652:                    .' work correctly.')
 7653:                .'</p>'
 7654:             );
 7655: 	    return (1,$currentphase);
 7656: 	}
 7657:     }
 7658: 
 7659:     return (0,$currentphase+1);
 7660: }
 7661: 
 7662: 
 7663: 
 7664: sub scantron_validate_ID {
 7665:     my ($r,$currentphase,$skipbysec,$checksec,@gradable) = @_;
 7666:     
 7667:     #get student info
 7668:     my $classlist=&Apache::loncoursedata::get_classlist();
 7669:     my %idmap=&username_to_idmap($classlist);
 7670:     my $secidx = &Apache::loncoursedata::CL_SECTION();
 7671: 
 7672:     #get scantron line setup
 7673:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7674:     my ($scanlines,$scan_data)=&scantron_getfile();
 7675: 
 7676:     my $nav_error;
 7677:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
 7678:     if ($nav_error) {
 7679:         $r->print(&navmap_errormsg());
 7680:         return(1,$currentphase);
 7681:     }
 7682: 
 7683:     my %found=('ids'=>{},'usernames'=>{});
 7684:     my $unsavedskips = 0;
 7685:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7686: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7687: 	if ($line=~/^[\s\cz]*$/) { next; }
 7688: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7689: 						 $scan_data);
 7690: 	my $id=$$scan_record{'scantron.ID'};
 7691: 	my $found;
 7692: 	foreach my $checkid (keys(%idmap)) {
 7693: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 7694: 	}
 7695: 	if ($found) {
 7696: 	    my $username=$idmap{$found};
 7697:             if ($checksec) {
 7698:                 if (ref($classlist->{$username}) eq 'ARRAY') {
 7699:                     my $stusec = $classlist->{$username}->[$secidx];
 7700:                     if ($stusec ne $checksec) {
 7701:                         unless ((@gradable > 0) && (grep(/^\Q$stusec\E$/,@gradable))) {
 7702:                             my $skip=1;
 7703:                             &scantron_put_line($scanlines,$scan_data,$i,$line,$skip);
 7704:                             if (ref($skipbysec) eq 'HASH') {
 7705:                                 if ($stusec eq '') {
 7706:                                     $skipbysec->{'none'} ++;
 7707:                                 } else {
 7708:                                     $skipbysec->{$stusec} ++;
 7709:                                 }
 7710:                             }
 7711:                             $unsavedskips ++;
 7712:                             next;
 7713:                         }
 7714:                     }
 7715:                 }
 7716:             }
 7717: 	    if ($found{'ids'}{$found}) {
 7718: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7719: 					 $line,'duplicateID',$found);
 7720:                 if ($unsavedskips) {
 7721:                     &scantron_putfile($scanlines,$scan_data);
 7722:                     $unsavedskips = 0;
 7723:                 }
 7724: 		return(1,$currentphase);
 7725: 	    } elsif ($found{'usernames'}{$username}) {
 7726: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7727: 					 $line,'duplicateID',$username);
 7728:                 if ($unsavedskips) {
 7729:                     &scantron_putfile($scanlines,$scan_data);
 7730:                     $unsavedskips = 0;
 7731:                 }
 7732: 		return(1,$currentphase);
 7733: 	    }
 7734: 	    #FIXME store away line we previously saw the ID on to use above
 7735: 	    $found{'ids'}{$found}++;
 7736: 	    $found{'usernames'}{$username}++;
 7737: 	} else {
 7738: 	    if ($id =~ /^\s*$/) {
 7739: 		my $username=&scan_data($scan_data,"$i.user");
 7740:                 if (($checksec && $username ne '')) {
 7741:                     if (ref($classlist->{$username}) eq 'ARRAY') {
 7742:                         my $stusec = $classlist->{$username}->[$secidx];
 7743:                         if ($stusec ne $checksec) {
 7744:                             unless ((@gradable > 0) && (grep(/^\Q$stusec\E$/,@gradable))) {
 7745:                                 my $skip=1;
 7746:                                 &scantron_put_line($scanlines,$scan_data,$i,$line,$skip);
 7747:                                 if (ref($skipbysec) eq 'HASH') {
 7748:                                     if ($stusec eq '') {
 7749:                                         $skipbysec->{'none'} ++;
 7750:                                     } else {
 7751:                                         $skipbysec->{$stusec} ++;
 7752:                                     }
 7753:                                 }
 7754:                                 $unsavedskips ++;
 7755:                                 next;
 7756:                             }
 7757:                         }
 7758:                     }
 7759: 		} elsif (defined($username) && $found{'usernames'}{$username}) {
 7760: 		    &scantron_get_correction($r,$i,$scan_record,
 7761: 					     \%scantron_config,
 7762: 					     $line,'duplicateID',$username);
 7763:                     if ($unsavedskips) {
 7764:                         &scantron_putfile($scanlines,$scan_data);
 7765:                         $unsavedskips = 0;
 7766:                     }
 7767: 		    return(1,$currentphase);
 7768: 		} elsif (!defined($username)) {
 7769: 		    &scantron_get_correction($r,$i,$scan_record,
 7770: 					     \%scantron_config,
 7771: 					     $line,'incorrectID');
 7772:                     if ($unsavedskips) {
 7773:                         &scantron_putfile($scanlines,$scan_data);
 7774:                         $unsavedskips = 0;
 7775:                     }
 7776: 		    return(1,$currentphase);
 7777: 		}
 7778: 		$found{'usernames'}{$username}++;
 7779: 	    } else {
 7780: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7781: 					 $line,'incorrectID');
 7782:                 if ($unsavedskips) {
 7783:                     &scantron_putfile($scanlines,$scan_data);
 7784:                     $unsavedskips = 0;
 7785:                 }
 7786: 		return(1,$currentphase);
 7787: 	    }
 7788: 	}
 7789:     }
 7790:     if ($unsavedskips) {
 7791:         &scantron_putfile($scanlines,$scan_data);
 7792:         $unsavedskips = 0;
 7793:     }
 7794:     return (0,$currentphase+1);
 7795: }
 7796: 
 7797: sub scantron_get_sections {
 7798:     my %bysec;
 7799:     if ($env{'form.scantron_format'} ne '') {
 7800:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7801:         my ($scanlines,$scan_data)=&scantron_getfile();
 7802:         my $classlist=&Apache::loncoursedata::get_classlist();
 7803:         my %idmap=&username_to_idmap($classlist);
 7804:         foreach my $key (keys(%idmap)) {
 7805:             my $lckey = lc($key);
 7806:             $idmap{$lckey} = $idmap{$key};
 7807:         }
 7808:         my $secidx = &Apache::loncoursedata::CL_SECTION();
 7809:         for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7810:             my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7811:             if ($line=~/^[\s\cz]*$/) { next; }
 7812:             my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7813:                                                      $scan_data);
 7814:             my $id=lc($$scan_record{'scantron.ID'});
 7815:             if (exists($idmap{$id})) {
 7816:                 if (ref($classlist->{$idmap{$id}}) eq 'ARRAY') {
 7817:                     my $stusec = $classlist->{$idmap{$id}}->[$secidx];
 7818:                     if ($stusec eq '') {
 7819:                         $bysec{'none'} ++;
 7820:                     } else {
 7821:                         $bysec{$stusec} ++;
 7822:                     }
 7823:                 }
 7824:             }
 7825:         }
 7826:     }
 7827:     return %bysec;
 7828: }
 7829: 
 7830: sub scantron_get_correction {
 7831:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
 7832:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
 7833: #FIXME in the case of a duplicated ID the previous line, probably need
 7834: #to show both the current line and the previous one and allow skipping
 7835: #the previous one or the current one
 7836: 
 7837:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 7838:         $r->print(
 7839:             '<p class="LC_warning">'
 7840:            .&mt('An error was detected ([_1]) for PaperID [_2]',
 7841:                 "<b>$error</b>",
 7842:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
 7843:            ."</p> \n");
 7844:     } else {
 7845:         $r->print(
 7846:             '<p class="LC_warning">'
 7847:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
 7848:                 "<b>$error</b>", $i, "<pre>$line</pre>")
 7849:            ."</p> \n");
 7850:     }
 7851:     my $message =
 7852:         '<p>'
 7853:        .&mt('The ID on the form is [_1]',
 7854:             "<tt>$$scan_record{'scantron.ID'}</tt>")
 7855:        .'<br />'
 7856:        .&mt('The name on the paper is [_1], [_2]',
 7857:             $$scan_record{'scantron.LastName'},
 7858:             $$scan_record{'scantron.FirstName'})
 7859:        .'</p>';
 7860: 
 7861:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 7862:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 7863:                            # Array populated for doublebubble or
 7864:     my @lines_to_correct;  # missingbubble errors to build javascript
 7865:                            # to validate radio button checking   
 7866: 
 7867:     if ($error =~ /ID$/) {
 7868: 	if ($error eq 'incorrectID') {
 7869:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
 7870: 		      "</p>\n");
 7871: 	} elsif ($error eq 'duplicateID') {
 7872:             $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 7873: 	}
 7874: 	$r->print($message);
 7875: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 7876: 	$r->print("\n<ul><li> ");
 7877: 	#FIXME it would be nice if this sent back the user ID and
 7878: 	#could do partial userID matches
 7879: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 7880: 				       'scantron_username','scantron_domain'));
 7881: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 7882: 	$r->print("\n:\n".
 7883: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 7884: 
 7885: 	$r->print('</li>');
 7886:     } elsif ($error =~ /CODE$/) {
 7887: 	if ($error eq 'incorrectCODE') {
 7888: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 7889: 	} elsif ($error eq 'duplicateCODE') {
 7890: 	    $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");
 7891: 	}
 7892: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
 7893: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
 7894:                  ."</p>\n");
 7895: 	$r->print($message);
 7896: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
 7897: 	$r->print("\n<br /> ");
 7898: 	my $i=0;
 7899: 	if ($error eq 'incorrectCODE' 
 7900: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 7901: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 7902: 	    if ($closest > 0) {
 7903: 		foreach my $testcode (@{$closest}) {
 7904: 		    my $checked='';
 7905: 		    if (!$i) { $checked=' checked="checked"'; }
 7906: 		    $r->print("
 7907:    <label>
 7908:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 7909:        ".&mt("Use the similar CODE [_1] instead.",
 7910: 	    "<b><tt>".$testcode."</tt></b>")."
 7911:     </label>
 7912:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 7913: 		    $r->print("\n<br />");
 7914: 		    $i++;
 7915: 		}
 7916: 	    }
 7917: 	}
 7918: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 7919: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 7920: 	    $r->print("
 7921:     <label>
 7922:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 7923:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
 7924: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 7925:     </label>");
 7926: 	    $r->print("\n<br />");
 7927: 	}
 7928: 
 7929: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
 7930: function change_radio(field) {
 7931:     var slct=document.scantronupload.scantron_CODE_resolution;
 7932:     var i;
 7933:     for (i=0;i<slct.length;i++) {
 7934:         if (slct[i].value==field) { slct[i].checked=true; }
 7935:     }
 7936: }
 7937: ENDSCRIPT
 7938: 	my $href="/adm/pickcode?".
 7939: 	   "form=".&escape("scantronupload").
 7940: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 7941: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 7942: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 7943: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 7944: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 7945: 	    $r->print("
 7946:     <label>
 7947:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 7948:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 7949: 	     "<a target='_blank' href='$href'>","</a>")."
 7950:     </label> 
 7951:     ".&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\')" />'));
 7952: 	    $r->print("\n<br />");
 7953: 	}
 7954: 	$r->print("
 7955:     <label>
 7956:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 7957:        ".&mt("Use [_1] as the CODE.",
 7958: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 7959: 	$r->print("\n<br /><br />");
 7960:     } elsif ($error eq 'doublebubble') {
 7961: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 7962: 
 7963: 	# The form field scantron_questions is acutally a list of line numbers.
 7964: 	# represented by this form so:
 7965: 
 7966: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7967:                                                 $respnumlookup,$startline);
 7968: 
 7969: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7970: 		  $line_list.'" />');
 7971: 	$r->print($message);
 7972: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 7973: 	foreach my $question (@{$arg}) {
 7974: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7975:                                                    $scan_record, $error,
 7976:                                                    $randomorder,$randompick,
 7977:                                                    $respnumlookup,$startline);
 7978:             push(@lines_to_correct,@linenums);
 7979: 	}
 7980:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7981:     } elsif ($error eq 'missingbubble') {
 7982: 	$r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
 7983: 	$r->print($message);
 7984: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 7985: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 7986: 
 7987: 	# The form field scantron_questions is actually a list of line numbers not
 7988: 	# a list of question numbers. Therefore:
 7989: 	#
 7990: 
 7991: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7992:                                                 $respnumlookup,$startline);
 7993: 
 7994: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7995: 		  $line_list.'" />');
 7996: 	foreach my $question (@{$arg}) {
 7997: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7998:                                                    $scan_record, $error,
 7999:                                                    $randomorder,$randompick,
 8000:                                                    $respnumlookup,$startline);
 8001:             push(@lines_to_correct,@linenums);
 8002: 	}
 8003:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 8004:     } else {
 8005: 	$r->print("\n<ul>");
 8006:     }
 8007:     $r->print("\n</li></ul>");
 8008: }
 8009: 
 8010: sub verify_bubbles_checked {
 8011:     my (@ansnums) = @_;
 8012:     my $ansnumstr = join('","',@ansnums);
 8013:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 8014:     &js_escape(\$warning);
 8015:     my $output = &Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT);
 8016: function verify_bubble_radio(form) {
 8017:     var ansnumArray = new Array ("$ansnumstr");
 8018:     var need_bubble_count = 0;
 8019:     for (var i=0; i<ansnumArray.length; i++) {
 8020:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 8021:             var bubble_picked = 0; 
 8022:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 8023:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 8024:                     bubble_picked = 1;
 8025:                 }
 8026:             }
 8027:             if (bubble_picked == 0) {
 8028:                 need_bubble_count ++;
 8029:             }
 8030:         }
 8031:     }
 8032:     if (need_bubble_count) {
 8033:         alert("$warning");
 8034:         return;
 8035:     }
 8036:     form.submit(); 
 8037: }
 8038: ENDSCRIPT
 8039:     return $output;
 8040: }
 8041: 
 8042: =pod
 8043: 
 8044: =item  questions_to_line_list
 8045: 
 8046: Converts a list of questions into a string of comma separated
 8047: line numbers in the answer sheet used by the questions.  This is
 8048: used to fill in the scantron_questions form field.
 8049: 
 8050:   Arguments:
 8051:      questions    - Reference to an array of questions.
 8052:      randomorder  - True if randomorder in use.
 8053:      randompick   - True if randompick in use.
 8054:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
 8055:                      for current line to question number used for same question
 8056:                      in "Master Seqence" (as seen by Course Coordinator).
 8057:      startline    - Reference to hash where key is question number (0 is first)
 8058:                     and key is number of first bubble line for current student
 8059:                     or code-based randompick and/or randomorder.
 8060: 
 8061: =cut
 8062: 
 8063: 
 8064: sub questions_to_line_list {
 8065:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
 8066:     my @lines;
 8067: 
 8068:     foreach my $item (@{$questions}) {
 8069:         my $question = $item;
 8070:         my ($first,$count,$last);
 8071:         if ($item =~ /^(\d+)\.(\d+)$/) {
 8072:             $question = $1;
 8073:             my $subquestion = $2;
 8074:             my $responsenum = $question-1;
 8075:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8076:                 $responsenum = $respnumlookup->{$question-1};
 8077:                 if (ref($startline) eq 'HASH') {
 8078:                     $first = $startline->{$question-1} + 1;
 8079:                 }
 8080:             } else {
 8081:                 $first = $first_bubble_line{$responsenum} + 1;
 8082:             }
 8083:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8084:             my $subcount = 1;
 8085:             while ($subcount<$subquestion) {
 8086:                 $first += $subans[$subcount-1];
 8087:                 $subcount ++;
 8088:             }
 8089:             $count = $subans[$subquestion-1];
 8090:         } else {
 8091:             my $responsenum = $question-1;
 8092:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8093:                 $responsenum = $respnumlookup->{$question-1};
 8094:                 if (ref($startline) eq 'HASH') {
 8095:                     $first = $startline->{$question-1} + 1;
 8096:                 }
 8097:             } else {
 8098:                 $first = $first_bubble_line{$responsenum} + 1;
 8099:             }
 8100: 	    $count   = $bubble_lines_per_response{$responsenum};
 8101:         }
 8102:         $last = $first+$count-1;
 8103:         push(@lines, ($first..$last));
 8104:     }
 8105:     return join(',', @lines);
 8106: }
 8107: 
 8108: =pod 
 8109: 
 8110: =item prompt_for_corrections
 8111: 
 8112: Prompts for a potentially multiline correction to the
 8113: user's bubbling (factors out common code from scantron_get_correction
 8114: for multi and missing bubble cases).
 8115: 
 8116:  Arguments:
 8117:    $r           - Apache request object.
 8118:    $question    - The question number to prompt for.
 8119:    $scan_config - The scantron file configuration hash.
 8120:    $scan_record - Reference to the hash that has the the parsed scanlines.
 8121:    $error       - Type of error
 8122:    $randomorder - True if randomorder in use.
 8123:    $randompick  - True if randompick in use.
 8124:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
 8125:                     for current line to question number used for same question
 8126:                     in "Master Seqence" (as seen by Course Coordinator).
 8127:    $startline   - Reference to hash where key is question number (0 is first)
 8128:                   and value is number of first bubble line for current student
 8129:                   or code-based randompick and/or randomorder.
 8130: 
 8131: 
 8132:  Implicit inputs:
 8133:    %bubble_lines_per_response   - Starting line numbers for each question.
 8134:                                   Numbered from 0 (but question numbers are from
 8135:                                   1.
 8136:    %first_bubble_line           - Starting bubble line for each question.
 8137:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 8138:                                   type problems render as separate sub-questions, 
 8139:                                   in exam mode. This hash contains a 
 8140:                                   comma-separated list of the lines per 
 8141:                                   sub-question.
 8142:    %responsetype_per_response   - essayresponse, formularesponse,
 8143:                                   stringresponse, imageresponse, reactionresponse,
 8144:                                   and organicresponse type problem parts can have
 8145:                                   multiple lines per response if the weight
 8146:                                   assigned exceeds 10.  In this case, only
 8147:                                   one bubble per line is permitted, but more 
 8148:                                   than one line might contain bubbles, e.g.
 8149:                                   bubbling of: line 1 - J, line 2 - J, 
 8150:                                   line 3 - B would assign 22 points.  
 8151: 
 8152: =cut
 8153: 
 8154: sub prompt_for_corrections {
 8155:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
 8156:         $randompick, $respnumlookup, $startline) = @_;
 8157:     my ($current_line,$lines);
 8158:     my @linenums;
 8159:     my $questionnum = $question;
 8160:     my ($first,$responsenum);
 8161:     if ($question =~ /^(\d+)\.(\d+)$/) {
 8162:         $question = $1;
 8163:         my $subquestion = $2;
 8164:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8165:             $responsenum = $respnumlookup->{$question-1};
 8166:             if (ref($startline) eq 'HASH') {
 8167:                 $first = $startline->{$question-1};
 8168:             }
 8169:         } else {
 8170:             $responsenum = $question-1;
 8171:             $first = $first_bubble_line{$responsenum};
 8172:         }
 8173:         $current_line = $first + 1 ;
 8174:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8175:         my $subcount = 1;
 8176:         while ($subcount<$subquestion) {
 8177:             $current_line += $subans[$subcount-1];
 8178:             $subcount ++;
 8179:         }
 8180:         $lines = $subans[$subquestion-1];
 8181:     } else {
 8182:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8183:             $responsenum = $respnumlookup->{$question-1};
 8184:             if (ref($startline) eq 'HASH') { 
 8185:                 $first = $startline->{$question-1};
 8186:             }
 8187:         } else {
 8188:             $responsenum = $question-1;
 8189:             $first = $first_bubble_line{$responsenum};
 8190:         }
 8191:         $current_line = $first + 1;
 8192:         $lines        = $bubble_lines_per_response{$responsenum};
 8193:     }
 8194:     if ($lines > 1) {
 8195:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 8196:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 8197:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 8198:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 8199:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 8200:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 8201:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 8202:             $r->print(
 8203:                 &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)
 8204:                .'<br /><br />'
 8205:                .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
 8206:                .'<br />'
 8207:                .&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.')
 8208:                .'<br />'
 8209:                .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
 8210:                .'<br /><br />'
 8211:             );
 8212:         } else {
 8213:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 8214:         }
 8215:     }
 8216:     for (my $i =0; $i < $lines; $i++) {
 8217:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 8218: 	&scantron_bubble_selector($r,$scan_config,$current_line,
 8219: 	        		  $questionnum,$error,split('', $selected));
 8220:         push(@linenums,$current_line);
 8221: 	$current_line++;
 8222:     }
 8223:     if ($lines > 1) {
 8224: 	$r->print("<hr /><br />");
 8225:     }
 8226:     return @linenums;
 8227: }
 8228: 
 8229: =pod
 8230: 
 8231: =item scantron_bubble_selector
 8232:   
 8233:    Generates the html radiobuttons to correct a single bubble line
 8234:    possibly showing the existing the selected bubbles if known
 8235: 
 8236:  Arguments:
 8237:     $r           - Apache request object
 8238:     $scan_config - hash from &Apache::lonnet::get_scantron_config()
 8239:     $line        - Number of the line being displayed.
 8240:     $questionnum - Question number (may include subquestion)
 8241:     $error       - Type of error.
 8242:     @selected    - Array of bubbles picked on this line.
 8243: 
 8244: =cut
 8245: 
 8246: sub scantron_bubble_selector {
 8247:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 8248:     my $max=$$scan_config{'Qlength'};
 8249: 
 8250:     my $scmode=$$scan_config{'Qon'};
 8251:     if ($scmode eq 'number' || $scmode eq 'letter') { 
 8252:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
 8253:             ($$scan_config{'BubblesPerRow'} > 0)) {
 8254:             $max=$$scan_config{'BubblesPerRow'};
 8255:             if (($scmode eq 'number') && ($max > 10)) {
 8256:                 $max = 10;
 8257:             } elsif (($scmode eq 'letter') && $max > 26) {
 8258:                 $max = 26;
 8259:             }
 8260:         } else {
 8261:             $max = 10;
 8262:         }
 8263:     }
 8264: 
 8265:     my @alphabet=('A'..'Z');
 8266:     $r->print(&Apache::loncommon::start_data_table().
 8267:               &Apache::loncommon::start_data_table_row());
 8268:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 8269:     for (my $i=0;$i<$max+1;$i++) {
 8270: 	$r->print("\n".'<td align="center">');
 8271: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 8272: 	else { $r->print('&nbsp;'); }
 8273: 	$r->print('</td>');
 8274:     }
 8275:     $r->print(&Apache::loncommon::end_data_table_row().
 8276:               &Apache::loncommon::start_data_table_row());
 8277:     for (my $i=0;$i<$max;$i++) {
 8278: 	$r->print("\n".
 8279: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 8280: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 8281:     }
 8282:     my $nobub_checked = ' ';
 8283:     if ($error eq 'missingbubble') {
 8284:         $nobub_checked = ' checked = "checked" ';
 8285:     }
 8286:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 8287: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 8288:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 8289:               $line.'" value="'.$questionnum.'" /></td>');
 8290:     $r->print(&Apache::loncommon::end_data_table_row().
 8291:               &Apache::loncommon::end_data_table());
 8292: }
 8293: 
 8294: =pod
 8295: 
 8296: =item num_matches
 8297: 
 8298:    Counts the number of characters that are the same between the two arguments.
 8299: 
 8300:  Arguments:
 8301:    $orig - CODE from the scanline
 8302:    $code - CODE to match against
 8303: 
 8304:  Returns:
 8305:    $count - integer count of the number of same characters between the
 8306:             two arguments
 8307: 
 8308: =cut
 8309: 
 8310: sub num_matches {
 8311:     my ($orig,$code) = @_;
 8312:     my @code=split(//,$code);
 8313:     my @orig=split(//,$orig);
 8314:     my $same=0;
 8315:     for (my $i=0;$i<scalar(@code);$i++) {
 8316: 	if ($code[$i] eq $orig[$i]) { $same++; }
 8317:     }
 8318:     return $same;
 8319: }
 8320: 
 8321: =pod
 8322: 
 8323: =item scantron_get_closely_matching_CODEs
 8324: 
 8325:    Cycles through all CODEs and finds the set that has the greatest
 8326:    number of same characters as the provided CODE
 8327: 
 8328:  Arguments:
 8329:    $allcodes - hash ref returned by &get_codes()
 8330:    $CODE     - CODE from the current scanline
 8331: 
 8332:  Returns:
 8333:    2 element list
 8334:     - first elements is number of how closely matching the best fit is 
 8335:       (5 means best set has 5 matching characters)
 8336:     - second element is an arrary ref containing the set of valid CODEs
 8337:       that best fit the passed in CODE
 8338: 
 8339: =cut
 8340: 
 8341: sub scantron_get_closely_matching_CODEs {
 8342:     my ($allcodes,$CODE)=@_;
 8343:     my @CODEs;
 8344:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 8345: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 8346:     }
 8347: 
 8348:     return ($#CODEs,$CODEs[-1]);
 8349: }
 8350: 
 8351: =pod
 8352: 
 8353: =item get_codes
 8354: 
 8355:    Builds a hash which has keys of all of the valid CODEs from the selected
 8356:    set of remembered CODEs.
 8357: 
 8358:  Arguments:
 8359:   $old_name - name of the set of remembered CODEs
 8360:   $cdom     - domain of the course
 8361:   $cnum     - internal course name
 8362: 
 8363:  Returns:
 8364:   %allcodes - keys are the valid CODEs, values are all 1
 8365: 
 8366: =cut
 8367: 
 8368: sub get_codes {
 8369:     my ($old_name, $cdom, $cnum) = @_;
 8370:     if (!$old_name) {
 8371: 	$old_name=$env{'form.scantron_CODElist'};
 8372:     }
 8373:     if (!$cdom) {
 8374: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 8375:     }
 8376:     if (!$cnum) {
 8377: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 8378:     }
 8379:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 8380: 				    $cdom,$cnum);
 8381:     my %allcodes;
 8382:     if ($result{"type\0$old_name"} eq 'number') {
 8383: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 8384:     } else {
 8385: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 8386:     }
 8387:     return %allcodes;
 8388: }
 8389: 
 8390: =pod
 8391: 
 8392: =item scantron_validate_CODE
 8393: 
 8394:    Validates all scanlines in the selected file to not have any
 8395:    invalid or underspecified CODEs and that none of the codes are
 8396:    duplicated if this was requested.
 8397: 
 8398: =cut
 8399: 
 8400: sub scantron_validate_CODE {
 8401:     my ($r,$currentphase) = @_;
 8402:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8403:     if ($scantron_config{'CODElocation'} &&
 8404: 	$scantron_config{'CODEstart'} &&
 8405: 	$scantron_config{'CODElength'}) {
 8406: 	if (!defined($env{'form.scantron_CODElist'})) {
 8407: 	    &FIXME_blow_up()
 8408: 	}
 8409:     } else {
 8410: 	return (0,$currentphase+1);
 8411:     }
 8412:     
 8413:     my %usedCODEs;
 8414: 
 8415:     my %allcodes=&get_codes();
 8416: 
 8417:     my $nav_error;
 8418:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
 8419:     if ($nav_error) {
 8420:         $r->print(&navmap_errormsg());
 8421:         return(1,$currentphase);
 8422:     }
 8423: 
 8424:     my ($scanlines,$scan_data)=&scantron_getfile();
 8425:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8426: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8427: 	if ($line=~/^[\s\cz]*$/) { next; }
 8428: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8429: 						 $scan_data);
 8430: 	my $CODE=$$scan_record{'scantron.CODE'};
 8431: 	my $error=0;
 8432: 	if (!&Apache::lonnet::validCODE($CODE)) {
 8433: 	    &scantron_get_correction($r,$i,$scan_record,
 8434: 				     \%scantron_config,
 8435: 				     $line,'incorrectCODE',\%allcodes);
 8436: 	    return(1,$currentphase);
 8437: 	}
 8438: 	if (%allcodes && !exists($allcodes{$CODE}) 
 8439: 	    && !$$scan_record{'scantron.useCODE'}) {
 8440: 	    &scantron_get_correction($r,$i,$scan_record,
 8441: 				     \%scantron_config,
 8442: 				     $line,'incorrectCODE',\%allcodes);
 8443: 	    return(1,$currentphase);
 8444: 	}
 8445: 	if (exists($usedCODEs{$CODE}) 
 8446: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 8447: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 8448: 	    &scantron_get_correction($r,$i,$scan_record,
 8449: 				     \%scantron_config,
 8450: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 8451: 	    return(1,$currentphase);
 8452: 	}
 8453: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 8454:     }
 8455:     return (0,$currentphase+1);
 8456: }
 8457: 
 8458: =pod
 8459: 
 8460: =item scantron_validate_doublebubble
 8461: 
 8462:    Validates all scanlines in the selected file to not have any
 8463:    bubble lines with multiple bubbles marked.
 8464: 
 8465: =cut
 8466: 
 8467: sub scantron_validate_doublebubble {
 8468:     my ($r,$currentphase) = @_;
 8469:     #get student info
 8470:     my $classlist=&Apache::loncoursedata::get_classlist();
 8471:     my %idmap=&username_to_idmap($classlist);
 8472:     my (undef,undef,$sequence)=
 8473:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8474: 
 8475:     #get scantron line setup
 8476:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8477:     my ($scanlines,$scan_data)=&scantron_getfile();
 8478: 
 8479:     my $navmap = Apache::lonnavmaps::navmap->new();
 8480:     unless (ref($navmap)) {
 8481:         $r->print(&navmap_errormsg());
 8482:         return(1,$currentphase);
 8483:     }
 8484:     my $map=$navmap->getResourceByUrl($sequence);
 8485:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8486:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8487:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8488:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8489: 
 8490:     my $nav_error;
 8491:     if (ref($map)) {
 8492:         $randomorder = $map->randomorder();
 8493:         $randompick = $map->randompick();
 8494:         if ($randomorder || $randompick) {
 8495:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8496:             if ($nav_error) {
 8497:                 $r->print(&navmap_errormsg());
 8498:                 return(1,$currentphase);
 8499:             }
 8500:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8501:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8502:         }
 8503:     } else {
 8504:         $r->print(&navmap_errormsg());
 8505:         return(1,$currentphase);
 8506:     }
 8507: 
 8508:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
 8509:     if ($nav_error) {
 8510:         $r->print(&navmap_errormsg());
 8511:         return(1,$currentphase);
 8512:     }
 8513: 
 8514:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8515: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8516: 	if ($line=~/^[\s\cz]*$/) { next; }
 8517: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8518: 						 $scan_data,undef,\%idmap,$randomorder,
 8519:                                                  $randompick,$sequence,\@master_seq,
 8520:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8521:                                                  \%orderedforcode,\%respnumlookup,\%startline);
 8522: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 8523: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 8524: 				 'doublebubble',
 8525: 				 $$scan_record{'scantron.doubleerror'},
 8526:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
 8527:     	return (1,$currentphase);
 8528:     }
 8529:     return (0,$currentphase+1);
 8530: }
 8531: 
 8532: 
 8533: sub scantron_get_maxbubble {
 8534:     my ($nav_error,$scantron_config) = @_;
 8535:     if (defined($env{'form.scantron_maxbubble'}) &&
 8536: 	$env{'form.scantron_maxbubble'}) {
 8537: 	&restore_bubble_lines();
 8538: 	return $env{'form.scantron_maxbubble'};
 8539:     }
 8540: 
 8541:     my (undef, undef, $sequence) =
 8542: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8543: 
 8544:     my $navmap=Apache::lonnavmaps::navmap->new();
 8545:     unless (ref($navmap)) {
 8546:         if (ref($nav_error)) {
 8547:             $$nav_error = 1;
 8548:         }
 8549:         return;
 8550:     }
 8551:     my $map=$navmap->getResourceByUrl($sequence);
 8552:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8553:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
 8554: 
 8555:     &Apache::lonxml::clear_problem_counter();
 8556: 
 8557:     my $uname       = $env{'user.name'};
 8558:     my $udom        = $env{'user.domain'};
 8559:     my $cid         = $env{'request.course.id'};
 8560:     my $total_lines = 0;
 8561:     %bubble_lines_per_response = ();
 8562:     %first_bubble_line         = ();
 8563:     %subdivided_bubble_lines   = ();
 8564:     %responsetype_per_response = ();
 8565:     %masterseq_id_responsenum  = ();
 8566: 
 8567:     my $response_number = 0;
 8568:     my $bubble_line     = 0;
 8569:     foreach my $resource (@resources) {
 8570:         my $resid = $resource->id(); 
 8571:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
 8572:                                                           $udom,undef,$bubbles_per_row);
 8573:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 8574: 	    foreach my $part_id (@{$parts}) {
 8575:                 my $lines;
 8576: 
 8577: 	        # TODO - make this a persistent hash not an array.
 8578: 
 8579:                 # optionresponse, matchresponse and rankresponse type items 
 8580:                 # render as separate sub-questions in exam mode.
 8581:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 8582:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 8583:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 8584:                     my ($numbub,$numshown);
 8585:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 8586:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 8587:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 8588:                         }
 8589:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 8590:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 8591:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 8592:                         }
 8593:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 8594:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 8595:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 8596:                         }
 8597:                     }
 8598:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 8599:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 8600:                     }
 8601:                     my $bubbles_per_row =
 8602:                         &bubblesheet_bubbles_per_row($scantron_config);
 8603:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
 8604:                     if (($numbub % $bubbles_per_row) != 0) {
 8605:                         $inner_bubble_lines++;
 8606:                     }
 8607:                     for (my $i=0; $i<$numshown; $i++) {
 8608:                         $subdivided_bubble_lines{$response_number} .= 
 8609:                             $inner_bubble_lines.',';
 8610:                     }
 8611:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 8612:                     $lines = $numshown * $inner_bubble_lines;
 8613:                 } else {
 8614:                     $lines = $analysis->{"$part_id.bubble_lines"};
 8615:                 }
 8616: 
 8617:                 $first_bubble_line{$response_number} = $bubble_line;
 8618: 	        $bubble_lines_per_response{$response_number} = $lines;
 8619:                 $responsetype_per_response{$response_number} = 
 8620:                     $analysis->{$part_id.'.type'};
 8621:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;  
 8622: 	        $response_number++;
 8623: 
 8624: 	        $bubble_line +=  $lines;
 8625: 	        $total_lines +=  $lines;
 8626: 	    }
 8627:         }
 8628:     }
 8629:     &Apache::lonnet::delenv('scantron.');
 8630: 
 8631:     &save_bubble_lines();
 8632:     $env{'form.scantron_maxbubble'} =
 8633: 	$total_lines;
 8634:     return $env{'form.scantron_maxbubble'};
 8635: }
 8636: 
 8637: sub bubblesheet_bubbles_per_row {
 8638:     my ($scantron_config) = @_;
 8639:     my $bubbles_per_row;
 8640:     if (ref($scantron_config) eq 'HASH') {
 8641:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
 8642:     }
 8643:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
 8644:         $bubbles_per_row = 10;
 8645:     }
 8646:     return $bubbles_per_row;
 8647: }
 8648: 
 8649: sub scantron_validate_missingbubbles {
 8650:     my ($r,$currentphase) = @_;
 8651:     #get student info
 8652:     my $classlist=&Apache::loncoursedata::get_classlist();
 8653:     my %idmap=&username_to_idmap($classlist);
 8654:     my (undef,undef,$sequence)=
 8655:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8656: 
 8657:     #get scantron line setup
 8658:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8659:     my ($scanlines,$scan_data)=&scantron_getfile();
 8660: 
 8661:     my $navmap = Apache::lonnavmaps::navmap->new();
 8662:     unless (ref($navmap)) {
 8663:         $r->print(&navmap_errormsg());
 8664:         return(1,$currentphase);
 8665:     }
 8666: 
 8667:     my $map=$navmap->getResourceByUrl($sequence);
 8668:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8669:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8670:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8671:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8672: 
 8673:     my $nav_error;
 8674:     if (ref($map)) {
 8675:         $randomorder = $map->randomorder();
 8676:         $randompick = $map->randompick();
 8677:         if ($randomorder || $randompick) {
 8678:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8679:             if ($nav_error) {
 8680:                 $r->print(&navmap_errormsg());
 8681:                 return(1,$currentphase);
 8682:             }
 8683:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8684:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8685:         }
 8686:     } else {
 8687:         $r->print(&navmap_errormsg());
 8688:         return(1,$currentphase);
 8689:     }
 8690: 
 8691: 
 8692:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 8693:     if ($nav_error) {
 8694:         $r->print(&navmap_errormsg());
 8695:         return(1,$currentphase);
 8696:     }
 8697: 
 8698:     if (!$max_bubble) { $max_bubble=2**31; }
 8699:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8700: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8701: 	if ($line=~/^[\s\cz]*$/) { next; }
 8702: 	my $scan_record =
 8703:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
 8704: 				     $randomorder,$randompick,$sequence,\@master_seq,
 8705:                                      \%symb_to_resource,\%grader_partids_by_symb,
 8706:                                      \%orderedforcode,\%respnumlookup,\%startline);
 8707: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 8708: 	my @to_correct;
 8709: 	
 8710: 	# Probably here's where the error is...
 8711: 
 8712: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 8713:             my $lastbubble;
 8714:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 8715:                my $question = $1;
 8716:                my $subquestion = $2;
 8717:                my ($first,$responsenum);
 8718:                if ($randomorder || $randompick) {
 8719:                    $responsenum = $respnumlookup{$question-1};
 8720:                    $first = $startline{$question-1};
 8721:                } else {
 8722:                    $responsenum = $question-1; 
 8723:                    $first = $first_bubble_line{$responsenum};
 8724:                }
 8725:                if (!defined($first)) { next; }
 8726:                my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8727:                my $subcount = 1;
 8728:                while ($subcount<$subquestion) {
 8729:                    $first += $subans[$subcount-1];
 8730:                    $subcount ++;
 8731:                }
 8732:                my $count = $subans[$subquestion-1];
 8733:                $lastbubble = $first + $count;
 8734:             } else {
 8735:                my ($first,$responsenum);
 8736:                if ($randomorder || $randompick) {
 8737:                    $responsenum = $respnumlookup{$missing-1};
 8738:                    $first = $startline{$missing-1};
 8739:                } else {
 8740:                    $responsenum = $missing-1;
 8741:                    $first = $first_bubble_line{$responsenum};
 8742:                }
 8743:                if (!defined($first)) { next; }
 8744:                $lastbubble = $first + $bubble_lines_per_response{$responsenum};
 8745:             }
 8746:             if ($lastbubble > $max_bubble) { next; }
 8747: 	    push(@to_correct,$missing);
 8748: 	}
 8749: 	if (@to_correct) {
 8750: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 8751: 				     $line,'missingbubble',\@to_correct,
 8752:                                      $randomorder,$randompick,\%respnumlookup,
 8753:                                      \%startline);
 8754: 	    return (1,$currentphase);
 8755: 	}
 8756: 
 8757:     }
 8758:     return (0,$currentphase+1);
 8759: }
 8760: 
 8761: sub hand_bubble_option {
 8762:     my (undef, undef, $sequence) =
 8763:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8764:     return if ($sequence eq '');
 8765:     my $navmap = Apache::lonnavmaps::navmap->new();
 8766:     unless (ref($navmap)) {
 8767:         return;
 8768:     }
 8769:     my $needs_hand_bubbles;
 8770:     my $map=$navmap->getResourceByUrl($sequence);
 8771:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8772:     foreach my $res (@resources) {
 8773:         if (ref($res)) {
 8774:             if ($res->is_problem()) {
 8775:                 my $partlist = $res->parts();
 8776:                 foreach my $part (@{ $partlist }) {
 8777:                     my @types = $res->responseType($part);
 8778:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
 8779:                         $needs_hand_bubbles = 1;
 8780:                         last;
 8781:                     }
 8782:                 }
 8783:             }
 8784:         }
 8785:     }
 8786:     if ($needs_hand_bubbles) {
 8787:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8788:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8789:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
 8790:                &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 />').
 8791:                '<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;'.
 8792:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
 8793:     }
 8794:     return;
 8795: }
 8796: 
 8797: sub scantron_process_students {
 8798:     my ($r,$symb) = @_;
 8799: 
 8800:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8801:     if (!$symb) {
 8802: 	return '';
 8803:     }
 8804:     my $default_form_data=&defaultFormData($symb);
 8805: 
 8806:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8807:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config); 
 8808:     my ($scanlines,$scan_data)=&scantron_getfile();
 8809:     my $classlist=&Apache::loncoursedata::get_classlist();
 8810:     my %idmap=&username_to_idmap($classlist);
 8811:     my $navmap=Apache::lonnavmaps::navmap->new();
 8812:     unless (ref($navmap)) {
 8813:         $r->print(&navmap_errormsg());
 8814:         return '';
 8815:     }
 8816:     my $map=$navmap->getResourceByUrl($sequence);
 8817:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8818:         %grader_randomlists_by_symb);
 8819:     if (ref($map)) {
 8820:         $randomorder = $map->randomorder();
 8821:         $randompick = $map->randompick();
 8822:     } else {
 8823:         $r->print(&navmap_errormsg());
 8824:         return '';
 8825:     }
 8826:     my $nav_error;
 8827:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8828:     if ($randomorder || $randompick) {
 8829:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8830:         if ($nav_error) {
 8831:             $r->print(&navmap_errormsg());
 8832:             return '';
 8833:         }
 8834:     }
 8835:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8836:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 8837: 
 8838:     my ($uname,$udom);
 8839:     my $result= <<SCANTRONFORM;
 8840: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 8841:   <input type="hidden" name="command" value="scantron_configphase" />
 8842:   $default_form_data
 8843: SCANTRONFORM
 8844:     $r->print($result);
 8845: 
 8846:     my ($checksec,@possibles)=&gradable_sections();
 8847:     my @delayqueue;
 8848:     my (%completedstudents,%scandata);
 8849: 
 8850:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 8851:     my $count=&get_todo_count($scanlines,$scan_data);
 8852:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 8853:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
 8854:     $r->print('<br />');
 8855:     my $start=&Time::HiRes::time();
 8856:     my $i=-1;
 8857:     my $started;
 8858: 
 8859:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 8860:     if ($nav_error) {
 8861:         $r->print(&navmap_errormsg());
 8862:         return '';
 8863:     }
 8864: 
 8865:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 8866:     # the user and return.
 8867: 
 8868:     if ($ssi_error) {
 8869: 	$r->print("</form>");
 8870: 	&ssi_print_error($r);
 8871:         &Apache::lonnet::remove_lock($lock);
 8872: 	return '';		# Dunno why the other returns return '' rather than just returning.
 8873:     }
 8874: 
 8875:     my %lettdig = &Apache::lonnet::letter_to_digits();
 8876:     my $numletts = scalar(keys(%lettdig));
 8877:     my %orderedforcode;
 8878: 
 8879:     while ($i<$scanlines->{'count'}) {
 8880:  	($uname,$udom)=('','');
 8881:  	$i++;
 8882:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8883:  	if ($line=~/^[\s\cz]*$/) { next; }
 8884: 	if ($started) {
 8885: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 8886: 	}
 8887: 	$started=1;
 8888:         my %respnumlookup = ();
 8889:         my %startline = ();
 8890:         my $total;
 8891:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8892:                                                  $scan_data,undef,\%idmap,$randomorder,
 8893:                                                  $randompick,$sequence,\@master_seq,
 8894:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8895:                                                  \%orderedforcode,\%respnumlookup,\%startline,
 8896:                                                  \$total);
 8897:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 8898:  					      \%idmap,$i)) {
 8899:   	    &scantron_add_delay(\@delayqueue,$line,
 8900:  				'Unable to find a student that matches',1);
 8901:  	    next;
 8902:   	}
 8903:  	if (exists $completedstudents{$uname}) {
 8904:  	    &scantron_add_delay(\@delayqueue,$line,
 8905:  				'Student '.$uname.' has multiple sheets',2);
 8906:  	    next;
 8907:  	}
 8908:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 8909:         if (($checksec ne '') && ($checksec ne $usec)) {
 8910:             unless (grep(/^\Q$usec\E$/,@possibles)) {
 8911:                 &scantron_add_delay(\@delayqueue,$line,
 8912:                                     "No role with manage grades privilege in student's section ($usec)",3);
 8913:                 next;
 8914:             }
 8915:         }
 8916:         my $user = $uname.':'.$usec;
 8917:   	($uname,$udom)=split(/:/,$uname);
 8918: 
 8919:         my $scancode;
 8920:         if ((exists($scan_record->{'scantron.CODE'})) &&
 8921:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 8922:             $scancode = $scan_record->{'scantron.CODE'};
 8923:         } else {
 8924:             $scancode = '';
 8925:         }
 8926: 
 8927:         my @mapresources = @resources;
 8928:         if ($randomorder || $randompick) {
 8929:             @mapresources = 
 8930:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 8931:                              \%orderedforcode);
 8932:         }
 8933:         my (%partids_by_symb,$res_error);
 8934:         foreach my $resource (@mapresources) {
 8935:             my $ressymb;
 8936:             if (ref($resource)) {
 8937:                 $ressymb = $resource->symb();
 8938:             } else {
 8939:                 $res_error = 1;
 8940:                 last;
 8941:             }
 8942:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8943:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8944:                 my $currcode;
 8945:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
 8946:                     $currcode = $scancode;
 8947:                 }
 8948:                 my ($analysis,$parts) =
 8949:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 8950:                                               $uname,$udom,undef,$bubbles_per_row,
 8951:                                               $currcode);
 8952:                 $partids_by_symb{$ressymb} = $parts;
 8953:             } else {
 8954:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 8955:             }
 8956:         }
 8957: 
 8958:         if ($res_error) {
 8959:             &scantron_add_delay(\@delayqueue,$line,
 8960:                                 'An error occurred while grading student '.$uname,2);
 8961:             next;
 8962:         }
 8963: 
 8964: 	&Apache::lonxml::clear_problem_counter();
 8965:   	&Apache::lonnet::appenv($scan_record);
 8966: 
 8967: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 8968: 	    &scantron_putfile($scanlines,$scan_data);
 8969: 	}
 8970: 	
 8971:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8972:                                    \@mapresources,\%partids_by_symb,
 8973:                                    $bubbles_per_row,$randomorder,$randompick,
 8974:                                    \%respnumlookup,\%startline) 
 8975:             eq 'ssi_error') {
 8976:             $ssi_error = 0; # So end of handler error message does not trigger.
 8977:             $r->print("</form>");
 8978:             &ssi_print_error($r);
 8979:             &Apache::lonnet::remove_lock($lock);
 8980:             return '';      # Why return ''?  Beats me.
 8981:         }
 8982: 
 8983:         if (($scancode) && ($randomorder || $randompick)) {
 8984:             my $parmresult =
 8985:                 &Apache::lonparmset::storeparm_by_symb($symb,
 8986:                                                        '0_examcode',2,$scancode,
 8987:                                                        'string_examcode',$uname,
 8988:                                                        $udom);
 8989:         }
 8990: 	$completedstudents{$uname}={'line'=>$line};
 8991:         if ($env{'form.verifyrecord'}) {
 8992:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8993:             if ($randompick) {
 8994:                 if ($total) {
 8995:                     $lastpos = $total*$scantron_config{'Qlength'};
 8996:                 }
 8997:             }
 8998: 
 8999:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 9000:             chomp($studentdata);
 9001:             $studentdata =~ s/\r$//;
 9002:             my $studentrecord = '';
 9003:             my $counter = -1;
 9004:             foreach my $resource (@mapresources) {
 9005:                 my $ressymb = $resource->symb();
 9006:                 ($counter,my $recording) =
 9007:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 9008:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 9009:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
 9010:                                              $randompick,\%respnumlookup,\%startline);
 9011:                 $studentrecord .= $recording;
 9012:             }
 9013:             if ($studentrecord ne $studentdata) {
 9014:                 &Apache::lonxml::clear_problem_counter();
 9015:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 9016:                                            \@mapresources,\%partids_by_symb,
 9017:                                            $bubbles_per_row,$randomorder,$randompick,
 9018:                                            \%respnumlookup,\%startline) 
 9019:                     eq 'ssi_error') {
 9020:                     $ssi_error = 0; # So end of handler error message does not trigger.
 9021:                     $r->print("</form>");
 9022:                     &ssi_print_error($r);
 9023:                     &Apache::lonnet::remove_lock($lock);
 9024:                     delete($completedstudents{$uname});
 9025:                     return '';
 9026:                 }
 9027:                 $counter = -1;
 9028:                 $studentrecord = '';
 9029:                 foreach my $resource (@mapresources) {
 9030:                     my $ressymb = $resource->symb();
 9031:                     ($counter,my $recording) =
 9032:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 9033:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 9034:                                                  \%scantron_config,\%lettdig,$numletts,
 9035:                                                  $randomorder,$randompick,\%respnumlookup,
 9036:                                                  \%startline);
 9037:                     $studentrecord .= $recording;
 9038:                 }
 9039:                 if ($studentrecord ne $studentdata) {
 9040:                     $r->print('<p><span class="LC_warning">');
 9041:                     if ($scancode eq '') {
 9042:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
 9043:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 9044:                     } else {
 9045:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
 9046:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 9047:                     }
 9048:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 9049:                               &Apache::loncommon::start_data_table_header_row()."\n".
 9050:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 9051:                               &Apache::loncommon::end_data_table_header_row()."\n".
 9052:                               &Apache::loncommon::start_data_table_row().
 9053:                               '<td>'.&mt('Bubblesheet').'</td>'.
 9054:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
 9055:                               &Apache::loncommon::end_data_table_row().
 9056:                               &Apache::loncommon::start_data_table_row().
 9057:                               '<td>'.&mt('Stored submissions').'</td>'.
 9058:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
 9059:                               &Apache::loncommon::end_data_table_row().
 9060:                               &Apache::loncommon::end_data_table().'</p>');
 9061:                 } else {
 9062:                     $r->print('<br /><span class="LC_warning">'.
 9063:                              &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 />'.
 9064:                              &mt("As a consequence, this user's submission history records two tries.").
 9065:                                  '</span><br />');
 9066:                 }
 9067:             }
 9068:         }
 9069:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 9070:     } continue {
 9071: 	&Apache::lonxml::clear_problem_counter();
 9072: 	&Apache::lonnet::delenv('scantron.');
 9073:     }
 9074:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 9075:     &Apache::lonnet::remove_lock($lock);
 9076: #    my $lasttime = &Time::HiRes::time()-$start;
 9077: #    $r->print("<p>took $lasttime</p>");
 9078: 
 9079:     $r->print("</form>");
 9080:     return '';
 9081: }
 9082: 
 9083: sub graders_resources_pass {
 9084:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
 9085:         $bubbles_per_row) = @_;
 9086:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 9087:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 9088:         foreach my $resource (@{$resources}) {
 9089:             my $ressymb = $resource->symb();
 9090:             my ($analysis,$parts) =
 9091:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 9092:                                           $env{'user.name'},$env{'user.domain'},
 9093:                                           1,$bubbles_per_row);
 9094:             $grader_partids_by_symb->{$ressymb} = $parts;
 9095:             if (ref($analysis) eq 'HASH') {
 9096:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 9097:                     $grader_randomlists_by_symb->{$ressymb} =
 9098:                         $analysis->{'parts_withrandomlist'};
 9099:                 }
 9100:             }
 9101:         }
 9102:     }
 9103:     return;
 9104: }
 9105: 
 9106: =pod
 9107: 
 9108: =item users_order
 9109: 
 9110:   Returns array of resources in current map, ordered based on either CODE,
 9111:   if this is a CODEd exam, or based on student's identity if this is a 
 9112:   "NAMEd" exam.
 9113: 
 9114:   Should be used when randomorder and/or randompick applied when the 
 9115:   corresponding exam was printed, prior to students completing bubblesheets 
 9116:   for the version of the exam the student received.
 9117: 
 9118: =cut
 9119: 
 9120: sub users_order  {
 9121:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
 9122:     my @mapresources;
 9123:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
 9124:         return @mapresources;
 9125:     }
 9126:     if ($scancode) {
 9127:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
 9128:             @mapresources = @{$orderedforcode->{$scancode}};
 9129:         } else {
 9130:             $env{'form.CODE'} = $scancode;
 9131:             my $actual_seq =
 9132:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 9133:                                                                $master_seq,
 9134:                                                                $user,$scancode,1);
 9135:             if (ref($actual_seq) eq 'ARRAY') {
 9136:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
 9137:                 if (ref($orderedforcode) eq 'HASH') {
 9138:                     if (@mapresources > 0) { 
 9139:                         $orderedforcode->{$scancode} = \@mapresources;
 9140:                     }
 9141:                 }
 9142:             }
 9143:             delete($env{'form.CODE'});
 9144:         }
 9145:     } else {
 9146:         my $actual_seq =
 9147:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 9148:                                                            $master_seq,
 9149:                                                            $user,undef,1);
 9150:         if (ref($actual_seq) eq 'ARRAY') {
 9151:             @mapresources = 
 9152:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
 9153:         }
 9154:     }
 9155:     return @mapresources;
 9156: }
 9157: 
 9158: sub grade_student_bubbles {
 9159:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
 9160:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
 9161:     my $uselookup = 0;
 9162:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
 9163:         (ref($startline) eq 'HASH')) {
 9164:         $uselookup = 1;
 9165:     }
 9166: 
 9167:     if (ref($resources) eq 'ARRAY') {
 9168:         my $count = 0;
 9169:         foreach my $resource (@{$resources}) {
 9170:             my $ressymb = $resource->symb();
 9171:             my %form = ('submitted'      => 'scantron',
 9172:                         'grade_target'   => 'grade',
 9173:                         'grade_username' => $uname,
 9174:                         'grade_domain'   => $udom,
 9175:                         'grade_courseid' => $env{'request.course.id'},
 9176:                         'grade_symb'     => $ressymb,
 9177:                         'CODE'           => $scancode
 9178:                        );
 9179:             if ($bubbles_per_row ne '') {
 9180:                 $form{'bubbles_per_row'} = $bubbles_per_row;
 9181:             }
 9182:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
 9183:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
 9184:             }
 9185:             if (ref($parts) eq 'HASH') {
 9186:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 9187:                     foreach my $part (@{$parts->{$ressymb}}) {
 9188:                         if ($uselookup) {
 9189:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
 9190:                         } else {
 9191:                             $form{'scantron_questnum_start.'.$part} =
 9192:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
 9193:                         }
 9194:                         $count++;
 9195:                     }
 9196:                 }
 9197:             }
 9198:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 9199:             return 'ssi_error' if ($ssi_error);
 9200:             last if (&Apache::loncommon::connection_aborted($r));
 9201:         }
 9202:     }
 9203:     return;
 9204: }
 9205: 
 9206: sub scantron_upload_scantron_data {
 9207:     my ($r,$symb) = @_;
 9208:     my $dom = $env{'request.role.domain'};
 9209:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($dom);
 9210:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 9211:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 9212:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 9213: 							  'domainid',
 9214: 							  'coursename',$dom);
 9215:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 9216:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
 9217:     my $default_form_data=&defaultFormData($symb);
 9218:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 9219:     &js_escape(\$nofile_alert);
 9220:     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.");
 9221:     &js_escape(\$nocourseid_alert);
 9222:     $r->print(&Apache::lonhtmlcommon::scripttag('
 9223:     function checkUpload(formname) {
 9224: 	if (formname.upfile.value == "") {
 9225: 	    alert("'.$nofile_alert.'");
 9226: 	    return false;
 9227: 	}
 9228:         if (formname.courseid.value == "") {
 9229:             alert("'.$nocourseid_alert.'");
 9230:             return false;
 9231:         }
 9232: 	formname.submit();
 9233:     }
 9234: 
 9235:     function ToSyllabus() {
 9236:         var cdom = '."'$dom'".';
 9237:         var cnum = document.rules.courseid.value;
 9238:         if (cdom == "" || cdom == null) {
 9239:             return;
 9240:         }
 9241:         if (cnum == "" || cnum == null) {
 9242:            return;
 9243:         }
 9244:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 9245:                             "height=350,width=350,scrollbars=yes,menubar=no");
 9246:         return;
 9247:     }
 9248: 
 9249:     '.$formatjs.'
 9250: '));
 9251:     $r->print('
 9252: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
 9253: 
 9254: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 9255: '.$default_form_data.
 9256:   &Apache::lonhtmlcommon::start_pick_box().
 9257:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 9258:   '<input name="courseid" type="text" size="30" />'.$select_link.
 9259:   &Apache::lonhtmlcommon::row_closure().
 9260:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 9261:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 9262:   &Apache::lonhtmlcommon::row_closure().
 9263:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 9264:   '<input name="domainid" type="hidden" />'.$domdesc.
 9265:   &Apache::lonhtmlcommon::row_closure());
 9266:     if ($formatoptions) {
 9267:         $r->print(&Apache::lonhtmlcommon::row_title($formattitle).$formatoptions.
 9268:                   &Apache::lonhtmlcommon::row_closure());
 9269:     }
 9270:     $r->print(
 9271:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 9272:   '<input type="file" name="upfile" size="50" />'.
 9273:   &Apache::lonhtmlcommon::row_closure(1).
 9274:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 9275: 
 9276: <input name="command" value="scantronupload_save" type="hidden" />
 9277: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 9278: </form>
 9279: ');
 9280:     return '';
 9281: }
 9282: 
 9283: sub scantron_upload_dataformat {
 9284:     my ($dom) = @_;
 9285:     my ($formatoptions,$formattitle,$formatjs);
 9286:     $formatjs = <<'END';
 9287: function toggleScantab(form) {
 9288:    return;
 9289: }
 9290: END
 9291:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$dom);
 9292:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 9293:         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
 9294:             if (keys(%{$domconfig{'scantron'}{'config'}}) > 1) {
 9295:                 if (($domconfig{'scantron'}{'config'}{'dat'}) &&
 9296:                     (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH')) {
 9297:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {  
 9298:                         if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
 9299:                             my ($onclick,$formatextra,$singleline);
 9300:                             my @lines = &Apache::lonnet::get_scantronformat_file();
 9301:                             my $count = 0;
 9302:                             foreach my $line (@lines) {
 9303:                                 next if ($line =~ /^#/);
 9304:                                 $singleline = $line;
 9305:                                 $count ++;
 9306:                             }
 9307:                             if ($count > 1) {
 9308:                                 $formatextra = '<div style="display:none" id="bubbletype">'.
 9309:                                                '<span class="LC_nobreak">'.
 9310:                                                &mt('Bubblesheet type:').'&nbsp;'.
 9311:                                                &scantron_scantab().'</span></div>';
 9312:                                 $onclick = ' onclick="toggleScantab(this.form);"';
 9313:                                 $formatjs = <<"END";
 9314: function toggleScantab(form) {
 9315:     var divid = 'bubbletype';
 9316:     if (document.getElementById(divid)) {
 9317:         var radioname = 'fileformat';
 9318:         var num = form.elements[radioname].length;
 9319:         if (num) {
 9320:             for (var i=0; i<num; i++) {
 9321:                 if (form.elements[radioname][i].checked) {
 9322:                     var chosen = form.elements[radioname][i].value;
 9323:                     if (chosen == 'dat') {
 9324:                         document.getElementById(divid).style.display = 'none';
 9325:                     } else if (chosen == 'csv') {
 9326:                         document.getElementById(divid).style.display = 'block';
 9327:                     }
 9328:                 }
 9329:             }
 9330:         }
 9331:     }
 9332:     return;
 9333: }
 9334: 
 9335: END
 9336:                             } elsif ($count == 1) {
 9337:                                 my $formatname = (split(/:/,$singleline,2))[0];
 9338:                                 $formatextra = '<input type="hidden" name="scantron_format" value="'.$formatname.'" />';
 9339:                             }
 9340:                             $formattitle = &mt('File format');
 9341:                             $formatoptions = '<label><input name="fileformat" type="radio" value="dat" checked="checked"'.$onclick.' />'.
 9342:                                              &mt('Plain Text (no delimiters)').
 9343:                                              '</label>'.('&nbsp;'x2).
 9344:                                              '<label><input name="fileformat" type="radio" value="csv"'.$onclick.' />'.
 9345:                                              &mt('Comma separated values').'</label>'.$formatextra;
 9346:                         }
 9347:                     }
 9348:                 }
 9349:             } elsif (keys(%{$domconfig{'scantron'}{'config'}}) == 1) {
 9350:                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
 9351:                     if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
 9352:                         $formattitle = &mt('Bubblesheet type');
 9353:                         $formatoptions = &scantron_scantab();
 9354:                     }
 9355:                 }
 9356:             }
 9357:         }
 9358:     }
 9359:     return ($formatoptions,$formattitle,$formatjs);
 9360: }
 9361: 
 9362: sub scantron_upload_scantron_data_save {
 9363:     my ($r,$symb) = @_;
 9364:     my $doanotherupload=
 9365: 	'<br /><form action="/adm/grades" method="post">'."\n".
 9366: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 9367: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 9368: 	'</form>'."\n";
 9369:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 9370: 	!&Apache::lonnet::allowed('usc',
 9371: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'}) &&
 9372:         !&Apache::lonnet::allowed('usc',
 9373:                             $env{'form.domainid'}.'_'.$env{'form.courseid'}.'/'.$env{'form.coursesec'})) {
 9374: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 9375: 	unless ($symb) {
 9376: 	    $r->print($doanotherupload);
 9377: 	}
 9378: 	return '';
 9379:     }
 9380:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 9381:     my $uploadedfile;
 9382:     $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
 9383:     if (length($env{'form.upfile'}) < 2) {
 9384:         $r->print(
 9385:             &Apache::lonhtmlcommon::confirm_success(
 9386:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
 9387:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
 9388:     } else {
 9389:         my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$env{'form.domainid'});
 9390:         my $parser;
 9391:         if (ref($domconfig{'scantron'}) eq 'HASH') {
 9392:             if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
 9393:                 my $is_csv;
 9394:                 my @possibles = keys(%{$domconfig{'scantron'}{'config'}});
 9395:                 if (@possibles > 1) {
 9396:                     if ($env{'form.fileformat'} eq 'csv') {
 9397:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
 9398:                             if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
 9399:                                 if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
 9400:                                     $is_csv = 1;
 9401:                                 }
 9402:                             }
 9403:                         }
 9404:                     }
 9405:                 } elsif (@possibles == 1) {
 9406:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
 9407:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
 9408:                             if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
 9409:                                 $is_csv = 1;
 9410:                             }
 9411:                         }
 9412:                     }
 9413:                 }
 9414:                 if ($is_csv) {
 9415:                    $parser = $domconfig{'scantron'}{'config'}{'csv'};
 9416:                 }
 9417:             }
 9418:         }
 9419:         my $result =
 9420:             &Apache::lonnet::userfileupload('upfile','scantron','scantron',$parser,'','',
 9421:                                             $env{'form.courseid'},$env{'form.domainid'});
 9422:         if ($result =~ m{^/uploaded/}) {
 9423:             $r->print(
 9424:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
 9425:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
 9426:                         (length($env{'form.upfile'})-1),
 9427:                         '<span class="LC_filename">'.$result.'</span>'));
 9428:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 9429:             if ($uploadedfile =~ /^scantron_orig_/) {
 9430:                 my $logname = $uploadedfile;
 9431:                 $logname =~ s/^scantron_orig_//;
 9432:                 if ($logname ne '') {
 9433:                     my $now = time;
 9434:                     my %info = ($logname => { $now => $env{'user.name'}.':'.$env{'user.domain'} });  
 9435:                     &Apache::lonnet::put('scantronupload',\%info,$env{'form.domainid'},$env{'form.courseid'});
 9436:                 }
 9437:             }
 9438:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 9439:                                                        $env{'form.courseid'},$symb,$uploadedfile));
 9440:         } else {
 9441:             $r->print(
 9442:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
 9443:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
 9444:                           $result,
 9445: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 9446: 	}
 9447:     }
 9448:     if ($symb) {
 9449: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
 9450:     } else {
 9451: 	$r->print($doanotherupload);
 9452:     }
 9453:     return '';
 9454: }
 9455: 
 9456: sub validate_uploaded_scantron_file {
 9457:     my ($cdom,$cname,$symb,$fname,$context,$countsref) = @_;
 9458: 
 9459:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 9460:     my @lines;
 9461:     if ($scanlines ne '-1') {
 9462:         @lines=split("\n",$scanlines,-1);
 9463:     }
 9464:     my ($output,$secidx,$checksec,$priv,%crsroleshash,@possibles);
 9465:     $secidx = &Apache::loncoursedata::CL_SECTION();
 9466:     if ($context eq 'download') {
 9467:         $priv = 'mgr';
 9468:     } else {
 9469:         $priv = 'usc';
 9470:     }
 9471:     unless ((&Apache::lonnet::allowed($priv,$env{'request.role.domain'})) ||
 9472:             (($env{'request.course.id'}) &&
 9473:              (&Apache::lonnet::allowed($priv,$env{'request.course.id'})))) {
 9474:         if ($env{'request.course.sec'} ne '') {
 9475:             unless (&Apache::lonnet::allowed($priv,
 9476:                                          "$env{'request.course.id'}/$env{'request.course.sec'}")) {
 9477:                 unless ($context eq 'download') {
 9478:                     $output = '<p class="LC_warning">'.&mt('You do not have permission to upload bubblesheet data').'</p>';
 9479:                 }
 9480:                 return $output;
 9481:             }
 9482:             ($checksec,@possibles)=&gradable_sections();
 9483:         }
 9484:     }
 9485:     if (@lines) {
 9486:         my (%counts,$max_match_format);
 9487:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
 9488:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 9489:         my %idmap = &username_to_idmap($classlist);
 9490:         foreach my $key (keys(%idmap)) {
 9491:             my $lckey = lc($key);
 9492:             $idmap{$lckey} = $idmap{$key};
 9493:         }
 9494:         my %unique_formats;
 9495:         my @formatlines = &Apache::lonnet::get_scantronformat_file();
 9496:         foreach my $line (@formatlines) {
 9497:             chomp($line);
 9498:             my @config = split(/:/,$line);
 9499:             my $idstart = $config[5];
 9500:             my $idlength = $config[6];
 9501:             if (($idstart ne '') && ($idlength > 0)) {
 9502:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 9503:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 9504:                 } else {
 9505:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 9506:                 }
 9507:             }
 9508:         }
 9509:         foreach my $key (keys(%unique_formats)) {
 9510:             my ($idstart,$idlength) = split(':',$key);
 9511:             %{$counts{$key}} = (
 9512:                                'found'   => 0,
 9513:                                'total'   => 0,
 9514:                                'totalanysec' => 0,
 9515:                                'othersec' => 0,
 9516:                               );
 9517:             foreach my $line (@lines) {
 9518:                 next if ($line =~ /^#/);
 9519:                 next if ($line =~ /^[\s\cz]*$/);
 9520:                 my $id = substr($line,$idstart-1,$idlength);
 9521:                 $id = lc($id);
 9522:                 if (exists($idmap{$id})) {
 9523:                     if ($checksec ne '') {
 9524:                         $counts{$key}{'totalanysec'} ++;
 9525:                         if (ref($classlist->{$idmap{$id}}) eq 'ARRAY') {
 9526:                             my $stusec = $classlist->{$idmap{$id}}->[$secidx];
 9527:                             if ($stusec ne $checksec) {
 9528:                                 if (@possibles) {
 9529:                                     unless (grep(/^\Q$stusec\E$/,@possibles)) {
 9530:                                         $counts{$key}{'othersec'} ++;
 9531:                                         next;
 9532:                                     }
 9533:                                 } else {
 9534:                                     $counts{$key}{'othersec'} ++;
 9535:                                     next;
 9536:                                 }
 9537:                             }
 9538:                         }
 9539:                     }
 9540:                     $counts{$key}{'found'} ++;
 9541:                 }
 9542:                 $counts{$key}{'total'} ++;
 9543:             }
 9544:             if ($counts{$key}{'total'}) {
 9545:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 9546:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 9547:                     $max_match_pct = $percent_match;
 9548:                     $max_match_format = $key;
 9549:                     $found_match_count = $counts{$key}{'found'};
 9550:                     $max_match_count = $counts{$key}{'total'};
 9551:                 }
 9552:             }
 9553:         }
 9554:         if ((ref($unique_formats{$max_match_format}) eq 'ARRAY') && ($context ne 'download')) {
 9555:             my $format_descs;
 9556:             my $numwithformat = @{$unique_formats{$max_match_format}};
 9557:             for (my $i=0; $i<$numwithformat; $i++) {
 9558:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 9559:                 if ($i<$numwithformat-2) {
 9560:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 9561:                 } elsif ($i==$numwithformat-2) {
 9562:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 9563:                 } elsif ($i==$numwithformat-1) {
 9564:                     $format_descs .= '"<i>'.$desc.'</i>"';
 9565:                 }
 9566:             }
 9567:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 9568:             $output .= '<br />';
 9569:             if ($found_match_count == $max_match_count) {
 9570:                 # 100% matching entries
 9571:                 $output .= &Apache::lonhtmlcommon::confirm_success(
 9572:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
 9573:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
 9574:                 &mt('Comparison of student IDs in the uploaded file with'.
 9575:                     ' the course roster found matches for [_1] of the [_2] entries'.
 9576:                     ' in the file (for the format defined for [_3]).',
 9577:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
 9578:             } else {
 9579:                 # Not all entries matching? -> Show warning and additional info
 9580:                 $output .=
 9581:                     &Apache::lonhtmlcommon::confirm_success(
 9582:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
 9583:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
 9584:                         &mt('Not all entries could be matched!'),1).'<br />'.
 9585:                     &mt('Comparison of student IDs in the uploaded file with'.
 9586:                         ' the course roster found matches for [_1] of the [_2] entries'.
 9587:                         ' in the file (for the format defined for [_3]).',
 9588:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
 9589:                     '<p class="LC_info">'.
 9590:                     &mt('A low percentage of matches results from one of the following:').
 9591:                     '</p><ul>'.
 9592:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
 9593:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
 9594:                                '<i>'.$cdom.'</i>').'</li>'.
 9595:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 9596:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
 9597:                     '</ul>';
 9598:             }
 9599:             if (($checksec ne '') && (ref($counts{$max_match_format}) eq 'HASH')) {
 9600:                 if ($counts{$max_match_format}{'othersec'}) {
 9601:                     my $percent_nongrade = (100*$counts{$max_match_format}{'othersec'})/($counts{$max_match_format}{'totalanysec'});
 9602:                     my $showpct = sprintf("%.0f",$percent_nongrade).'%';
 9603:                     my $confirmdel = &mt('Are you sure you want to permanently delete this file?');
 9604:                     &js_escape(\$confirmdel);
 9605:                     $output .= '<p class="LC_warning">'.
 9606:                                &mt('Comparison of student IDs in the uploaded file with the course roster found [_1][quant,_2,match,matches][_3] for students in section(s) for which none of your role(s) have privileges to modify grades',
 9607:                                    '<b>',$counts{$max_match_format}{'othersec'},'</b>').
 9608:                                '<br />'.
 9609:                                &mt('Unless you are assigned role(s) which allow modification of grades in additional sections, [_1] of the records in this file will be automatically excluded when you perform bubblesheet grading.','<b>'.$showpct.'</b>').
 9610:                                '</p><p>'.
 9611:                                &mt('If you prefer to delete the file now, use: [_1]').
 9612:                                '<form method="post" name="delupload" action="/adm/grades">'.
 9613:                                '<input type="hidden" name="symb" value="'.$symb.'" />'.
 9614:                                '<input type="hidden" name="domainid" value="'.$cdom.'" />'.
 9615:                                '<input type="hidden" name="courseid" value="'.$cname.'" />'.
 9616:                                '<input type="hidden" name="coursesec" value="'.$env{'request.course.sec'}.'" />'. 
 9617:                                '<input type="hidden" name="uploadedfile" value="'.$fname.'" />'. 
 9618:                                '<input type="hidden" name="command" value="scantronupload_delete" />'.
 9619:                                '<input type="button" name="delbutton" value="'.&mt('Delete Uploaded File').'" onclick="javascript:if (confirm('."'$confirmdel'".')) { document.delupload.submit(); }" />'.
 9620:                                '</form></p>';
 9621:                 }
 9622:             }
 9623:         }
 9624:         if (($context eq 'download') && ($checksec ne '')) {
 9625:             if ((ref($countsref) eq 'HASH') && (ref($counts{$max_match_format}) eq 'HASH')) {
 9626:                 $countsref->{'totalanysec'} = $counts{$max_match_format}{'totalanysec'};
 9627:                 $countsref->{'othersec'} = $counts{$max_match_format}{'othersec'};
 9628:             }
 9629:         } 
 9630:     } elsif ($context ne 'download') {
 9631:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
 9632:     }
 9633:     return $output;
 9634: }
 9635: 
 9636: sub gradable_sections {
 9637:     my $checksec = $env{'request.course.sec'};
 9638:     my @oksecs;
 9639:     if ($checksec) {
 9640:         my %availablesecs = &sections_grade_privs();
 9641:         if (ref($availablesecs{'mgr'}) eq 'ARRAY') {
 9642:             foreach my $sec (@{$availablesecs{'mgr'}}) {
 9643:                 unless (grep(/^\Q$sec\E$/,@oksecs)) {
 9644:                     push(@oksecs,$sec);
 9645:                 }
 9646:             }
 9647:             if (grep(/^all$/,@oksecs)) {
 9648:                 undef($checksec);
 9649:             }
 9650:         }
 9651:     }
 9652:     return($checksec,@oksecs);
 9653: }
 9654: 
 9655: sub sections_grade_privs {
 9656:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9657:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9658:     my %availablesecs = (
 9659:                           mgr => [],
 9660:                           vgr => [],
 9661:                           usc => [],
 9662:                         );
 9663:     my $ccrole = 'cc';
 9664:     if ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Community') {
 9665:         $ccrole = 'co';
 9666:     }
 9667:     my %crsroleshash = &Apache::lonnet::get_my_roles($env{'user.name'},$env{'user.domain'},
 9668:                                                      'userroles',['active'],
 9669:                                                      [$ccrole,'in','cr'],$cdom,1);
 9670:     my $crsid = $cnum.':'.$cdom;
 9671:     foreach my $item (keys(%crsroleshash)) {
 9672:         next unless ($item =~ /^$crsid\:/);
 9673:         my ($crsnum,$crsdom,$role,$sec) = split(/\:/,$item);
 9674:         my $suffix = "/$cdom/$cnum./$cdom/$cnum";
 9675:         if ($sec ne '') {
 9676:             $suffix = "/$cdom/$cnum/$sec./$cdom/$cnum/$sec";
 9677:         }
 9678:         if (($role eq $ccrole) || ($role eq 'in')) {
 9679:             foreach my $priv ('mgr','vgr','usc') { 
 9680:                 unless (grep(/^all$/,@{$availablesecs{$priv}})) {
 9681:                     if ($sec eq '') {
 9682:                         $availablesecs{$priv} = ['all'];
 9683:                     } elsif ($sec ne $env{'request.course.sec'}) {
 9684:                         unless (grep(/^\Q$sec\E$/,@{$availablesecs{$priv}})) {
 9685:                             push(@{$availablesecs{$priv}},$sec);
 9686:                         }
 9687:                     }
 9688:                 }
 9689:             }
 9690:         } elsif ($role =~ m{^cr/}) {
 9691:             foreach my $priv ('mgr','vgr','usc') {
 9692:                 unless (grep(/^all$/,@{$availablesecs{$priv}})) {
 9693:                     if ($env{"user.priv.$role.$suffix"} =~ /:$priv&/) {
 9694:                         if ($sec eq '') {
 9695:                             $availablesecs{$priv} = ['all'];
 9696:                         } elsif ($sec ne $env{'request.course.sec'}) {
 9697:                             unless (grep(/^\Q$sec\E$/,@{$availablesecs{$priv}})) {
 9698:                                 push(@{$availablesecs{$priv}},$sec);
 9699:                             }
 9700:                         }
 9701:                     }
 9702:                 }
 9703:             }
 9704:         }
 9705:     }
 9706:     return %availablesecs;
 9707: }
 9708: 
 9709: sub scantron_upload_delete {
 9710:     my ($r,$symb) = @_;
 9711:     my $filename = $env{'form.uploadedfile'};
 9712:     if ($filename =~ /^scantron_orig_/) {
 9713:         if (&Apache::lonnet::allowed('usc',$env{'form.domainid'}) ||
 9714:             &Apache::lonnet::allowed('usc',
 9715:                                      $env{'form.domainid'}.'_'.$env{'form.courseid'}) ||
 9716:             &Apache::lonnet::allowed('usc',
 9717:                                      $env{'form.domainid'}.'_'.$env{'form.courseid'}.'/'.$env{'form.coursesec'})) {
 9718:             my $uploadurl = '/uploaded/'.$env{'form.domainid'}.'/'.$env{'form.courseid'}.'/'.$env{'form.uploadedfile'};
 9719:             my $retrieval = &Apache::lonnet::getfile($uploadurl);
 9720:             if ($retrieval eq '-1') {
 9721:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
 9722:                           &mt('File requested for deletion not found.'));
 9723:             } else {
 9724:                 $filename =~ s/^scantron_orig_//;
 9725:                 if ($filename ne '') {
 9726:                     my ($is_valid,$numleft);
 9727:                     my %info = &Apache::lonnet::get('scantronupload',[$filename],$env{'form.domainid'},$env{'form.courseid'});
 9728:                     if (keys(%info)) {
 9729:                         if (ref($info{$filename}) eq 'HASH') {
 9730:                             foreach my $timestamp (sort(keys(%{$info{$filename}}))) {
 9731:                                 if ($info{$filename}{$timestamp} eq $env{'user.name'}.':'.$env{'user.domain'}) {
 9732:                                     $is_valid = 1;
 9733:                                     delete($info{$filename}{$timestamp}); 
 9734:                                 }
 9735:                             }
 9736:                             $numleft = scalar(keys(%{$info{$filename}}));
 9737:                         }
 9738:                     }
 9739:                     if ($is_valid) {
 9740:                         my $result = &Apache::lonnet::removeuploadedurl($uploadurl);
 9741:                         if ($result eq 'ok') {
 9742:                             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion successful')).'<br />');
 9743:                             if ($numleft) {
 9744:                                 &Apache::lonnet::put('scantronupload',\%info,$env{'form.domainid'},$env{'form.courseid'});
 9745:                             } else {
 9746:                                 &Apache::lonnet::del('scantronupload',[$filename],$env{'form.domainid'},$env{'form.courseid'});
 9747:                             }
 9748:                         } else {
 9749:                             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
 9750:                                       &mt('Result was [_1]',$result));
 9751:                         }
 9752:                     } else {
 9753:                         $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
 9754:                                   &mt('File requested for deletion was uploaded by a different user.'));
 9755:                     }
 9756:                 } else {
 9757:                     $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
 9758:                               &mt('Filename of bubblesheet data file requested for deletion is invalid.'));
 9759:                 }
 9760:             }
 9761:         } else {
 9762:             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'. 
 9763:                       &mt('You are not permitted to delete bubblesheet data files from the requested course.'));
 9764:         }
 9765:     } else {
 9766:         $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
 9767:                           &mt('Filename of bubblesheet data file requested for deletion is invalid.'));
 9768:     }
 9769:     return;
 9770: }
 9771: 
 9772: sub valid_file {
 9773:     my ($requested_file)=@_;
 9774:     foreach my $filename (sort(&scantron_filenames())) {
 9775: 	if ($requested_file eq $filename) { return 1; }
 9776:     }
 9777:     return 0;
 9778: }
 9779: 
 9780: sub scantron_download_scantron_data {
 9781:     my ($r,$symb) = @_;
 9782:     my $default_form_data=&defaultFormData($symb);
 9783:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9784:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9785:     my $file=$env{'form.scantron_selectfile'};
 9786:     if (! &valid_file($file)) {
 9787: 	$r->print('
 9788: 	<p>
 9789: 	    '.&mt('The requested filename was invalid.').'
 9790:         </p>
 9791: ');
 9792: 	return;
 9793:     }
 9794:     my (%uploader,$is_owner,%counts,$percent);
 9795:     my %uploader = &Apache::lonnet::get('scantronupload',[$file],$cdom,$cname);
 9796:     if (ref($uploader{$file}) eq 'HASH') {
 9797:         foreach my $timestamp (sort { $a <=> $b } keys(%{$uploader{$file}})) {
 9798:             if ($uploader{$file}{$timestamp} eq $env{'user.name'}.':'.$env{'user.domain'}) {
 9799:                 $is_owner = 1;
 9800:                 last;
 9801:             }
 9802:         }
 9803:     }
 9804:     unless ($is_owner) {
 9805:         &validate_uploaded_scantron_file($cdom,$cname,$symb,'scantron_orig_'.$file,'download',\%counts);
 9806:         if ($counts{'totalanysec'}) {
 9807:             my $percent_othersec = (100*$counts{'othersec'})/($counts{'totalanysec'});
 9808:             if ($percent_othersec >= 10) {
 9809:                 my $showpct = sprintf("%.0f",$percent_othersec).'%';
 9810:                 $r->print('<p class="LC_warning">'.
 9811:                           &mt('The original uploaded file includes [_1] or more of records for students for which none of your roles have rights to modify grades, so files are unavailable for download.',$showpct).
 9812:                           '</p>');
 9813:                 return;
 9814:             }
 9815:         }
 9816:     }
 9817:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 9818:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 9819:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 9820:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 9821:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 9822:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 9823:     $r->print('
 9824:     <p>
 9825: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
 9826: 	      '<a href="'.$orig.'">','</a>').'
 9827:     </p>
 9828:     <p>
 9829: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 9830: 	      '<a href="'.$corrected.'">','</a>').'
 9831:     </p>
 9832:     <p>
 9833: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 9834: 	      '<a href="'.$skipped.'">','</a>').'
 9835:     </p>
 9836: ');
 9837:     return '';
 9838: }
 9839: 
 9840: sub checkscantron_results {
 9841:     my ($r,$symb) = @_;
 9842:     if (!$symb) {return '';}
 9843:     my $cid = $env{'request.course.id'};
 9844:     my %lettdig = &Apache::lonnet::letter_to_digits();
 9845:     my $numletts = scalar(keys(%lettdig));
 9846:     my $cnum = $env{'course.'.$cid.'.num'};
 9847:     my $cdom = $env{'course.'.$cid.'.domain'};
 9848:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 9849:     my %record;
 9850:     my %scantron_config =
 9851:         &Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 9852:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 9853:     my ($scanlines,$scan_data)=&scantron_getfile();
 9854:     my $classlist=&Apache::loncoursedata::get_classlist();
 9855:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 9856:     my $navmap=Apache::lonnavmaps::navmap->new();
 9857:     unless (ref($navmap)) {
 9858:         $r->print(&navmap_errormsg());
 9859:         return '';
 9860:     }
 9861:     my $map=$navmap->getResourceByUrl($sequence);
 9862:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 9863:         %grader_randomlists_by_symb,%orderedforcode);
 9864:     if (ref($map)) { 
 9865:         $randomorder=$map->randomorder();
 9866:         $randompick=$map->randompick();
 9867:     }
 9868:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 9869:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 9870:     if ($nav_error) {
 9871:         $r->print(&navmap_errormsg());
 9872:         return '';
 9873:     }
 9874:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 9875:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 9876:     my ($uname,$udom);
 9877:     my (%scandata,%lastname,%bylast);
 9878:     $r->print('
 9879: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 9880: 
 9881:     my @delayqueue;
 9882:     my %completedstudents;
 9883: 
 9884:     my $count=&get_todo_count($scanlines,$scan_data);
 9885:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 9886:     my ($username,$domain,$started);
 9887:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 9888:     if ($nav_error) {
 9889:         $r->print(&navmap_errormsg());
 9890:         return '';
 9891:     }
 9892: 
 9893:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
 9894:     my $start=&Time::HiRes::time();
 9895:     my $i=-1;
 9896: 
 9897:     while ($i<$scanlines->{'count'}) {
 9898:         ($username,$domain,$uname)=('','','');
 9899:         $i++;
 9900:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 9901:         if ($line=~/^[\s\cz]*$/) { next; }
 9902:         if ($started) {
 9903:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 9904:         }
 9905:         $started=1;
 9906:         my $scan_record=
 9907:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 9908:                                                      $scan_data);
 9909:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
 9910:                                               \%idmap,$i)) {
 9911:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9912:                                 'Unable to find a student that matches',1);
 9913:             next;
 9914:         }
 9915:         if (exists $completedstudents{$uname}) {
 9916:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9917:                                 'Student '.$uname.' has multiple sheets',2);
 9918:             next;
 9919:         }
 9920:         my $pid = $scan_record->{'scantron.ID'};
 9921:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 9922:         push(@{$bylast{$lastname{$pid}}},$pid);
 9923:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 9924:         my $user = $uname.':'.$usec;
 9925:         ($username,$domain)=split(/:/,$uname);
 9926: 
 9927:         my $scancode;
 9928:         if ((exists($scan_record->{'scantron.CODE'})) &&
 9929:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 9930:             $scancode = $scan_record->{'scantron.CODE'};
 9931:         } else {
 9932:             $scancode = '';
 9933:         }
 9934: 
 9935:         my @mapresources = @resources;
 9936:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 9937:         my %respnumlookup=();
 9938:         my %startline=();
 9939:         if ($randomorder || $randompick) {
 9940:             @mapresources =
 9941:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 9942:                              \%orderedforcode);
 9943:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
 9944:                                              $scan_record,\@master_seq,\%symb_to_resource,
 9945:                                              \%grader_partids_by_symb,\%orderedforcode,
 9946:                                              \%respnumlookup,\%startline);
 9947:             if ($randompick && $total) {
 9948:                 $lastpos = $total*$scantron_config{'Qlength'};
 9949:             }
 9950:         }
 9951:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 9952:         chomp($scandata{$pid});
 9953:         $scandata{$pid} =~ s/\r$//;
 9954: 
 9955:         my $counter = -1;
 9956:         foreach my $resource (@mapresources) {
 9957:             my $parts;
 9958:             my $ressymb = $resource->symb();
 9959:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 9960:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 9961:                 my $currcode;
 9962:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
 9963:                     $currcode = $scancode;
 9964:                 }
 9965:                 (my $analysis,$parts) =
 9966:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 9967:                                               $username,$domain,undef,
 9968:                                               $bubbles_per_row,$currcode);
 9969:             } else {
 9970:                 $parts = $grader_partids_by_symb{$ressymb};
 9971:             }
 9972:             ($counter,my $recording) =
 9973:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 9974:                                          $scandata{$pid},$parts,
 9975:                                          \%scantron_config,\%lettdig,$numletts,
 9976:                                          $randomorder,$randompick,
 9977:                                          \%respnumlookup,\%startline);
 9978:             $record{$pid} .= $recording;
 9979:         }
 9980:     }
 9981:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 9982:     $r->print('<br />');
 9983:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 9984:     $passed = 0;
 9985:     $failed = 0;
 9986:     $numstudents = 0;
 9987:     foreach my $last (sort(keys(%bylast))) {
 9988:         if (ref($bylast{$last}) eq 'ARRAY') {
 9989:             foreach my $pid (sort(@{$bylast{$last}})) {
 9990:                 my $showscandata = $scandata{$pid};
 9991:                 my $showrecord = $record{$pid};
 9992:                 $showscandata =~ s/\s/&nbsp;/g;
 9993:                 $showrecord =~ s/\s/&nbsp;/g;
 9994:                 if ($scandata{$pid} eq $record{$pid}) {
 9995:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 9996:                     $okstudents .= '<tr class="'.$css_class.'">'.
 9997: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 9998: '</tr>'."\n".
 9999: '<tr class="'.$css_class.'">'."\n".
10000: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
10001:                     $passed ++;
10002:                 } else {
10003:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
10004:                     $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".
10005: '</tr>'."\n".
10006: '<tr class="'.$css_class.'">'."\n".
10007: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
10008: '</tr>'."\n";
10009:                     $failed ++;
10010:                 }
10011:                 $numstudents ++;
10012:             }
10013:         }
10014:     }
10015:     $r->print(
10016:         '<p>'
10017:        .&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).',
10018:             '<b>',
10019:             $numstudents,
10020:             '</b>',
10021:             $env{'form.scantron_maxbubble'})
10022:        .'</p>'
10023:     );
10024:     $r->print('<p>'
10025:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
10026:              .'<br />'
10027:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
10028:              .'</p>'
10029:     );
10030:     if ($passed) {
10031:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
10032:         $r->print(&Apache::loncommon::start_data_table()."\n".
10033:                  &Apache::loncommon::start_data_table_header_row()."\n".
10034:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
10035:                  &Apache::loncommon::end_data_table_header_row()."\n".
10036:                  $okstudents."\n".
10037:                  &Apache::loncommon::end_data_table().'<br />');
10038:     }
10039:     if ($failed) {
10040:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
10041:         $r->print(&Apache::loncommon::start_data_table()."\n".
10042:                  &Apache::loncommon::start_data_table_header_row()."\n".
10043:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
10044:                  &Apache::loncommon::end_data_table_header_row()."\n".
10045:                  $badstudents."\n".
10046:                  &Apache::loncommon::end_data_table()).'<br />'.
10047:                  &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.');  
10048:     }
10049:     $r->print('</form><br />');
10050:     return;
10051: }
10052: 
10053: sub verify_scantron_grading {
10054:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
10055:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
10056:         $respnumlookup,$startline) = @_;
10057:     my ($record,%expected,%startpos);
10058:     return ($counter,$record) if (!ref($resource));
10059:     return ($counter,$record) if (!$resource->is_problem());
10060:     my $symb = $resource->symb();
10061:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
10062:     foreach my $part_id (@{$partids}) {
10063:         $counter ++;
10064:         $expected{$part_id} = 0;
10065:         my $respnum = $counter;
10066:         if ($randomorder || $randompick) {
10067:             $respnum = $respnumlookup->{$counter};
10068:             $startpos{$part_id} = $startline->{$counter} + 1;
10069:         } else {
10070:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
10071:         }
10072:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
10073:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
10074:             foreach my $item (@sub_lines) {
10075:                 $expected{$part_id} += $item;
10076:             }
10077:         } else {
10078:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
10079:         }
10080:     }
10081:     if ($symb) {
10082:         my %recorded;
10083:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
10084:         if ($returnhash{'version'}) {
10085:             my %lasthash=();
10086:             my $version;
10087:             for ($version=1;$version<=$returnhash{'version'};$version++) {
10088:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
10089:                     $lasthash{$key}=$returnhash{$version.':'.$key};
10090:                 }
10091:             }
10092:             foreach my $key (keys(%lasthash)) {
10093:                 if ($key =~ /\.scantron$/) {
10094:                     my $value = &unescape($lasthash{$key});
10095:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
10096:                     if ($value eq '') {
10097:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
10098:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
10099:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
10100:                             }
10101:                         }
10102:                     } else {
10103:                         my @tocheck;
10104:                         my @items = split(//,$value);
10105:                         if (($scantron_config->{'Qon'} eq 'letter') ||
10106:                             ($scantron_config->{'Qon'} eq 'number')) {
10107:                             if (@items < $expected{$part_id}) {
10108:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
10109:                                 my @singles = split(//,$fragment);
10110:                                 foreach my $pos (@singles) {
10111:                                     if ($pos eq ' ') {
10112:                                         push(@tocheck,$pos);
10113:                                     } else {
10114:                                         my $next = shift(@items);
10115:                                         push(@tocheck,$next);
10116:                                     }
10117:                                 }
10118:                             } else {
10119:                                 @tocheck = @items;
10120:                             }
10121:                             foreach my $letter (@tocheck) {
10122:                                 if ($scantron_config->{'Qon'} eq 'letter') {
10123:                                     if ($letter !~ /^[A-J]$/) {
10124:                                         $letter = $scantron_config->{'Qoff'};
10125:                                     }
10126:                                     $recorded{$part_id} .= $letter;
10127:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
10128:                                     my $digit;
10129:                                     if ($letter !~ /^[A-J]$/) {
10130:                                         $digit = $scantron_config->{'Qoff'};
10131:                                     } else {
10132:                                         $digit = $lettdig->{$letter};
10133:                                     }
10134:                                     $recorded{$part_id} .= $digit;
10135:                                 }
10136:                             }
10137:                         } else {
10138:                             @tocheck = @items;
10139:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
10140:                                 my $curr_sub = shift(@tocheck);
10141:                                 my $digit;
10142:                                 if ($curr_sub =~ /^[A-J]$/) {
10143:                                     $digit = $lettdig->{$curr_sub}-1;
10144:                                 }
10145:                                 if ($curr_sub eq 'J') {
10146:                                     $digit += scalar($numletts);
10147:                                 }
10148:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
10149:                                     if ($j == $digit) {
10150:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
10151:                                     } else {
10152:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
10153:                                     }
10154:                                 }
10155:                             }
10156:                         }
10157:                     }
10158:                 }
10159:             }
10160:         }
10161:         foreach my $part_id (@{$partids}) {
10162:             if ($recorded{$part_id} eq '') {
10163:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
10164:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
10165:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
10166:                     }
10167:                 }
10168:             }
10169:             $record .= $recorded{$part_id};
10170:         }
10171:     }
10172:     return ($counter,$record);
10173: }
10174: 
10175: #-------- end of section for handling grading scantron forms -------
10176: #
10177: #-------------------------------------------------------------------
10178: 
10179: #-------------------------- Menu interface -------------------------
10180: #
10181: #--- Href with symb and command ---
10182: 
10183: sub href_symb_cmd {
10184:     my ($symb,$cmd)=@_;
10185:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
10186: }
10187: 
10188: sub grading_menu {
10189:     my ($request,$symb) = @_;
10190:     if (!$symb) {return '';}
10191: 
10192:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
10193:                   'command'=>'individual');
10194:     
10195:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10196: 
10197:     $fields{'command'}='ungraded';
10198:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
10199: 
10200:     $fields{'command'}='table';
10201:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
10202: 
10203:     $fields{'command'}='all_for_one';
10204:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
10205: 
10206:     $fields{'command'}='downloadfilesselect';
10207:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
10208: 
10209:     $fields{'command'} = 'csvform';
10210:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10211:     
10212:     $fields{'command'} = 'processclicker';
10213:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10214:     
10215:     $fields{'command'} = 'scantron_selectphase';
10216:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10217: 
10218:     $fields{'command'} = 'initialverifyreceipt';
10219:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10220:     
10221:     my @menu = ({	categorytitle=>'Hand Grading',
10222:             items =>[
10223:                         {	linktext => 'Select individual students to grade',
10224:                     		url => $url1a,
10225:                     		permission => 'F',
10226:                     		icon => 'grade_students.png',
10227:                     		linktitle => 'Grade current resource for a selection of students.'
10228:                         }, 
10229:                         {       linktext => 'Grade ungraded submissions',
10230:                                 url => $url1b,
10231:                                 permission => 'F',
10232:                                 icon => 'ungrade_sub.png',
10233:                                 linktitle => 'Grade all submissions that have not been graded yet.'
10234:                         },
10235: 
10236:                         {       linktext => 'Grading table',
10237:                                 url => $url1c,
10238:                                 permission => 'F',
10239:                                 icon => 'grading_table.png',
10240:                                 linktitle => 'Grade current resource for all students.'
10241:                         },
10242:                         {       linktext => 'Grade page/folder for one student',
10243:                                 url => $url1d,
10244:                                 permission => 'F',
10245:                                 icon => 'grade_PageFolder.png',
10246:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
10247:                         },
10248:                         {       linktext => 'Download submissions',
10249:                                 url => $url1e,
10250:                                 permission => 'F',
10251:                                 icon => 'download_sub.png',
10252:                                 linktitle => 'Download all students submissions.'
10253:                         }]},
10254:                          { categorytitle=>'Automated Grading',
10255:                items =>[
10256: 
10257:                 	    {	linktext => 'Upload Scores',
10258:                     		url => $url2,
10259:                     		permission => 'F',
10260:                     		icon => 'uploadscores.png',
10261:                     		linktitle => 'Specify a file containing the class scores for current resource.'
10262:                 	    },
10263:                 	    {	linktext => 'Process Clicker',
10264:                     		url => $url3,
10265:                     		permission => 'F',
10266:                     		icon => 'addClickerInfoFile.png',
10267:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
10268:                 	    },
10269:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
10270:                     		url => $url4,
10271:                     		permission => 'F',
10272:                     		icon => 'bubblesheet.png',
10273:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
10274:                 	    },
10275:                             {   linktext => 'Verify Receipt Number',
10276:                                 url => $url5,
10277:                                 permission => 'F',
10278:                                 icon => 'receipt_number.png',
10279:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
10280:                             }
10281: 
10282:                     ]
10283:             });
10284: 
10285:     # Create the menu
10286:     my $Str;
10287:     $Str .= '<form method="post" action="" name="gradingMenu">';
10288:     $Str .= '<input type="hidden" name="command" value="" />'.
10289:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10290: 
10291:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
10292:     return $Str;    
10293: }
10294: 
10295: sub ungraded {
10296:     my ($request)=@_;
10297:     &submit_options($request);
10298: }
10299: 
10300: sub submit_options_sequence {
10301:     my ($request,$symb) = @_;
10302:     if (!$symb) {return '';}
10303:     &commonJSfunctions($request);
10304:     my $result;
10305: 
10306:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10307:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10308:     $result.=&selectfield(0).
10309:             '<input type="hidden" name="command" value="pickStudentPage" />
10310:             <div>
10311:               <input type="submit" value="'.&mt('Next').' &rarr;" />
10312:             </div>
10313:         </div>
10314:   </form>';
10315:     return $result;
10316: }
10317: 
10318: sub submit_options_table {
10319:     my ($request,$symb) = @_;
10320:     if (!$symb) {return '';}
10321:     &commonJSfunctions($request);
10322:     my $is_tool = ($symb =~ /ext\.tool$/);
10323:     my $result;
10324: 
10325:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10326:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10327: 
10328:     $result.=&selectfield(1,$is_tool).
10329:             '<input type="hidden" name="command" value="viewgrades" />
10330:             <div>
10331:               <input type="submit" value="'.&mt('Next').' &rarr;" />
10332:             </div>
10333:         </div>
10334:   </form>';
10335:     return $result;
10336: }
10337: 
10338: sub submit_options_download {
10339:     my ($request,$symb) = @_;
10340:     if (!$symb) {return '';}
10341: 
10342:     my $is_tool = ($symb =~ /ext\.tool$/);
10343:     &commonJSfunctions($request);
10344: 
10345:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10346:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10347:     $result.='
10348: <h2>
10349:   '.&mt('Select Students for whom to Download Submissions').'
10350: </h2>'.&selectfield(1,$is_tool).'
10351:                 <input type="hidden" name="command" value="downloadfileslink" /> 
10352:               <input type="submit" value="'.&mt('Next').' &rarr;" />
10353:             </div>
10354:           </div>
10355: 
10356: 
10357:   </form>';
10358:     return $result;
10359: }
10360: 
10361: #--- Displays the submissions first page -------
10362: sub submit_options {
10363:     my ($request,$symb) = @_;
10364:     if (!$symb) {return '';}
10365: 
10366:     my $is_tool = ($symb =~ /ext\.tool$/);
10367:     &commonJSfunctions($request);
10368:     my $result;
10369: 
10370:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10371: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10372:     $result.=&selectfield(1,$is_tool).'
10373:                 <input type="hidden" name="command" value="submission" /> 
10374: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
10375:             </div>
10376:           </div>
10377:   </form>';
10378:     return $result;
10379: }
10380: 
10381: sub selectfield {
10382:    my ($full,$is_tool)=@_;
10383:    my %options;
10384:    if ($is_tool) {
10385:        %options =
10386:            (&transtatus_options,
10387:             'select_form_order' => ['yes','incorrect','all']);
10388:    } else {
10389:        %options = 
10390:            (&substatus_options,
10391:             'select_form_order' => ['yes','queued','graded','incorrect','all']);
10392:    }
10393:    my $result='<div class="LC_columnSection">
10394:   
10395:     <fieldset>
10396:       <legend>
10397:        '.&mt('Sections').'
10398:       </legend>
10399:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
10400:     </fieldset>
10401:   
10402:     <fieldset>
10403:       <legend>
10404:         '.&mt('Groups').'
10405:       </legend>
10406:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
10407:     </fieldset>
10408:   
10409:     <fieldset>
10410:       <legend>
10411:         '.&mt('Access Status').'
10412:       </legend>
10413:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
10414:     </fieldset>';
10415:     if ($full) {
10416:         my $heading = &mt('Submission Status');
10417:         if ($is_tool) {
10418:             $heading = &mt('Transaction Status');
10419:         }
10420:         $result.='
10421:     <fieldset>
10422:       <legend>
10423:         '.$heading.'
10424:       </legend>'.
10425:        &Apache::loncommon::select_form('all','submitonly',\%options).
10426:    '</fieldset>';
10427:     }
10428:     $result.='</div><br />';
10429:     return $result;
10430: }
10431: 
10432: sub substatus_options {
10433:     return &Apache::lonlocal::texthash(
10434:                                       'yes'       => 'with submissions',
10435:                                       'queued'    => 'in grading queue',
10436:                                       'graded'    => 'with ungraded submissions',
10437:                                       'incorrect' => 'with incorrect submissions',
10438:                                       'all'       => 'with any status',
10439:                                       );
10440: }
10441: 
10442: sub transtatus_options {
10443:     return &Apache::lonlocal::texthash(
10444:                                        'yes'       => 'with score transactions',
10445:                                        'incorrect' => 'with less than full credit',
10446:                                        'all'       => 'with any status',
10447:                                       );
10448: }
10449: 
10450: sub reset_perm {
10451:     undef(%perm);
10452: }
10453: 
10454: sub init_perm {
10455:     &reset_perm();
10456:     foreach my $test_perm ('vgr','mgr','opa','usc') {
10457: 
10458: 	my $scope = $env{'request.course.id'};
10459: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
10460: 
10461: 	    $scope .= '/'.$env{'request.course.sec'};
10462: 	    if ( $perm{$test_perm}=
10463: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
10464: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
10465: 	    } else {
10466: 		delete($perm{$test_perm});
10467: 	    }
10468: 	}
10469:     }
10470: }
10471: 
10472: sub init_old_essays {
10473:     my ($symb,$apath,$adom,$aname) = @_;
10474:     if ($symb ne '') {
10475:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
10476:         if (keys(%essays) > 0) {
10477:             $old_essays{$symb} = \%essays;
10478:         }
10479:     }
10480:     return;
10481: }
10482: 
10483: sub reset_old_essays {
10484:     undef(%old_essays);
10485: }
10486: 
10487: sub gather_clicker_ids {
10488:     my %clicker_ids;
10489: 
10490:     my $classlist = &Apache::loncoursedata::get_classlist();
10491: 
10492:     # Set up a couple variables.
10493:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
10494:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
10495:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
10496: 
10497:     foreach my $student (keys(%$classlist)) {
10498:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
10499:         my $username = $classlist->{$student}->[$username_idx];
10500:         my $domain   = $classlist->{$student}->[$domain_idx];
10501:         my $clickers =
10502: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
10503:         foreach my $id (split(/\,/,$clickers)) {
10504:             $id=~s/^[\#0]+//;
10505:             $id=~s/[\-\:]//g;
10506:             if (exists($clicker_ids{$id})) {
10507: 		$clicker_ids{$id}.=','.$username.':'.$domain;
10508:             } else {
10509: 		$clicker_ids{$id}=$username.':'.$domain;
10510:             }
10511:         }
10512:     }
10513:     return %clicker_ids;
10514: }
10515: 
10516: sub gather_adv_clicker_ids {
10517:     my %clicker_ids;
10518:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
10519:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
10520:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
10521:     foreach my $element (sort(keys(%coursepersonnel))) {
10522:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
10523:             my ($puname,$pudom)=split(/\:/,$person);
10524:             my $clickers =
10525: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
10526:             foreach my $id (split(/\,/,$clickers)) {
10527: 		$id=~s/^[\#0]+//;
10528:                 $id=~s/[\-\:]//g;
10529: 		if (exists($clicker_ids{$id})) {
10530: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
10531: 		} else {
10532: 		    $clicker_ids{$id}=$puname.':'.$pudom;
10533: 		}
10534:             }
10535:         }
10536:     }
10537:     return %clicker_ids;
10538: }
10539: 
10540: sub clicker_grading_parameters {
10541:     return ('gradingmechanism' => 'scalar',
10542:             'upfiletype' => 'scalar',
10543:             'specificid' => 'scalar',
10544:             'pcorrect' => 'scalar',
10545:             'pincorrect' => 'scalar');
10546: }
10547: 
10548: sub process_clicker {
10549:     my ($r,$symb)=@_;
10550:     if (!$symb) {return '';}
10551:     my $result=&checkforfile_js();
10552:     $result.=&Apache::loncommon::start_data_table().
10553:              &Apache::loncommon::start_data_table_header_row().
10554:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
10555:              &Apache::loncommon::end_data_table_header_row().
10556:              &Apache::loncommon::start_data_table_row()."<td>\n";
10557: # Attempt to restore parameters from last session, set defaults if not present
10558:     my %Saveable_Parameters=&clicker_grading_parameters();
10559:     &Apache::loncommon::restore_course_settings('grades_clicker',
10560:                                                  \%Saveable_Parameters);
10561:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
10562:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
10563:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
10564:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
10565: 
10566:     my %checked;
10567:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
10568:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
10569:           $checked{$gradingmechanism}=' checked="checked"';
10570:        }
10571:     }
10572: 
10573:     my $upload=&mt("Evaluate File");
10574:     my $type=&mt("Type");
10575:     my $attendance=&mt("Award points just for participation");
10576:     my $personnel=&mt("Correctness determined from response by course personnel");
10577:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
10578:     my $given=&mt("Correctness determined from given list of answers").' '.
10579:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
10580:     my $pcorrect=&mt("Percentage points for correct solution");
10581:     my $pincorrect=&mt("Percentage points for incorrect solution");
10582:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
10583: 						   {'iclicker' => 'i>clicker',
10584:                                                     'interwrite' => 'interwrite PRS',
10585:                                                     'turning' => 'Turning Technologies'});
10586:     $symb = &Apache::lonenc::check_encrypt($symb);
10587:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
10588: function sanitycheck() {
10589: // Accept only integer percentages
10590:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
10591:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
10592: // Find out grading choice
10593:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
10594:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
10595:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
10596:       }
10597:    }
10598: // By default, new choice equals user selection
10599:    newgradingchoice=gradingchoice;
10600: // Not good to give more points for false answers than correct ones
10601:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
10602:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
10603:    }
10604: // If new choice is attendance only, and old choice was correctness-based, restore defaults
10605:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
10606:       document.forms.gradesupload.pcorrect.value=100;
10607:       document.forms.gradesupload.pincorrect.value=100;
10608:    }
10609: // If the values are different, cannot be attendance only
10610:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
10611:        (gradingchoice=='attendance')) {
10612:        newgradingchoice='personnel';
10613:    }
10614: // Change grading choice to new one
10615:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
10616:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
10617:          document.forms.gradesupload.gradingmechanism[i].checked=true;
10618:       } else {
10619:          document.forms.gradesupload.gradingmechanism[i].checked=false;
10620:       }
10621:    }
10622: // Remember the old state
10623:    document.forms.gradesupload.waschecked.value=newgradingchoice;
10624: }
10625: ENDUPFORM
10626:     $result.= <<ENDUPFORM;
10627: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
10628: <input type="hidden" name="symb" value="$symb" />
10629: <input type="hidden" name="command" value="processclickerfile" />
10630: <input type="file" name="upfile" size="50" />
10631: <br /><label>$type: $selectform</label>
10632: ENDUPFORM
10633:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
10634:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
10635:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
10636: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
10637: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
10638: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
10639: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
10640: <br />&nbsp;&nbsp;&nbsp;
10641: <input type="text" name="givenanswer" size="50" />
10642: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
10643: ENDGRADINGFORM
10644:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
10645:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
10646:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
10647: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
10648: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
10649: </form>
10650: ENDPERCFORM
10651:     $result.='</td>'.
10652:              &Apache::loncommon::end_data_table_row().
10653:              &Apache::loncommon::end_data_table();
10654:     return $result;
10655: }
10656: 
10657: sub process_clicker_file {
10658:     my ($r,$symb) = @_;
10659:     if (!$symb) {return '';}
10660: 
10661:     my %Saveable_Parameters=&clicker_grading_parameters();
10662:     &Apache::loncommon::store_course_settings('grades_clicker',
10663:                                               \%Saveable_Parameters);
10664:     my $result='';
10665:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
10666: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
10667: 	return $result;
10668:     }
10669:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
10670:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
10671:         return $result;
10672:     }
10673:     my $foundgiven=0;
10674:     if ($env{'form.gradingmechanism'} eq 'given') {
10675:         $env{'form.givenanswer'}=~s/^\s*//gs;
10676:         $env{'form.givenanswer'}=~s/\s*$//gs;
10677:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
10678:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
10679:         my @answers=split(/\,/,$env{'form.givenanswer'});
10680:         $foundgiven=$#answers+1;
10681:     }
10682:     my %clicker_ids=&gather_clicker_ids();
10683:     my %correct_ids;
10684:     if ($env{'form.gradingmechanism'} eq 'personnel') {
10685: 	%correct_ids=&gather_adv_clicker_ids();
10686:     }
10687:     if ($env{'form.gradingmechanism'} eq 'specific') {
10688: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
10689: 	   $correct_id=~tr/a-z/A-Z/;
10690: 	   $correct_id=~s/\s//gs;
10691: 	   $correct_id=~s/^[\#0]+//;
10692:            $correct_id=~s/[\-\:]//g;
10693:            if ($correct_id) {
10694: 	      $correct_ids{$correct_id}='specified';
10695:            }
10696:         }
10697:     }
10698:     if ($env{'form.gradingmechanism'} eq 'attendance') {
10699: 	$result.=&mt('Score based on attendance only');
10700:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
10701:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
10702:     } else {
10703: 	my $number=0;
10704: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
10705: 	foreach my $id (sort(keys(%correct_ids))) {
10706: 	    $result.='<br /><tt>'.$id.'</tt> - ';
10707: 	    if ($correct_ids{$id} eq 'specified') {
10708: 		$result.=&mt('specified');
10709: 	    } else {
10710: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
10711: 		$result.=&Apache::loncommon::plainname($uname,$udom);
10712: 	    }
10713: 	    $number++;
10714: 	}
10715:         $result.="</p>\n";
10716:         if ($number==0) {
10717:             $result .=
10718:                  &Apache::lonhtmlcommon::confirm_success(
10719:                      &mt('No IDs found to determine correct answer'),1);
10720:             return $result;
10721:         }
10722:     }
10723:     if (length($env{'form.upfile'}) < 2) {
10724:         $result .=
10725:             &Apache::lonhtmlcommon::confirm_success(
10726:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
10727:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
10728:         return $result;
10729:     }
10730:     my $mimetype;
10731:     if ($env{'form.upfiletype'} eq 'iclicker') {
10732:         my $mm = new File::MMagic;
10733:         $mimetype = $mm->checktype_contents($env{'form.upfile'});
10734:         unless (($mimetype eq 'text/plain') || ($mimetype eq 'text/html')) {
10735:             $result.= '<p>'.
10736:                 &Apache::lonhtmlcommon::confirm_success(
10737:                     &mt('File format is neither csv (iclicker 6) nor xml (iclicker 7)'),1).'</p>';
10738:             return $result;
10739:         }
10740:     } elsif (($env{'form.upfiletype'} ne 'interwrite') && ($env{'form.upfiletype'} ne 'turning')) {
10741:         $result .= '<p>'.
10742:             &Apache::lonhtmlcommon::confirm_success(
10743:                 &mt('Invalid clicker type: choose one of: i>clicker, Interwrite PRS, or Turning Technologies.'),1).'</p>';
10744:         return $result;
10745:     }
10746: 
10747: # Were able to get all the info needed, now analyze the file
10748: 
10749:     $result.=&Apache::loncommon::studentbrowser_javascript();
10750:     $symb = &Apache::lonenc::check_encrypt($symb);
10751:     $result.=&Apache::loncommon::start_data_table().
10752:              &Apache::loncommon::start_data_table_header_row().
10753:              '<th>'.&mt('Evaluate clicker file').'</th>'.
10754:              &Apache::loncommon::end_data_table_header_row().
10755:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
10756: <td>
10757: <form method="post" action="/adm/grades" name="clickeranalysis">
10758: <input type="hidden" name="symb" value="$symb" />
10759: <input type="hidden" name="command" value="assignclickergrades" />
10760: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
10761: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
10762: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
10763: ENDHEADER
10764:     if ($env{'form.gradingmechanism'} eq 'given') {
10765:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
10766:     } 
10767:     my %responses;
10768:     my @questiontitles;
10769:     my $errormsg='';
10770:     my $number=0;
10771:     if ($env{'form.upfiletype'} eq 'iclicker') {
10772:         if ($mimetype eq 'text/plain') {
10773:             ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
10774:         } elsif ($mimetype eq 'text/html') {
10775:             ($errormsg,$number)=&iclickerxml_eval(\@questiontitles,\%responses);
10776:         }
10777:     } elsif ($env{'form.upfiletype'} eq 'interwrite') {
10778:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
10779:     } elsif ($env{'form.upfiletype'} eq 'turning') {
10780:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
10781:     }
10782:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
10783:              '<input type="hidden" name="number" value="'.$number.'" />'.
10784:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
10785:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
10786:              '<br />';
10787:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
10788:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
10789:        return $result;
10790:     } 
10791: # Remember Question Titles
10792: # FIXME: Possibly need delimiter other than ":"
10793:     for (my $i=0;$i<$number;$i++) {
10794:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
10795:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
10796:     }
10797:     my $correct_count=0;
10798:     my $student_count=0;
10799:     my $unknown_count=0;
10800: # Match answers with usernames
10801: # FIXME: Possibly need delimiter other than ":"
10802:     foreach my $id (keys(%responses)) {
10803:        if ($correct_ids{$id}) {
10804:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
10805:           $correct_count++;
10806:        } elsif ($clicker_ids{$id}) {
10807:           if ($clicker_ids{$id}=~/\,/) {
10808: # More than one user with the same clicker!
10809:              $result.="</td>".&Apache::loncommon::end_data_table_row().
10810:                            &Apache::loncommon::start_data_table_row()."<td>".
10811:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
10812:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10813:                            "<select name='multi".$id."'>";
10814:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
10815:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
10816:              }
10817:              $result.='</select>';
10818:              $unknown_count++;
10819:           } else {
10820: # Good: found one and only one user with the right clicker
10821:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
10822:              $student_count++;
10823:           }
10824:        } else {
10825:           $result.="</td>".&Apache::loncommon::end_data_table_row().
10826:                            &Apache::loncommon::start_data_table_row()."<td>".
10827:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
10828:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10829:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
10830:                    "\n".&mt("Domain").": ".
10831:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
10832:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,'',$id);
10833:           $unknown_count++;
10834:        }
10835:     }
10836:     $result.='<hr />'.
10837:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
10838:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
10839:        if ($correct_count==0) {
10840:           $errormsg.="Found no correct answers for grading!";
10841:        } elsif ($correct_count>1) {
10842:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
10843:        }
10844:     }
10845:     if ($number<1) {
10846:        $errormsg.="Found no questions.";
10847:     }
10848:     if ($errormsg) {
10849:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
10850:     } else {
10851:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
10852:     }
10853:     $result.='</form></td>'.
10854:              &Apache::loncommon::end_data_table_row().
10855:              &Apache::loncommon::end_data_table();
10856:     return $result;
10857: }
10858: 
10859: sub iclicker_eval {
10860:     my ($questiontitles,$responses)=@_;
10861:     my $number=0;
10862:     my $errormsg='';
10863:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10864:         my %components=&Apache::loncommon::record_sep($line);
10865:         my @entries=map {$components{$_}} (sort(keys(%components)));
10866: 	if ($entries[0] eq 'Question') {
10867: 	    for (my $i=3;$i<$#entries;$i+=6) {
10868: 		$$questiontitles[$number]=$entries[$i];
10869: 		$number++;
10870: 	    }
10871: 	}
10872: 	if ($entries[0]=~/^\#/) {
10873: 	    my $id=$entries[0];
10874: 	    my @idresponses;
10875: 	    $id=~s/^[\#0]+//;
10876: 	    for (my $i=0;$i<$number;$i++) {
10877: 		my $idx=3+$i*6;
10878:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
10879: 		push(@idresponses,$entries[$idx]);
10880: 	    }
10881: 	    $$responses{$id}=join(',',@idresponses);
10882: 	}
10883:     }
10884:     return ($errormsg,$number);
10885: }
10886: 
10887: sub iclickerxml_eval {
10888:     my ($questiontitles,$responses)=@_;
10889:     my $number=0;
10890:     my $errormsg='';
10891:     my @state;
10892:     my %respbyid;
10893:     my $p = HTML::Parser->new
10894:     (
10895:         xml_mode => 1,
10896:         start_h =>
10897:             [sub {
10898:                  my ($tagname,$attr) = @_;
10899:                  push(@state,$tagname);
10900:                  if ("@state" eq "ssn p") {
10901:                      my $title = $attr->{qn};
10902:                      $title =~ s/(^\s+|\s+$)//g;
10903:                      $questiontitles->[$number]=$title;
10904:                  } elsif ("@state" eq "ssn p v") {
10905:                      my $id = $attr->{id};
10906:                      my $entry = $attr->{ans};
10907:                      $id=~s/^[\#0]+//;
10908:                      $entry =~s/[^a-zA-Z0-9\.\*\-\+]+//g;
10909:                      $respbyid{$id}[$number] = $entry;
10910:                  }
10911:             }, "tagname, attr"],
10912:          end_h =>
10913:                [sub {
10914:                    my ($tagname) = @_;
10915:                    if ("@state" eq "ssn p") {
10916:                        $number++;
10917:                    }
10918:                    pop(@state);
10919:                 }, "tagname"],
10920:     );
10921: 
10922:     $p->parse($env{'form.upfile'});
10923:     $p->eof;
10924:     foreach my $id (keys(%respbyid)) {
10925:         $responses->{$id}=join(',',@{$respbyid{$id}});
10926:     }
10927:     return ($errormsg,$number);
10928: }
10929: 
10930: sub interwrite_eval {
10931:     my ($questiontitles,$responses)=@_;
10932:     my $number=0;
10933:     my $errormsg='';
10934:     my $skipline=1;
10935:     my $questionnumber=0;
10936:     my %idresponses=();
10937:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10938:         my %components=&Apache::loncommon::record_sep($line);
10939:         my @entries=map {$components{$_}} (sort(keys(%components)));
10940:         if ($entries[1] eq 'Time') { $skipline=0; next; }
10941:         if ($entries[1] eq 'Response') { $skipline=1; }
10942:         next if $skipline;
10943:         if ($entries[0]!=$questionnumber) {
10944:            $questionnumber=$entries[0];
10945:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
10946:            $number++;
10947:         }
10948:         my $id=$entries[4];
10949:         $id=~s/^[\#0]+//;
10950:         $id=~s/^v\d*\://i;
10951:         $id=~s/[\-\:]//g;
10952:         $idresponses{$id}[$number]=$entries[6];
10953:     }
10954:     foreach my $id (keys(%idresponses)) {
10955:        $$responses{$id}=join(',',@{$idresponses{$id}});
10956:        $$responses{$id}=~s/^\s*\,//;
10957:     }
10958:     return ($errormsg,$number);
10959: }
10960: 
10961: sub turning_eval {
10962:     my ($questiontitles,$responses)=@_;
10963:     my $number=0;
10964:     my $errormsg='';
10965:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10966:         my %components=&Apache::loncommon::record_sep($line);
10967:         my @entries=map {$components{$_}} (sort(keys(%components)));
10968:         if ($#entries>$number) { $number=$#entries; }
10969:         my $id=$entries[0];
10970:         my @idresponses;
10971:         $id=~s/^[\#0]+//;
10972:         unless ($id) { next; }
10973:         for (my $idx=1;$idx<=$#entries;$idx++) {
10974:             $entries[$idx]=~s/\,/\;/g;
10975:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
10976:             push(@idresponses,$entries[$idx]);
10977:         }
10978:         $$responses{$id}=join(',',@idresponses);
10979:     }
10980:     for (my $i=1; $i<=$number; $i++) {
10981:         $$questiontitles[$i]=&mt('Question [_1]',$i);
10982:     }
10983:     return ($errormsg,$number);
10984: }
10985: 
10986: 
10987: sub assign_clicker_grades {
10988:     my ($r,$symb) = @_;
10989:     if (!$symb) {return '';}
10990: # See which part we are saving to
10991:     my $res_error;
10992:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
10993:     if ($res_error) {
10994:         return &navmap_errormsg();
10995:     }
10996: # FIXME: This should probably look for the first handgradeable part
10997:     my $part=$$partlist[0];
10998: # Start screen output
10999:     my $result = &Apache::loncommon::start_data_table().
11000:                  &Apache::loncommon::start_data_table_header_row().
11001:                  '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
11002:                  &Apache::loncommon::end_data_table_header_row().
11003:                  &Apache::loncommon::start_data_table_row().'<td>';
11004: # Get correct result
11005: # FIXME: Possibly need delimiter other than ":"
11006:     my @correct=();
11007:     my $gradingmechanism=$env{'form.gradingmechanism'};
11008:     my $number=$env{'form.number'};
11009:     if ($gradingmechanism ne 'attendance') {
11010:        foreach my $key (keys(%env)) {
11011:           if ($key=~/^form\.correct\:/) {
11012:              my @input=split(/\,/,$env{$key});
11013:              for (my $i=0;$i<=$#input;$i++) {
11014:                  if (($correct[$i]) && ($input[$i]) &&
11015:                      ($correct[$i] ne $input[$i])) {
11016:                     $result.='<br /><span class="LC_warning">'.
11017:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
11018:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
11019:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
11020:                     $correct[$i]=$input[$i];
11021:                  }
11022:              }
11023:           }
11024:        }
11025:        for (my $i=0;$i<$number;$i++) {
11026:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
11027:              $result.='<br /><span class="LC_error">'.
11028:                       &mt('No correct result given for question "[_1]"!',
11029:                           $env{'form.question:'.$i}).'</span>';
11030:           }
11031:        }
11032:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
11033:     }
11034: # Start grading
11035:     my $pcorrect=$env{'form.pcorrect'};
11036:     my $pincorrect=$env{'form.pincorrect'};
11037:     my $storecount=0;
11038:     my %users=();
11039:     foreach my $key (keys(%env)) {
11040:        my $user='';
11041:        if ($key=~/^form\.student\:(.*)$/) {
11042:           $user=$1;
11043:        }
11044:        if ($key=~/^form\.unknown\:(.*)$/) {
11045:           my $id=$1;
11046:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
11047:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
11048:           } elsif ($env{'form.multi'.$id}) {
11049:              $user=$env{'form.multi'.$id};
11050:           }
11051:        }
11052:        if ($user) {
11053:           if ($users{$user}) {
11054:              $result.='<br /><span class="LC_warning">'.
11055:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
11056:                       '</span><br />';
11057:           }
11058:           $users{$user}=1; 
11059:           my @answer=split(/\,/,$env{$key});
11060:           my $sum=0;
11061:           my $realnumber=$number;
11062:           for (my $i=0;$i<$number;$i++) {
11063:              if  ($correct[$i] eq '-') {
11064:                 $realnumber--;
11065:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/)) {
11066:                 if ($gradingmechanism eq 'attendance') {
11067:                    $sum+=$pcorrect;
11068:                 } elsif ($correct[$i] eq '*') {
11069:                    $sum+=$pcorrect;
11070:                 } else {
11071: # We actually grade if correct or not
11072:                    my $increment=$pincorrect;
11073: # Special case: numerical answer "0"
11074:                    if ($correct[$i] eq '0') {
11075:                       if ($answer[$i]=~/^[0\.]+$/) {
11076:                          $increment=$pcorrect;
11077:                       }
11078: # General numerical answer, both evaluate to something non-zero
11079:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
11080:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
11081:                          $increment=$pcorrect;
11082:                       }
11083: # Must be just alphanumeric
11084:                    } elsif ($answer[$i] eq $correct[$i]) {
11085:                       $increment=$pcorrect;
11086:                    }
11087:                    $sum+=$increment;
11088:                 }
11089:              }
11090:           }
11091:           my $ave=$sum/(100*$realnumber);
11092: # Store
11093:           my ($username,$domain)=split(/\:/,$user);
11094:           my %grades=();
11095:           $grades{"resource.$part.solved"}='correct_by_override';
11096:           $grades{"resource.$part.awarded"}=$ave;
11097:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
11098:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
11099:                                                  $env{'request.course.id'},
11100:                                                  $domain,$username);
11101:           if ($returncode ne 'ok') {
11102:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
11103:           } else {
11104:              $storecount++;
11105:           }
11106:        }
11107:     }
11108: # We are done
11109:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
11110:              '</td>'.
11111:              &Apache::loncommon::end_data_table_row().
11112:              &Apache::loncommon::end_data_table();
11113:     return $result;
11114: }
11115: 
11116: sub navmap_errormsg {
11117:     return '<div class="LC_error">'.
11118:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
11119:            &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>').
11120:            '</div>';
11121: }
11122: 
11123: sub startpage {
11124:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js,$onload) = @_;
11125:     my %args;
11126:     if ($onload) {
11127:          my %loaditems = (
11128:                         'onload' => $onload,
11129:                       );
11130:          $args{'add_entries'} = \%loaditems;
11131:     }
11132:     if ($nomenu) {
11133:         $args{'only_body'} = 1; 
11134:         $r->print(&Apache::loncommon::start_page("Student's Version",$js,\%args));
11135:     } else {
11136:         unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
11137:         $args{'bread_crumbs'} = $crumbs;
11138:         $r->print(&Apache::loncommon::start_page('Grading',$js,\%args));
11139:         if ($env{'request.course.id'}) {
11140:             &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
11141:         }
11142:     }
11143:     unless ($nodisplayflag) {
11144:         $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
11145:     }
11146: }
11147: 
11148: sub select_problem {
11149:     my ($r)=@_;
11150:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
11151:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1,undef,undef,1,1));
11152:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
11153:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
11154: }
11155: 
11156: sub handler {
11157:     my $request=$_[0];
11158:     &reset_caches();
11159:     if ($request->header_only) {
11160:         &Apache::loncommon::content_type($request,'text/html');
11161:         $request->send_http_header;
11162:         return OK;
11163:     }
11164:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
11165: 
11166: # see what command we need to execute
11167: 
11168:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
11169:     my $command=$commands[0];
11170: 
11171:     &init_perm();
11172:     if (!$env{'request.course.id'}) {
11173:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
11174:                 ($command =~ /^scantronupload/)) {
11175:             # Not in a course.
11176:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
11177:             return HTTP_NOT_ACCEPTABLE;
11178:         }
11179:     } elsif (!%perm) {
11180:         $request->internal_redirect('/adm/quickgrades');
11181:         return OK;
11182:     }
11183:     &Apache::loncommon::content_type($request,'text/html');
11184:     $request->send_http_header;
11185: 
11186:     if ($#commands > 0) {
11187: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
11188:     }
11189: 
11190: # see what the symb is
11191: 
11192:     my $symb=$env{'form.symb'};
11193:     unless ($symb) {
11194:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
11195:        $symb=&Apache::lonnet::symbread($url);
11196:     }
11197:     &Apache::lonenc::check_decrypt(\$symb);
11198: 
11199:     $ssi_error = 0;
11200:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
11201: #
11202: # Not called from a resource, but inside a course
11203: #    
11204:         &startpage($request,undef,[],1,1);
11205:         &select_problem($request);
11206:     } else {
11207: 	if ($command eq 'submission' && $perm{'vgr'}) {
11208:             my ($stuvcurrent,$stuvdisp,$versionform,$js);
11209:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
11210:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
11211:                     &choose_task_version_form($symb,$env{'form.student'},
11212:                                               $env{'form.userdom'});
11213:             }
11214:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
11215:             if ($versionform) {
11216:                 $request->print($versionform);
11217:             }
11218:             $request->print('<br clear="all" />');
11219: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
11220:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
11221:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
11222:                 &choose_task_version_form($symb,$env{'form.student'},
11223:                                           $env{'form.userdom'},
11224:                                           $env{'form.inhibitmenu'});
11225:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
11226:             if ($versionform) {
11227:                 $request->print($versionform);
11228:             }
11229:             $request->print('<br clear="all" />');
11230:             $request->print(&show_previous_task_version($request,$symb));
11231: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
11232:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
11233:                                        {href=>'',text=>'Select student'}],1,1);
11234: 	    &pickStudentPage($request,$symb);
11235: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
11236:             &startpage($request,$symb,
11237:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
11238:                                        {href=>'',text=>'Select student'},
11239:                                        {href=>'',text=>'Grade student'}],1,1);
11240: 	    &displayPage($request,$symb);
11241: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
11242:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
11243:                                        {href=>'',text=>'Select student'},
11244:                                        {href=>'',text=>'Grade student'},
11245:                                        {href=>'',text=>'Store grades'}],1,1);
11246: 	    &updateGradeByPage($request,$symb);
11247: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
11248:             &startpage($request,$symb,[{href=>'',text=>'...'},
11249:                                        {href=>'',text=>'Modify grades'}]);
11250: 	    &processGroup($request,$symb);
11251: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
11252:             &startpage($request,$symb);
11253: 	    $request->print(&grading_menu($request,$symb));
11254: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
11255:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
11256: 	    $request->print(&submit_options($request,$symb));
11257:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
11258:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
11259:             $request->print(&listStudents($request,$symb,'graded'));
11260:         } elsif ($command eq 'table' && $perm{'vgr'}) {
11261:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
11262:             $request->print(&submit_options_table($request,$symb));
11263:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
11264:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
11265:             $request->print(&submit_options_sequence($request,$symb));
11266: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
11267:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
11268: 	    $request->print(&viewgrades($request,$symb));
11269: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
11270:             &startpage($request,$symb,[{href=>'',text=>'...'},
11271:                                        {href=>'',text=>'Store grades'}]);
11272: 	    $request->print(&processHandGrade($request,$symb));
11273: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
11274:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
11275:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
11276:                                                                              text=>"Modify grades"},
11277:                                        {href=>'', text=>"Store grades"}]);
11278: 	    $request->print(&editgrades($request,$symb));
11279:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
11280:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
11281:             $request->print(&initialverifyreceipt($request,$symb));
11282: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
11283:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
11284:                                        {href=>'',text=>'Verification Result'}]);
11285: 	    $request->print(&verifyreceipt($request,$symb));
11286:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
11287:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
11288:             $request->print(&process_clicker($request,$symb));
11289:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
11290:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
11291:                                        {href=>'', text=>'Process clicker file'}]);
11292:             $request->print(&process_clicker_file($request,$symb));
11293:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
11294:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
11295:                                        {href=>'', text=>'Process clicker file'},
11296:                                        {href=>'', text=>'Store grades'}]);
11297:             $request->print(&assign_clicker_grades($request,$symb));
11298: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
11299:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11300: 	    $request->print(&upcsvScores_form($request,$symb));
11301: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
11302:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11303: 	    $request->print(&csvupload($request,$symb));
11304: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
11305:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11306: 	    $request->print(&csvuploadmap($request,$symb));
11307: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
11308: 	    if ($env{'form.associate'} ne 'Reverse Association') {
11309:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11310: 		$request->print(&csvuploadoptions($request,$symb));
11311: 	    } else {
11312: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
11313: 		    $env{'form.upfile_associate'} = 'reverse';
11314: 		} else {
11315: 		    $env{'form.upfile_associate'} = 'forward';
11316: 		}
11317:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11318: 		$request->print(&csvuploadmap($request,$symb));
11319: 	    }
11320: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
11321:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11322: 	    $request->print(&csvuploadassign($request,$symb));
11323: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
11324:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
11325:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
11326: 	    $request->print(&scantron_selectphase($request,undef,$symb));
11327:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
11328:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11329:  	    $request->print(&scantron_do_warning($request,$symb));
11330: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
11331:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11332: 	    $request->print(&scantron_validate_file($request,$symb));
11333: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
11334:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11335: 	    $request->print(&scantron_process_students($request,$symb));
11336:  	} elsif ($command eq 'scantronupload' && 
11337:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
11338:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
11339:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
11340:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
11341:  	} elsif ($command eq 'scantronupload_save' &&
11342:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
11343:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11344:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
11345:  	} elsif ($command eq 'scantron_download' && ($perm{'usc'} || $perm{'mgr'})) {
11346:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11347:  	    $request->print(&scantron_download_scantron_data($request,$symb));
11348:         } elsif ($command eq 'scantronupload_delete' &&
11349:                  (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
11350:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11351:             &scantron_upload_delete($request,$symb);
11352:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
11353:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11354:             $request->print(&checkscantron_results($request,$symb));
11355:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
11356:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
11357:             $request->print(&submit_options_download($request,$symb));
11358:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
11359:             &startpage($request,$symb,
11360:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
11361:     {href=>'', text=>'Download submitted files'}]);
11362:             &submit_download_link($request,$symb);
11363: 	} elsif ($command) {
11364:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
11365: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
11366: 	}
11367:     }
11368:     if ($ssi_error) {
11369: 	&ssi_print_error($request);
11370:     }
11371:     if ($env{'form.inhibitmenu'}) {
11372:         $request->print(&Apache::loncommon::end_page());
11373:     } elsif ($env{'request.course.id'}) {
11374:         &Apache::lonquickgrades::endGradeScreen($request);
11375:     }
11376:     &reset_caches();
11377:     return OK;
11378: }
11379: 
11380: 1;
11381: 
11382: __END__;
11383: 
11384: 
11385: =head1 NAME
11386: 
11387: Apache::grades
11388: 
11389: =head1 SYNOPSIS
11390: 
11391: Handles the viewing of grades.
11392: 
11393: This is part of the LearningOnline Network with CAPA project
11394: described at http://www.lon-capa.org.
11395: 
11396: =head1 OVERVIEW
11397: 
11398: Do an ssi with retries:
11399: While I'd love to factor out this with the version in lonprintout,
11400: 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
11401: I'm not quite ready to invent (e.g. an ssi_with_retry object).
11402: 
11403: At least the logic that drives this has been pulled out into loncommon.
11404: 
11405: 
11406: 
11407: ssi_with_retries - Does the server side include of a resource.
11408:                      if the ssi call returns an error we'll retry it up to
11409:                      the number of times requested by the caller.
11410:                      If we still have a problem, no text is appended to the
11411:                      output and we set some global variables.
11412:                      to indicate to the caller an SSI error occurred.  
11413:                      All of this is supposed to deal with the issues described
11414:                      in LON-CAPA BZ 5631 see:
11415:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
11416:                      by informing the user that this happened.
11417: 
11418: Parameters:
11419:   resource   - The resource to include.  This is passed directly, without
11420:                interpretation to lonnet::ssi.
11421:   form       - The form hash parameters that guide the interpretation of the resource
11422:                
11423:   retries    - Number of retries allowed before giving up completely.
11424: Returns:
11425:   On success, returns the rendered resource identified by the resource parameter.
11426: Side Effects:
11427:   The following global variables can be set:
11428:    ssi_error                - If an unrecoverable error occurred this becomes true.
11429:                               It is up to the caller to initialize this to false
11430:                               if desired.
11431:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
11432:                               of the resource that could not be rendered by the ssi
11433:                               call.
11434:    ssi_error_message   - The error string fetched from the ssi response
11435:                               in the event of an error.
11436: 
11437: 
11438: =head1 HANDLER SUBROUTINE
11439: 
11440: ssi_with_retries()
11441: 
11442: =head1 SUBROUTINES
11443: 
11444: =over
11445: 
11446: =head1 Routines to display previous version of a Task for a specific student
11447: 
11448: Tasks are graded pass/fail. Students who have yet to pass a particular Task
11449: can receive another opportunity. Access to tasks is slot-based. If a slot
11450: requires a proctor to check-in the student, a new version of the Task will
11451: be created when the student is checked in to the new opportunity.
11452: 
11453: If a particular student has tried two or more versions of a particular task,
11454: the submission screen provides a user with vgr privileges (e.g., a Course
11455: Coordinator) the ability to display a previous version worked on by the
11456: student.  By default, the current version is displayed. If a previous version
11457: has been selected for display, submission data are only shown that pertain
11458: to that particular version, and the interface to submit grades is not shown.
11459: 
11460: =over 4
11461: 
11462: =item show_previous_task_version()
11463: 
11464: Displays a specified version of a student's Task, as the student sees it.
11465: 
11466: Inputs: 2
11467:         request - request object
11468:         symb    - unique symb for current instance of resource
11469: 
11470: Output: None.
11471: 
11472: Side Effects: calls &show_problem() to print version of Task, with
11473:               version contained in form item: $env{'form.previousversion'}
11474: 
11475: =item choose_task_version_form()
11476: 
11477: Displays a web form used to select which version of a student's view of a
11478: Task should be displayed.  Either launches a pop-up window, or replaces
11479: content in existing pop-up, or replaces page in main window.
11480: 
11481: Inputs: 4
11482:         symb    - unique symb for current instance of resource
11483:         uname   - username of student
11484:         udom    - domain of student
11485:         nomenu  - 1 if display is in a pop-up window, and hence no menu
11486:                   breadcrumbs etc., are displayed
11487: 
11488: Output: 4
11489:         current   - student's current version
11490:         displayed - student's version being displayed
11491:         result    - scalar containing HTML for web form used to switch to
11492:                     a different version (or a link to close window, if pop-up).
11493:         js        - javascript for processing selection in versions web form
11494: 
11495: Side Effects: None.
11496: 
11497: =item previous_display_javascript()
11498: 
11499: Inputs: 2
11500:         nomenu  - 1 if display is in a pop-up window, and hence no menu
11501:                   breadcrumbs etc., are displayed.
11502:         current - student's current version number.
11503: 
11504: Output: 1
11505:         js      - javascript for processing selection in versions web form.
11506: 
11507: Side Effects: None.
11508: 
11509: =back
11510: 
11511: =head1 Routines to process bubblesheet data.
11512: 
11513: =over 4
11514: 
11515: =item scantron_get_correction() : 
11516: 
11517:    Builds the interface screen to interact with the operator to fix a
11518:    specific error condition in a specific scanline
11519: 
11520:  Arguments:
11521:     $r           - Apache request object
11522:     $i           - number of the current scanline
11523:     $scan_record - hash ref as returned from &scantron_parse_scanline()
11524:     $scan_config - hash ref as returned from &Apache::lonnet::get_scantron_config()
11525:     $line        - full contents of the current scanline
11526:     $error       - error condition, valid values are
11527:                    'incorrectCODE', 'duplicateCODE',
11528:                    'doublebubble', 'missingbubble',
11529:                    'duplicateID', 'incorrectID'
11530:     $arg         - extra information needed
11531:        For errors:
11532:          - duplicateID   - paper number that this studentID was seen before on
11533:          - duplicateCODE - array ref of the paper numbers this CODE was
11534:                            seen on before
11535:          - incorrectCODE - current incorrect CODE 
11536:          - doublebubble  - array ref of the bubble lines that have double
11537:                            bubble errors
11538:          - missingbubble - array ref of the bubble lines that have missing
11539:                            bubble errors
11540: 
11541:    $randomorder - True if exam folder has randomorder set
11542:    $randompick  - True if exam folder has randompick set
11543:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
11544:                      for current line to question number used for same question
11545:                      in "Master Seqence" (as seen by Course Coordinator).
11546:    $startline   - Reference to hash where key is question number (0 is first)
11547:                   and value is number of first bubble line for current student
11548:                   or code-based randompick and/or randomorder.
11549: 
11550: 
11551: 
11552: =item  scantron_get_maxbubble() : 
11553: 
11554:    Arguments:
11555:        $nav_error  - Reference to scalar which is a flag to indicate a
11556:                       failure to retrieve a navmap object.
11557:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
11558:        calling routine should trap the error condition and display the warning
11559:        found in &navmap_errormsg().
11560: 
11561:        $scantron_config - Reference to bubblesheet format configuration hash.
11562: 
11563:    Returns the maximum number of bubble lines that are expected to
11564:    occur. Does this by walking the selected sequence rendering the
11565:    resource and then checking &Apache::lonxml::get_problem_counter()
11566:    for what the current value of the problem counter is.
11567: 
11568:    Caches the results to $env{'form.scantron_maxbubble'},
11569:    $env{'form.scantron.bubble_lines.n'}, 
11570:    $env{'form.scantron.first_bubble_line.n'} and
11571:    $env{"form.scantron.sub_bubblelines.n"}
11572:    which are the total number of bubble lines, the number of bubble
11573:    lines for response n and number of the first bubble line for response n,
11574:    and a comma separated list of numbers of bubble lines for sub-questions
11575:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
11576: 
11577: 
11578: =item  scantron_validate_missingbubbles() : 
11579: 
11580:    Validates all scanlines in the selected file to not have any
11581:     answers that don't have bubbles that have not been verified
11582:     to be bubble free.
11583: 
11584: =item  scantron_process_students() : 
11585: 
11586:    Routine that does the actual grading of the bubblesheet information.
11587: 
11588:    The parsed scanline hash is added to %env 
11589: 
11590:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
11591:    foreach resource , with the form data of
11592: 
11593: 	'submitted'     =>'scantron' 
11594: 	'grade_target'  =>'grade',
11595: 	'grade_username'=> username of student
11596: 	'grade_domain'  => domain of student
11597: 	'grade_courseid'=> of course
11598: 	'grade_symb'    => symb of resource to grade
11599: 
11600:     This triggers a grading pass. The problem grading code takes care
11601:     of converting the bubbled letter information (now in %env) into a
11602:     valid submission.
11603: 
11604: =item  scantron_upload_scantron_data() :
11605: 
11606:     Creates the screen for adding a new bubblesheet data file to a course.
11607: 
11608: =item  scantron_upload_scantron_data_save() : 
11609: 
11610:    Adds a provided bubble information data file to the course if user
11611:    has the correct privileges to do so.
11612: 
11613: = item scantron_upload_delete() :
11614: 
11615:    Deletes a previously uploaded bubble information data file, if user
11616:    was the one who uploaded the file, and has the privileges to do so.
11617: 
11618: =item  valid_file() :
11619: 
11620:    Validates that the requested bubble data file exists in the course.
11621: 
11622: =item  scantron_download_scantron_data() : 
11623: 
11624:    Shows a list of the three internal files (original, corrected,
11625:    skipped) for a specific bubblesheet data file that exists in the
11626:    course.
11627: 
11628: =item  scantron_validate_ID() : 
11629: 
11630:    Validates all scanlines in the selected file to not have any
11631:    invalid or underspecified student/employee IDs
11632: 
11633: =item navmap_errormsg() :
11634: 
11635:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
11636:    Should be called whenever the request to instantiate a navmap object fails.
11637: 
11638: =back
11639: 
11640: =back
11641: 
11642: =cut

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