File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.751: download - view: text, annotated - select for diffs
Mon Oct 8 19:04:06 2018 UTC (5 years, 6 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- In grading interface render tex within <m> </m> tags when displaying a
  student's submission to an essayresponse item.

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.751 2018/10/08 19:04:06 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 String::Similarity;
   50: use LONCAPA;
   51: 
   52: use POSIX qw(floor);
   53: 
   54: 
   55: 
   56: my %perm=();
   57: my %old_essays=();
   58: 
   59: #  These variables are used to recover from ssi errors
   60: 
   61: my $ssi_retries = 5;
   62: my $ssi_error;
   63: my $ssi_error_resource;
   64: my $ssi_error_message;
   65: 
   66: 
   67: sub ssi_with_retries {
   68:     my ($resource, $retries, %form) = @_;
   69:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
   70:     if ($response->is_error) {
   71: 	$ssi_error          = 1;
   72: 	$ssi_error_resource = $resource;
   73: 	$ssi_error_message  = $response->code . " " . $response->message;
   74:     }
   75: 
   76:     return $content;
   77: 
   78: }
   79: #
   80: #  Prodcuces an ssi retry failure error message to the user:
   81: #
   82: 
   83: sub ssi_print_error {
   84:     my ($r) = @_;
   85:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
   86:     $r->print('
   87: <br />
   88: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
   89: <p>
   90: '.&mt('Unable to retrieve a resource from a server:').'<br />
   91: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
   92: '.&mt('Error:').' '.$ssi_error_message.'
   93: </p>
   94: <p>'.
   95: &mt('It is recommended that you try again later, as this error may mean the server was just temporarily unavailable, or is down for maintenance.').'<br />'.
   96: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
   97: '</p>');
   98:     return;
   99: }
  100: 
  101: #
  102: # --- Retrieve the parts from the metadata file.---
  103: # Returns an array of everything that the resources stores away
  104: #
  105: 
  106: sub getpartlist {
  107:     my ($symb,$errorref) = @_;
  108: 
  109:     my $navmap   = Apache::lonnavmaps::navmap->new();
  110:     unless (ref($navmap)) {
  111:         if (ref($errorref)) { 
  112:             $$errorref = 'navmap';
  113:             return;
  114:         }
  115:     }
  116:     my $res      = $navmap->getBySymb($symb);
  117:     my $partlist = $res->parts();
  118:     my $url      = $res->src();
  119:     my $toolsymb;
  120:     if ($url =~ /ext\.tool$/) {
  121:         $toolsymb = $symb;
  122:     }
  123:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys',$toolsymb));
  124: 
  125:     my @stores;
  126:     foreach my $part (@{ $partlist }) {
  127: 	foreach my $key (@metakeys) {
  128: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
  129: 	}
  130:     }
  131:     return @stores;
  132: }
  133: 
  134: #--- Format fullname, username:domain if different for display
  135: #--- Use anywhere where the student names are listed
  136: sub nameUserString {
  137:     my ($type,$fullname,$uname,$udom) = @_;
  138:     if ($type eq 'header') {
  139: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
  140:     } else {
  141: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
  142: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
  143:     }
  144: }
  145: 
  146: #--- Get the partlist and the response type for a given problem. ---
  147: #--- Indicate if a response type is coded handgraded or not. ---
  148: #--- Sets response_error pointer to "1" if navmaps object broken ---
  149: sub response_type {
  150:     my ($symb,$response_error) = @_;
  151: 
  152:     my $navmap = Apache::lonnavmaps::navmap->new();
  153:     unless (ref($navmap)) {
  154:         if (ref($response_error)) {
  155:             $$response_error = 1;
  156:         }
  157:         return;
  158:     }
  159:     my $res = $navmap->getBySymb($symb);
  160:     unless (ref($res)) {
  161:         $$response_error = 1;
  162:         return;
  163:     }
  164:     my $partlist = $res->parts();
  165:     my %vPart = 
  166: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
  167:     my (%response_types,%handgrade);
  168:     foreach my $part (@{ $partlist }) {
  169: 	next if (%vPart && !exists($vPart{$part}));
  170: 
  171: 	my @types = $res->responseType($part);
  172: 	my @ids = $res->responseIds($part);
  173: 	for (my $i=0; $i < scalar(@ids); $i++) {
  174: 	    $response_types{$part}{$ids[$i]} = $types[$i];
  175: 	    $handgrade{$part.'_'.$ids[$i]} = 
  176: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
  177: 				     '.handgrade',$symb);
  178: 	}
  179:     }
  180:     return ($partlist,\%handgrade,\%response_types);
  181: }
  182: 
  183: sub flatten_responseType {
  184:     my ($responseType) = @_;
  185:     my @part_response_id =
  186: 	map { 
  187: 	    my $part = $_;
  188: 	    map {
  189: 		[$part,$_]
  190: 		} sort(keys(%{ $responseType->{$part} }));
  191: 	} sort(keys(%$responseType));
  192:     return @part_response_id;
  193: }
  194: 
  195: sub get_display_part {
  196:     my ($partID,$symb)=@_;
  197:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
  198:     if (defined($display) and $display ne '') {
  199:         $display.= ' (<span class="LC_internal_info">'
  200:                   .&mt('Part ID: [_1]',$partID).'</span>)';
  201:     } else {
  202: 	$display=$partID;
  203:     }
  204:     return $display;
  205: }
  206: 
  207: sub reset_caches {
  208:     &reset_analyze_cache();
  209:     &reset_perm();
  210:     &reset_old_essays();
  211: }
  212: 
  213: {
  214:     my %analyze_cache;
  215:     my %analyze_cache_formkeys;
  216: 
  217:     sub reset_analyze_cache {
  218: 	undef(%analyze_cache);
  219:         undef(%analyze_cache_formkeys);
  220:     }
  221: 
  222:     sub get_analyze {
  223: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
  224: 	my $key = "$symb\0$uname\0$udom";
  225:         if ($type eq 'randomizetry') {
  226:             if ($trial ne '') {
  227:                 $key .= "\0".$trial;
  228:             }
  229:         }
  230: 	if (exists($analyze_cache{$key})) {
  231:             my $getupdate = 0;
  232:             if (ref($add_to_hash) eq 'HASH') {
  233:                 foreach my $item (keys(%{$add_to_hash})) {
  234:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
  235:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
  236:                             $getupdate = 1;
  237:                             last;
  238:                         }
  239:                     } else {
  240:                         $getupdate = 1;
  241:                     }
  242:                 }
  243:             }
  244:             if (!$getupdate) {
  245:                 return $analyze_cache{$key};
  246:             }
  247:         }
  248: 
  249: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  250: 	$url=&Apache::lonnet::clutter($url);
  251:         my %form = ('grade_target'      => 'analyze',
  252:                     'grade_domain'      => $udom,
  253:                     'grade_symb'        => $symb,
  254:                     'grade_courseid'    =>  $env{'request.course.id'},
  255:                     'grade_username'    => $uname,
  256:                     'grade_noincrement' => $no_increment);
  257:         if ($bubbles_per_row ne '') {
  258:             $form{'bubbles_per_row'} = $bubbles_per_row;
  259:         }
  260:         if ($type eq 'randomizetry') {
  261:             $form{'grade_questiontype'} = $type;
  262:             if ($rndseed ne '') {
  263:                 $form{'grade_rndseed'} = $rndseed;
  264:             }
  265:         }
  266:         if (ref($add_to_hash)) {
  267:             %form = (%form,%{$add_to_hash});
  268:         }
  269: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
  270: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  271: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  272:         if (ref($add_to_hash) eq 'HASH') {
  273:             $analyze_cache_formkeys{$key} = $add_to_hash;
  274:         } else {
  275:             $analyze_cache_formkeys{$key} = {};
  276:         }
  277: 	return $analyze_cache{$key} = \%analyze;
  278:     }
  279: 
  280:     sub get_order {
  281: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
  282: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
  283: 	return $analyze->{"$partid.$respid.shown"};
  284:     }
  285: 
  286:     sub get_radiobutton_correct_foil {
  287: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
  288: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
  289:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
  290:         if (ref($foils) eq 'ARRAY') {
  291: 	    foreach my $foil (@{$foils}) {
  292: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  293: 		    return $foil;
  294: 	        }
  295: 	    }
  296: 	}
  297:     }
  298: 
  299:     sub scantron_partids_tograde {
  300:         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row,$scancode) = @_;
  301:         my (%analysis,@parts);
  302:         if (ref($resource)) {
  303:             my $symb = $resource->symb();
  304:             my $add_to_form;
  305:             if ($check_for_randomlist) {
  306:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
  307:             }
  308:             if ($scancode) {
  309:                 if (ref($add_to_form) eq 'HASH') {
  310:                     $add_to_form->{'code_for_randomlist'} = $scancode;
  311:                 } else {
  312:                     $add_to_form = { 'code_for_randomlist' => $scancode,};
  313:                 }
  314:             }
  315:             my $analyze = 
  316:                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
  317:                              undef,undef,undef,$bubbles_per_row);
  318:             if (ref($analyze) eq 'HASH') {
  319:                 %analysis = %{$analyze};
  320:             }
  321:             if (ref($analysis{'parts'}) eq 'ARRAY') {
  322:                 foreach my $part (@{$analysis{'parts'}}) {
  323:                     my ($id,$respid) = split(/\./,$part);
  324:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
  325:                         push(@parts,$part);
  326:                     }
  327:                 }
  328:             }
  329:         }
  330:         return (\%analysis,\@parts);
  331:     }
  332: 
  333: }
  334: 
  335: #--- Clean response type for display
  336: #--- Currently filters option/rank/radiobutton/match/essay/Task
  337: #        response types only.
  338: sub cleanRecord {
  339:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  340: 	$uname,$udom,$type,$trial,$rndseed) = @_;
  341:     my $grayFont = '<span class="LC_internal_info">';
  342:     if ($response =~ /^(option|rank)$/) {
  343: 	my %answer=&Apache::lonnet::str2hash($answer);
  344:         my @answer = %answer;
  345:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
  346: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  347: 	my ($toprow,$bottomrow);
  348: 	foreach my $foil (@$order) {
  349: 	    if ($grading{$foil} == 1) {
  350: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  351: 	    } else {
  352: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  353: 	    }
  354: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  355: 	}
  356: 	return '<blockquote><table border="1">'.
  357: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  358: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  359: 	    $bottomrow.'</tr></table></blockquote>';
  360:     } elsif ($response eq 'match') {
  361: 	my %answer=&Apache::lonnet::str2hash($answer);
  362:         my @answer = %answer;
  363:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
  364: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  365: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  366: 	my ($toprow,$middlerow,$bottomrow);
  367: 	foreach my $foil (@$order) {
  368: 	    my $item=shift(@items);
  369: 	    if ($grading{$foil} == 1) {
  370: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  371: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  372: 	    } else {
  373: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  374: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  375: 	    }
  376: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  377: 	}
  378: 	return '<blockquote><table border="1">'.
  379: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  380: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  381: 	    $middlerow.'</tr>'.
  382: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  383: 	    $bottomrow.'</tr></table></blockquote>';
  384:     } elsif ($response eq 'radiobutton') {
  385: 	my %answer=&Apache::lonnet::str2hash($answer);
  386:         my @answer = %answer;
  387:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
  388: 	my ($toprow,$bottomrow);
  389: 	my $correct = 
  390: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
  391: 	foreach my $foil (@$order) {
  392: 	    if (exists($answer{$foil})) {
  393: 		if ($foil eq $correct) {
  394: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  395: 		} else {
  396: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  397: 		}
  398: 	    } else {
  399: 		$toprow.='<td>'.&mt('false').'</td>';
  400: 	    }
  401: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  402: 	}
  403: 	return '<blockquote><table border="1">'.
  404: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  405: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  406: 	    $bottomrow.'</tr></table></blockquote>';
  407:     } elsif ($response eq 'essay') {
  408: 	if (! exists ($env{'form.'.$symb})) {
  409: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  410: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  411: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  412: 
  413: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  414: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  415: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  416: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  417: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  418: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  419: 	}
  420:         $answer = &Apache::lontexconvert::msgtexconverted($answer);
  421: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  422: 
  423:     } elsif ( $response eq 'organic') {
  424:         my $result=&mt('Smile representation: [_1]',
  425:                            '"<tt>'.&HTML::Entities::encode($answer, '"<>&').'</tt>"');
  426: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  427: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  428: 	return $result;
  429:     } elsif ( $response eq 'Task') {
  430: 	if ( $answer eq 'SUBMITTED') {
  431: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  432: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  433: 	    return $result;
  434: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  435: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  436: 			       keys(%{$record}));
  437: 	    return join('<br />',($version,@matches));
  438: 			       
  439: 			       
  440: 	} else {
  441: 	    my $result =
  442: 		'<p>'
  443: 		.&mt('Overall result: [_1]',
  444: 		     $record->{$version."resource.$respid.$partid.status"})
  445: 		.'</p>';
  446: 	    
  447: 	    $result .= '<ul>';
  448: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  449: 			     keys(%{$record}));
  450: 	    foreach my $grade (sort(@grade)) {
  451: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  452: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  453: 				     $dim, $record->{$grade}).
  454: 			  '</li>';
  455: 	    }
  456: 	    $result.='</ul>';
  457: 	    return $result;
  458: 	}
  459:     } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
  460:         # Respect multiple input fields, see Bug #5409
  461: 	$answer = 
  462: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  463: 							      $answer);
  464: 	return $answer;
  465:     }
  466:     return &HTML::Entities::encode($answer, '"<>&');
  467: }
  468: 
  469: #-- A couple of common js functions
  470: sub commonJSfunctions {
  471:     my $request = shift;
  472:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
  473:     function radioSelection(radioButton) {
  474: 	var selection=null;
  475: 	if (radioButton.length > 1) {
  476: 	    for (var i=0; i<radioButton.length; i++) {
  477: 		if (radioButton[i].checked) {
  478: 		    return radioButton[i].value;
  479: 		}
  480: 	    }
  481: 	} else {
  482: 	    if (radioButton.checked) return radioButton.value;
  483: 	}
  484: 	return selection;
  485:     }
  486: 
  487:     function pullDownSelection(selectOne) {
  488: 	var selection="";
  489: 	if (selectOne.length > 1) {
  490: 	    for (var i=0; i<selectOne.length; i++) {
  491: 		if (selectOne[i].selected) {
  492: 		    return selectOne[i].value;
  493: 		}
  494: 	    }
  495: 	} else {
  496:             // only one value it must be the selected one
  497: 	    return selectOne.value;
  498: 	}
  499:     }
  500: COMMONJSFUNCTIONS
  501: }
  502: 
  503: #--- Dumps the class list with usernames,list of sections,
  504: #--- section, ids and fullnames for each user.
  505: sub getclasslist {
  506:     my ($getsec,$filterbyaccstatus,$getgroup,$symb,$submitonly,$filterbysubmstatus) = @_;
  507:     my @getsec;
  508:     my @getgroup;
  509:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  510:     if (!ref($getsec)) {
  511: 	if ($getsec ne '' && $getsec ne 'all') {
  512: 	    @getsec=($getsec);
  513: 	}
  514:     } else {
  515: 	@getsec=@{$getsec};
  516:     }
  517:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  518:     if (!ref($getgroup)) {
  519: 	if ($getgroup ne '' && $getgroup ne 'all') {
  520: 	    @getgroup=($getgroup);
  521: 	}
  522:     } else {
  523: 	@getgroup=@{$getgroup};
  524:     }
  525:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  526: 
  527:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  528:     # Bail out if we were unable to get the classlist
  529:     return if (! defined($classlist));
  530:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  531:     #
  532:     my %sections;
  533:     my %fullnames;
  534:     my ($cdom,$cnum,$partlist);
  535:     if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
  536:         $cdom = $env{"course.$env{'request.course.id'}.domain"};
  537:         $cnum = $env{"course.$env{'request.course.id'}.num"};
  538:         my $res_error;
  539:         ($partlist,my $handgrade,my $responseType) = &response_type($symb,\$res_error);
  540:     }
  541:     foreach my $student (keys(%$classlist)) {
  542:         my $end      = 
  543:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  544:         my $start    = 
  545:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  546:         my $id       = 
  547:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  548:         my $section  = 
  549:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  550:         my $fullname = 
  551:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  552:         my $status   = 
  553:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  554:         my $group   = 
  555:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  556: 	# filter students according to status selected
  557: 	if ($filterbyaccstatus && (!($stu_status =~ /Any/))) {
  558: 	    if (!($stu_status =~ $status)) {
  559: 		delete($classlist->{$student});
  560: 		next;
  561: 	    }
  562: 	}
  563: 	# filter students according to groups selected
  564: 	my @stu_groups = split(/,/,$group);
  565: 	if (@getgroup) {
  566: 	    my $exclude = 1;
  567: 	    foreach my $grp (@getgroup) {
  568: 	        foreach my $stu_group (@stu_groups) {
  569: 	            if ($stu_group eq $grp) {
  570: 	                $exclude = 0;
  571:     	            } 
  572: 	        }
  573:     	        if (($grp eq 'none') && !$group) {
  574:         	    $exclude = 0;
  575:         	}
  576: 	    }
  577: 	    if ($exclude) {
  578: 	        delete($classlist->{$student});
  579: 		next;
  580: 	    }
  581: 	}
  582:         if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
  583:             my $udom =
  584:                 $classlist->{$student}->[&Apache::loncoursedata::CL_SDOM()];
  585:             my $uname =
  586:                 $classlist->{$student}->[&Apache::loncoursedata::CL_SNAME()];
  587:             if (($symb ne '') && ($udom ne '') && ($uname ne '')) {
  588:                 if ($submitonly eq 'queued') {
  589:                     my %queue_status =
  590:                         &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
  591:                                                                 $udom,$uname);
  592:                     if (!defined($queue_status{'gradingqueue'})) {
  593:                         delete($classlist->{$student});
  594:                         next;
  595:                     }
  596:                 } else {
  597:                     my (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
  598:                     my $submitted = 0;
  599:                     my $graded = 0;
  600:                     my $incorrect = 0;
  601:                     foreach (keys(%status)) {
  602:                         $submitted = 1 if ($status{$_} ne 'nothing');
  603:                         $graded = 1 if ($status{$_} =~ /^ungraded/);
  604:                         $incorrect = 1 if ($status{$_} =~ /^incorrect/);
  605: 
  606:                         my ($foo,$partid,$foo1) = split(/\./,$_);
  607:                         if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
  608:                             $submitted = 0;
  609:                         }
  610:                     }
  611:                     if (!$submitted && ($submitonly eq 'yes' ||
  612:                                         $submitonly eq 'incorrect' ||
  613:                                         $submitonly eq 'graded')) {
  614:                         delete($classlist->{$student});
  615:                         next;
  616:                     } elsif (!$graded && ($submitonly eq 'graded')) {
  617:                         delete($classlist->{$student});
  618:                         next;
  619:                     } elsif (!$incorrect && $submitonly eq 'incorrect') {
  620:                         delete($classlist->{$student});
  621:                         next;
  622:                     }
  623:                 }
  624:             }
  625:         }
  626: 	$section = ($section ne '' ? $section : 'none');
  627: 	if (&canview($section)) {
  628: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  629: 		$sections{$section}++;
  630: 		if ($classlist->{$student}) {
  631: 		    $fullnames{$student}=$fullname;
  632: 		}
  633: 	    } else {
  634: 		delete($classlist->{$student});
  635: 	    }
  636: 	} else {
  637: 	    delete($classlist->{$student});
  638: 	}
  639:     }
  640:     my @sections = sort(keys(%sections));
  641:     return ($classlist,\@sections,\%fullnames);
  642: }
  643: 
  644: sub canmodify {
  645:     my ($sec)=@_;
  646:     if ($perm{'mgr'}) {
  647: 	if (!defined($perm{'mgr_section'})) {
  648: 	    # can modify whole class
  649: 	    return 1;
  650: 	} else {
  651: 	    if ($sec eq $perm{'mgr_section'}) {
  652: 		#can modify the requested section
  653: 		return 1;
  654: 	    } else {
  655: 		# can't modify the request section
  656: 		return 0;
  657: 	    }
  658: 	}
  659:     }
  660:     #can't modify
  661:     return 0;
  662: }
  663: 
  664: sub canview {
  665:     my ($sec)=@_;
  666:     if ($perm{'vgr'}) {
  667: 	if (!defined($perm{'vgr_section'})) {
  668: 	    # can modify whole class
  669: 	    return 1;
  670: 	} else {
  671: 	    if ($sec eq $perm{'vgr_section'}) {
  672: 		#can modify the requested section
  673: 		return 1;
  674: 	    } else {
  675: 		# can't modify the request section
  676: 		return 0;
  677: 	    }
  678: 	}
  679:     }
  680:     #can't modify
  681:     return 0;
  682: }
  683: 
  684: #--- Retrieve the grade status of a student for all the parts
  685: sub student_gradeStatus {
  686:     my ($symb,$udom,$uname,$partlist) = @_;
  687:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  688:     my %partstatus = ();
  689:     foreach (@$partlist) {
  690: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  691: 	$status              = 'nothing' if ($status eq '');
  692: 	$partstatus{$_}      = $status;
  693: 	my $subkey           = "resource.$_.submitted_by";
  694: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  695:     }
  696:     return %partstatus;
  697: }
  698: 
  699: # hidden form and javascript that calls the form
  700: # Use by verifyscript and viewgrades
  701: # Shows a student's view of problem and submission
  702: sub jscriptNform {
  703:     my ($symb) = @_;
  704:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  705:     my $jscript= &Apache::lonhtmlcommon::scripttag(
  706: 	'    function viewOneStudent(user,domain) {'."\n".
  707: 	'	document.onestudent.student.value = user;'."\n".
  708: 	'	document.onestudent.userdom.value = domain;'."\n".
  709: 	'	document.onestudent.submit();'."\n".
  710: 	'    }'."\n".
  711: 	"\n");
  712:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  713: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  714: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  715: 	'<input type="hidden" name="command" value="submission" />'."\n".
  716: 	'<input type="hidden" name="student" value="" />'."\n".
  717: 	'<input type="hidden" name="userdom" value="" />'."\n".
  718: 	'</form>'."\n";
  719:     return $jscript;
  720: }
  721: 
  722: 
  723: 
  724: # Given the score (as a number [0-1] and the weight) what is the final
  725: # point value? This function will round to the nearest tenth, third,
  726: # or quarter if one of those is within the tolerance of .00001.
  727: sub compute_points {
  728:     my ($score, $weight) = @_;
  729:     
  730:     my $tolerance = .00001;
  731:     my $points = $score * $weight;
  732: 
  733:     # Check for nearness to 1/x.
  734:     my $check_for_nearness = sub {
  735:         my ($factor) = @_;
  736:         my $num = ($points * $factor) + $tolerance;
  737:         my $floored_num = floor($num);
  738:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  739:             return $floored_num / $factor;
  740:         }
  741:         return $points;
  742:     };
  743: 
  744:     $points = $check_for_nearness->(10);
  745:     $points = $check_for_nearness->(3);
  746:     $points = $check_for_nearness->(4);
  747:     
  748:     return $points;
  749: }
  750: 
  751: #------------------ End of general use routines --------------------
  752: 
  753: #
  754: # Find most similar essay
  755: #
  756: 
  757: sub most_similar {
  758:     my ($uname,$udom,$symb,$uessay)=@_;
  759: 
  760:     unless ($symb) { return ''; }
  761: 
  762:     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
  763: 
  764: # ignore spaces and punctuation
  765: 
  766:     $uessay=~s/\W+/ /gs;
  767: 
  768: # ignore empty submissions (occuring when only files are sent)
  769: 
  770:     unless ($uessay=~/\w+/s) { return ''; }
  771: 
  772: # these will be returned. Do not care if not at least 50 percent similar
  773:     my $limit=0.6;
  774:     my $sname='';
  775:     my $sdom='';
  776:     my $scrsid='';
  777:     my $sessay='';
  778: # go through all essays ...
  779:     foreach my $tkey (keys(%{$old_essays{$symb}})) {
  780: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  781: # ... except the same student
  782:         next if (($tname eq $uname) && ($tdom eq $udom));
  783: 	my $tessay=$old_essays{$symb}{$tkey};
  784: 	$tessay=~s/\W+/ /gs;
  785: # String similarity gives up if not even limit
  786: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  787: # Found one
  788: 	if ($tsimilar>$limit) {
  789: 	    $limit=$tsimilar;
  790: 	    $sname=$tname;
  791: 	    $sdom=$tdom;
  792: 	    $scrsid=$tcrsid;
  793: 	    $sessay=$old_essays{$symb}{$tkey};
  794: 	}
  795:     }
  796:     if ($limit>0.6) {
  797:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  798:     } else {
  799:        return ('','','','',0);
  800:     }
  801: }
  802: 
  803: #-------------------------------------------------------------------
  804: 
  805: #------------------------------------ Receipt Verification Routines
  806: #
  807: 
  808: sub initialverifyreceipt {
  809:    my ($request,$symb) = @_;
  810:    &commonJSfunctions($request);
  811:    return '<form name="gradingMenu" action=""><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
  812:         &Apache::lonnet::recprefix($env{'request.course.id'}).
  813:         '-<input type="text" name="receipt" size="4" />'.
  814:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  815:         '<input type="hidden" name="command" value="verify" />'.
  816:         "</form>\n";
  817: }
  818: 
  819: #--- Check whether a receipt number is valid.---
  820: sub verifyreceipt {
  821:     my ($request,$symb)  = @_;
  822: 
  823:     my $courseid = $env{'request.course.id'};
  824:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  825: 	$env{'form.receipt'};
  826:     $receipt     =~ s/[^\-\d]//g;
  827: 
  828:     my $title.=
  829: 	'<h3><span class="LC_info">'.
  830: 	&mt('Verifying Receipt Number [_1]',$receipt).
  831: 	'</span></h3>'."\n";
  832: 
  833:     my ($string,$contents,$matches) = ('','',0);
  834:     my (undef,undef,$fullname) = &getclasslist('all','0');
  835:     
  836:     my $receiptparts=0;
  837:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  838: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  839:     my $parts=['0'];
  840:     if ($receiptparts) {
  841:         my $res_error; 
  842:         ($parts)=&response_type($symb,\$res_error);
  843:         if ($res_error) {
  844:             return &navmap_errormsg();
  845:         } 
  846:     }
  847:     
  848:     my $header = 
  849: 	&Apache::loncommon::start_data_table().
  850: 	&Apache::loncommon::start_data_table_header_row().
  851: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  852: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  853: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  854:     if ($receiptparts) {
  855: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  856:     }
  857:     $header.=
  858: 	&Apache::loncommon::end_data_table_header_row();
  859: 
  860:     foreach (sort 
  861: 	     {
  862: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  863: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  864: 		 }
  865: 		 return $a cmp $b;
  866: 	     } (keys(%$fullname))) {
  867: 	my ($uname,$udom)=split(/\:/);
  868: 	foreach my $part (@$parts) {
  869: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  870: 		$contents.=
  871: 		    &Apache::loncommon::start_data_table_row().
  872: 		    '<td>&nbsp;'."\n".
  873: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  874: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  875: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  876: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  877: 		if ($receiptparts) {
  878: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  879: 		}
  880: 		$contents.= 
  881: 		    &Apache::loncommon::end_data_table_row()."\n";
  882: 		
  883: 		$matches++;
  884: 	    }
  885: 	}
  886:     }
  887:     if ($matches == 0) {
  888:         $string = $title
  889:                  .'<p class="LC_warning">'
  890:                  .&mt('No match found for the above receipt number.')
  891:                  .'</p>';
  892:     } else {
  893: 	$string = &jscriptNform($symb).$title.
  894: 	    '<p>'.
  895: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
  896: 	    '</p>'.
  897: 	    $header.
  898: 	    $contents.
  899: 	    &Apache::loncommon::end_data_table()."\n";
  900:     }
  901:     return $string;
  902: }
  903: 
  904: #--- This is called by a number of programs.
  905: #--- Called from the Grading Menu - View/Grade an individual student
  906: #--- Also called directly when one clicks on the subm button 
  907: #    on the problem page.
  908: sub listStudents {
  909:     my ($request,$symb,$submitonly) = @_;
  910: 
  911:     my $is_tool   = ($symb =~ /ext\.tool$/);
  912:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  913:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  914:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  915:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  916:     unless ($submitonly) {
  917:        $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  918:     }
  919: 
  920:     my $result='';
  921:     my $res_error;
  922:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
  923: 
  924:     my %js_lt = &Apache::lonlocal::texthash (
  925: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
  926: 		'single'   => 'Please select the student before clicking on the Next button.',
  927: 	     );
  928:     &js_escape(\%js_lt);
  929:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
  930:     function checkSelect(checkBox) {
  931: 	var ctr=0;
  932: 	var sense="";
  933: 	if (checkBox.length > 1) {
  934: 	    for (var i=0; i<checkBox.length; i++) {
  935: 		if (checkBox[i].checked) {
  936: 		    ctr++;
  937: 		}
  938: 	    }
  939: 	    sense = '$js_lt{'multiple'}';
  940: 	} else {
  941: 	    if (checkBox.checked) {
  942: 		ctr = 1;
  943: 	    }
  944: 	    sense = '$js_lt{'single'}';
  945: 	}
  946: 	if (ctr == 0) {
  947: 	    alert(sense);
  948: 	    return false;
  949: 	}
  950: 	document.gradesub.submit();
  951:     }
  952: 
  953:     function reLoadList(formname) {
  954: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  955: 	formname.command.value = 'submission';
  956: 	formname.submit();
  957:     }
  958: LISTJAVASCRIPT
  959: 
  960:     &commonJSfunctions($request);
  961:     $request->print($result);
  962: 
  963:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  964: 	"\n";
  965: 	
  966:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
  967:     unless ($is_tool) {
  968:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
  969:                       .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
  970:                       .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
  971:                       .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
  972:                       .&Apache::lonhtmlcommon::row_closure();
  973:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
  974:                       .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
  975:                       .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
  976:                       .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
  977:                       .&Apache::lonhtmlcommon::row_closure();
  978:     }
  979: 
  980:     my $submission_options;
  981:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  982:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  983:     $env{'form.Status'} = $saveStatus;
  984:     my %optiontext;
  985:     if ($is_tool) {
  986:         %optiontext = &Apache::lonlocal::texthash (
  987:                           lastonly => 'last transaction',
  988:                           last     => 'last transaction with details',
  989:                           datesub  => 'all transactions',
  990:                           all      => 'all transactions with details',
  991:                       );
  992:     } else {
  993:         %optiontext = &Apache::lonlocal::texthash (
  994:                           lastonly => 'last submission',
  995:                           last     => 'last submission with details',
  996:                           datesub  => 'all submissions',
  997:                           all      => 'all submissions with details',
  998:                       );
  999:     }
 1000:     $submission_options.=
 1001:         '<span class="LC_nobreak">'.
 1002:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
 1003:         $optiontext{'lastonly'}.' </label></span>'."\n".
 1004:         '<span class="LC_nobreak">'.
 1005:         '<label><input type="radio" name="lastSub" value="last" /> '.
 1006:         $optiontext{'last'}.' </label></span>'."\n".
 1007:         '<span class="LC_nobreak">'.
 1008:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
 1009:         $optiontext{'datesub'}.'</label></span>'."\n".
 1010:         '<span class="LC_nobreak">'.
 1011:         '<label><input type="radio" name="lastSub" value="all" /> '.
 1012:         $optiontext{'all'}.'</label></span>';
 1013:     my $viewtitle;
 1014:     if ($is_tool) {
 1015:         $viewtitle = &mt('View Transactions');
 1016:     } else {
 1017:         $viewtitle = &mt('View Submissions');
 1018:     }
 1019:     $gradeTable .= &Apache::lonhtmlcommon::row_title($viewtitle)
 1020:                   .$submission_options
 1021:                   .&Apache::lonhtmlcommon::row_closure();
 1022: 
 1023:     my $closure;
 1024:     if (($is_tool) && (exists($env{'form.Status'}))) {
 1025:         $closure = 1;
 1026:     }
 1027:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
 1028:                   .'<select name="increment">'
 1029:                   .'<option value="1">'.&mt('Whole Points').'</option>'
 1030:                   .'<option value=".5">'.&mt('Half Points').'</option>'
 1031:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
 1032:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
 1033:                   .'</select>'
 1034:                   .&Apache::lonhtmlcommon::row_closure($closure);
 1035: 
 1036:     $gradeTable .= 
 1037:         &build_section_inputs().
 1038: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
 1039: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1040: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
 1041: 
 1042:     if (exists($env{'form.Status'})) {
 1043: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
 1044:     } else {
 1045:         if ($is_tool) {
 1046:             $closure = 1;
 1047:         }
 1048:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
 1049:                       .&Apache::lonhtmlcommon::StatusOptions(
 1050:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
 1051:                       .&Apache::lonhtmlcommon::row_closure($closure);
 1052:     }
 1053: 
 1054:     unless ($is_tool) {
 1055:         $closure = 1;
 1056:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
 1057:                       .'<input type="checkbox" name="checkPlag" checked="checked" />'
 1058:                       .&Apache::lonhtmlcommon::row_closure($closure);
 1059:     }
 1060:     $gradeTable .= &Apache::lonhtmlcommon::end_pick_box();
 1061:     my $regrademsg;
 1062:     if ($is_tool) {
 1063:         $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.");
 1064:     } else {
 1065:         $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.");
 1066:     }
 1067:     $gradeTable .= '<p>'
 1068:                   .$regrademsg."\n"
 1069:                   .'<input type="hidden" name="command" value="processGroup" />'
 1070:                   .'</p>';
 1071: 
 1072: # checkall buttons
 1073:     $gradeTable.=&check_script('gradesub', 'stuinfo');
 1074:     $gradeTable.='<input type="button" '."\n".
 1075:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
 1076:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
 1077:     $gradeTable.=&check_buttons();
 1078:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
 1079:     $gradeTable.= &Apache::loncommon::start_data_table().
 1080: 	&Apache::loncommon::start_data_table_header_row();
 1081:     my $loop = 0;
 1082:     while ($loop < 2) {
 1083: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
 1084: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
 1085: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1086: 	    foreach my $part (sort(@$partlist)) {
 1087: 		my $display_part=
 1088: 		    &get_display_part((split(/_/,$part))[0],$symb);
 1089: 		$gradeTable.=
 1090: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
 1091: 	    }
 1092: 	} elsif ($submitonly eq 'queued') {
 1093: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
 1094: 	}
 1095: 	$loop++;
 1096: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
 1097:     }
 1098:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
 1099: 
 1100:     my $ctr = 0;
 1101:     foreach my $student (sort 
 1102: 			 {
 1103: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 1104: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 1105: 			     }
 1106: 			     return $a cmp $b;
 1107: 			 }
 1108: 			 (keys(%$fullname))) {
 1109: 	my ($uname,$udom) = split(/:/,$student);
 1110: 
 1111: 	my %status = ();
 1112: 
 1113: 	if ($submitonly eq 'queued') {
 1114: 	    my %queue_status = 
 1115: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 1116: 							$udom,$uname);
 1117: 	    next if (!defined($queue_status{'gradingqueue'}));
 1118: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
 1119: 	}
 1120: 
 1121: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1122: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
 1123: 	    my $submitted = 0;
 1124: 	    my $graded = 0;
 1125: 	    my $incorrect = 0;
 1126: 	    foreach (keys(%status)) {
 1127: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1128: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1129: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1130: 		
 1131: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1132: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1133: 		    $submitted = 0;
 1134: 		    my ($part)=split(/\./,$partid);
 1135: 		    $gradeTable.='<input type="hidden" name="'.
 1136: 			$student.':'.$part.':submitted_by" value="'.
 1137: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1138: 		}
 1139: 	    }
 1140: 	    
 1141: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1142: 				     $submitonly eq 'incorrect' ||
 1143: 				     $submitonly eq 'graded'));
 1144: 	    next if (!$graded && ($submitonly eq 'graded'));
 1145: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1146: 	}
 1147: 
 1148: 	$ctr++;
 1149: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1150:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1151: 	if ( $perm{'vgr'} eq 'F' ) {
 1152: 	    if ($ctr%2 ==1) {
 1153: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1154: 	    }
 1155: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1156:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1157:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1158: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1159: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1160: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1161: 
 1162: 	    if ($submitonly ne 'all') {
 1163: 		foreach (sort(keys(%status))) {
 1164: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1165: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1166: 		}
 1167: 	    }
 1168: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1169: 	    if ($ctr%2 ==0) {
 1170: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1171: 	    }
 1172: 	}
 1173:     }
 1174:     if ($ctr%2 ==1) {
 1175: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1176: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1177: 		foreach (@$partlist) {
 1178: 		    $gradeTable.='<td>&nbsp;</td>';
 1179: 		}
 1180: 	    } elsif ($submitonly eq 'queued') {
 1181: 		$gradeTable.='<td>&nbsp;</td>';
 1182: 	    }
 1183: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1184:     }
 1185: 
 1186:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1187:         '<input type="button" '.
 1188:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
 1189:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1190:     if ($ctr == 0) {
 1191: 	my $num_students=(scalar(keys(%$fullname)));
 1192: 	if ($num_students eq 0) {
 1193: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1194: 	} else {
 1195: 	    my $submissions='submissions';
 1196: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1197: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1198: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1199: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1200: 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
 1201: 		    $num_students).
 1202: 		'</span><br />';
 1203: 	}
 1204:     } elsif ($ctr == 1) {
 1205: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1206:     }
 1207:     $request->print($gradeTable);
 1208:     return '';
 1209: }
 1210: 
 1211: #---- Called from the listStudents routine
 1212: 
 1213: sub check_script {
 1214:     my ($form, $type)=@_;
 1215:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
 1216:     function checkall() {
 1217:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1218:             ele = document.forms.'.$form.'.elements[i];
 1219:             if (ele.name == "'.$type.'") {
 1220:             document.forms.'.$form.'.elements[i].checked=true;
 1221:                                        }
 1222:         }
 1223:     }
 1224: 
 1225:     function checksec() {
 1226:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1227:             ele = document.forms.'.$form.'.elements[i];
 1228:            string = document.forms.'.$form.'.chksec.value;
 1229:            if
 1230:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1231:               document.forms.'.$form.'.elements[i].checked=true;
 1232:             }
 1233:         }
 1234:     }
 1235: 
 1236: 
 1237:     function uncheckall() {
 1238:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1239:             ele = document.forms.'.$form.'.elements[i];
 1240:             if (ele.name == "'.$type.'") {
 1241:             document.forms.'.$form.'.elements[i].checked=false;
 1242:                                        }
 1243:         }
 1244:     }
 1245: 
 1246: '."\n");
 1247:     return $chkallscript;
 1248: }
 1249: 
 1250: sub check_buttons {
 1251:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1252:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1253:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1254:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1255:     return $buttons;
 1256: }
 1257: 
 1258: #     Displays the submissions for one student or a group of students
 1259: sub processGroup {
 1260:     my ($request,$symb)  = @_;
 1261:     my $ctr        = 0;
 1262:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1263:     my $total      = scalar(@stuchecked)-1;
 1264: 
 1265:     foreach my $student (@stuchecked) {
 1266: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1267: 	$env{'form.student'}        = $uname;
 1268: 	$env{'form.userdom'}        = $udom;
 1269: 	$env{'form.fullname'}       = $fullname;
 1270: 	&submission($request,$ctr,$total,$symb);
 1271: 	$ctr++;
 1272:     }
 1273:     return '';
 1274: }
 1275: 
 1276: #------------------------------------------------------------------------------------
 1277: #
 1278: #-------------------------- Next few routines handles grading by student, essentially
 1279: #                           handles essay response type problem/part
 1280: #
 1281: #--- Javascript to handle the submission page functionality ---
 1282: sub sub_page_js {
 1283:     my $request = shift;
 1284:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1285:     &js_escape(\$alertmsg);
 1286:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1287:     function updateRadio(formname,id,weight) {
 1288: 	var gradeBox = formname["GD_BOX"+id];
 1289: 	var radioButton = formname["RADVAL"+id];
 1290: 	var oldpts = formname["oldpts"+id].value;
 1291: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1292: 	gradeBox.value = pts;
 1293: 	var resetbox = false;
 1294: 	if (isNaN(pts) || pts < 0) {
 1295: 	    alert("$alertmsg"+pts);
 1296: 	    for (var i=0; i<radioButton.length; i++) {
 1297: 		if (radioButton[i].checked) {
 1298: 		    gradeBox.value = i;
 1299: 		    resetbox = true;
 1300: 		}
 1301: 	    }
 1302: 	    if (!resetbox) {
 1303: 		formtextbox.value = "";
 1304: 	    }
 1305: 	    return;
 1306: 	}
 1307: 
 1308: 	if (pts > weight) {
 1309: 	    var resp = confirm("You entered a value ("+pts+
 1310: 			       ") greater than the weight for the part. Accept?");
 1311: 	    if (resp == false) {
 1312: 		gradeBox.value = oldpts;
 1313: 		return;
 1314: 	    }
 1315: 	}
 1316: 
 1317: 	for (var i=0; i<radioButton.length; i++) {
 1318: 	    radioButton[i].checked=false;
 1319: 	    if (pts == i && pts != "") {
 1320: 		radioButton[i].checked=true;
 1321: 	    }
 1322: 	}
 1323: 	updateSelect(formname,id);
 1324: 	formname["stores"+id].value = "0";
 1325:     }
 1326: 
 1327:     function writeBox(formname,id,pts) {
 1328: 	var gradeBox = formname["GD_BOX"+id];
 1329: 	if (checkSolved(formname,id) == 'update') {
 1330: 	    gradeBox.value = pts;
 1331: 	} else {
 1332: 	    var oldpts = formname["oldpts"+id].value;
 1333: 	    gradeBox.value = oldpts;
 1334: 	    var radioButton = formname["RADVAL"+id];
 1335: 	    for (var i=0; i<radioButton.length; i++) {
 1336: 		radioButton[i].checked=false;
 1337: 		if (i == oldpts) {
 1338: 		    radioButton[i].checked=true;
 1339: 		}
 1340: 	    }
 1341: 	}
 1342: 	formname["stores"+id].value = "0";
 1343: 	updateSelect(formname,id);
 1344: 	return;
 1345:     }
 1346: 
 1347:     function clearRadBox(formname,id) {
 1348: 	if (checkSolved(formname,id) == 'noupdate') {
 1349: 	    updateSelect(formname,id);
 1350: 	    return;
 1351: 	}
 1352: 	gradeSelect = formname["GD_SEL"+id];
 1353: 	for (var i=0; i<gradeSelect.length; i++) {
 1354: 	    if (gradeSelect[i].selected) {
 1355: 		var selectx=i;
 1356: 	    }
 1357: 	}
 1358: 	var stores = formname["stores"+id];
 1359: 	if (selectx == stores.value) { return };
 1360: 	var gradeBox = formname["GD_BOX"+id];
 1361: 	gradeBox.value = "";
 1362: 	var radioButton = formname["RADVAL"+id];
 1363: 	for (var i=0; i<radioButton.length; i++) {
 1364: 	    radioButton[i].checked=false;
 1365: 	}
 1366: 	stores.value = selectx;
 1367:     }
 1368: 
 1369:     function checkSolved(formname,id) {
 1370: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1371: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1372: 	    if (!reply) {return "noupdate";}
 1373: 	    formname.overRideScore.value = 'yes';
 1374: 	}
 1375: 	return "update";
 1376:     }
 1377: 
 1378:     function updateSelect(formname,id) {
 1379: 	formname["GD_SEL"+id][0].selected = true;
 1380: 	return;
 1381:     }
 1382: 
 1383: //=========== Check that a point is assigned for all the parts  ============
 1384:     function checksubmit(formname,val,total,parttot) {
 1385: 	formname.gradeOpt.value = val;
 1386: 	if (val == "Save & Next") {
 1387: 	    for (i=0;i<=total;i++) {
 1388: 		for (j=0;j<parttot;j++) {
 1389: 		    var partid = formname["partid"+i+"_"+j].value;
 1390: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1391: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1392: 			if (points == "") {
 1393: 			    var name = formname["name"+i].value;
 1394: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1395: 			    var resp = confirm("You did not assign a score for "+studentID+
 1396: 					       ", part "+partid+". Continue?");
 1397: 			    if (resp == false) {
 1398: 				formname["GD_BOX"+i+"_"+partid].focus();
 1399: 				return false;
 1400: 			    }
 1401: 			}
 1402: 		    }
 1403: 		}
 1404: 	    }
 1405: 	}
 1406: 	formname.submit();
 1407:     }
 1408: 
 1409: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1410:     function checkSubmitPage(formname,total) {
 1411: 	noscore = new Array(100);
 1412: 	var ptr = 0;
 1413: 	for (i=1;i<total;i++) {
 1414: 	    var partid = formname["q_"+i].value;
 1415: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1416: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1417: 		var status = formname["solved"+i+"_"+partid].value;
 1418: 		if (points == "" && status != "correct_by_student") {
 1419: 		    noscore[ptr] = i;
 1420: 		    ptr++;
 1421: 		}
 1422: 	    }
 1423: 	}
 1424: 	if (ptr != 0) {
 1425: 	    var sense = ptr == 1 ? ": " : "s: ";
 1426: 	    var prolist = "";
 1427: 	    if (ptr == 1) {
 1428: 		prolist = noscore[0];
 1429: 	    } else {
 1430: 		var i = 0;
 1431: 		while (i < ptr-1) {
 1432: 		    prolist += noscore[i]+", ";
 1433: 		    i++;
 1434: 		}
 1435: 		prolist += "and "+noscore[i];
 1436: 	    }
 1437: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1438: 	    if (resp == false) {
 1439: 		return false;
 1440: 	    }
 1441: 	}
 1442: 
 1443: 	formname.submit();
 1444:     }
 1445: SUBJAVASCRIPT
 1446: }
 1447: 
 1448: #--- javascript for essay type problem --
 1449: sub sub_page_kw_js {
 1450:     my $request = shift;
 1451:     my $iconpath = $request->dir_config('lonIconsURL');
 1452:     &commonJSfunctions($request);
 1453: 
 1454:     my $inner_js_msg_central= (<<INNERJS);
 1455: <script type="text/javascript">
 1456:     function checkInput() {
 1457:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1458:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1459:       var usrctr = document.msgcenter.usrctr.value;
 1460:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1461:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1462: 
 1463:       var msgchk = "";
 1464:       if (document.msgcenter.subchk.checked) {
 1465:          msgchk = "msgsub,";
 1466:       }
 1467:       var includemsg = 0;
 1468:       for (var i=1; i<=nmsg; i++) {
 1469:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1470:           var frmmsg = document.msgcenter["msg"+i];
 1471:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1472:           var showflg = opener.document.SCORE["shownOnce"+i];
 1473:           showflg.value = "1";
 1474:           var chkbox = document.msgcenter["msgn"+i];
 1475:           if (chkbox.checked) {
 1476:              msgchk += "savemsg"+i+",";
 1477:              includemsg = 1;
 1478:           }
 1479:       }
 1480:       if (document.msgcenter.newmsgchk.checked) {
 1481:          msgchk += "newmsg"+usrctr;
 1482:          includemsg = 1;
 1483:       }
 1484:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1485:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1486:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1487:       includemsg.value = msgchk;
 1488: 
 1489:       self.close()
 1490: 
 1491:     }
 1492: </script>
 1493: INNERJS
 1494: 
 1495:     my $inner_js_highlight_central= (<<INNERJS);
 1496: <script type="text/javascript">
 1497:     function updateChoice(flag) {
 1498:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1499:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1500:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1501:       opener.document.SCORE.refresh.value = "on";
 1502:       if (opener.document.SCORE.keywords.value!=""){
 1503:          opener.document.SCORE.submit();
 1504:       }
 1505:       self.close()
 1506:     }
 1507: </script>
 1508: INNERJS
 1509: 
 1510:     my $start_page_msg_central = 
 1511:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1512: 				       {'js_ready'  => 1,
 1513: 					'only_body' => 1,
 1514: 					'bgcolor'   =>'#FFFFFF',});
 1515:     my $end_page_msg_central = 
 1516: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1517: 
 1518: 
 1519:     my $start_page_highlight_central = 
 1520:         &Apache::loncommon::start_page('Highlight Central',
 1521: 				       $inner_js_highlight_central,
 1522: 				       {'js_ready'  => 1,
 1523: 					'only_body' => 1,
 1524: 					'bgcolor'   =>'#FFFFFF',});
 1525:     my $end_page_highlight_central = 
 1526: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1527: 
 1528:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1529:     $docopen=~s/^document\.//;
 1530:     my %js_lt = &Apache::lonlocal::texthash(
 1531:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
 1532:                 plse => 'Please select a word or group of words from document and then click this link.',
 1533:                 adds => 'Add selection to keyword list? Edit if desired.',
 1534:                 col1 => 'red',
 1535:                 col2 => 'green',
 1536:                 col3 => 'blue',
 1537:                 siz1 => 'normal',
 1538:                 siz2 => '+1',
 1539:                 siz3 => '+2',
 1540:                 sty1 => 'normal',
 1541:                 sty2 => 'italic',
 1542:                 sty3 => 'bold',
 1543:              );
 1544:     my %html_js_lt = &Apache::lonlocal::texthash(
 1545:                 comp => 'Compose Message for: ',
 1546:                 incl => 'Include',
 1547:                 type => 'Type',
 1548:                 subj => 'Subject',
 1549:                 mesa => 'Message',
 1550:                 new  => 'New',
 1551:                 save => 'Save',
 1552:                 canc => 'Cancel',
 1553:                 kehi => 'Keyword Highlight Options',
 1554:                 txtc => 'Text Color',
 1555:                 font => 'Font Size',
 1556:                 fnst => 'Font Style',
 1557:              );
 1558:     &js_escape(\%js_lt);
 1559:     &html_escape(\%html_js_lt);
 1560:     &js_escape(\%html_js_lt);
 1561:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1562: 
 1563: //===================== Show list of keywords ====================
 1564:   function keywords(formname) {
 1565:     var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
 1566:     if (nret==null) return;
 1567:     formname.keywords.value = nret;
 1568: 
 1569:     if (formname.keywords.value != "") {
 1570: 	formname.refresh.value = "on";
 1571: 	formname.submit();
 1572:     }
 1573:     return;
 1574:   }
 1575: 
 1576: //===================== Script to view submitted by ==================
 1577:   function viewSubmitter(submitter) {
 1578:     document.SCORE.refresh.value = "on";
 1579:     document.SCORE.NCT.value = "1";
 1580:     document.SCORE.unamedom0.value = submitter;
 1581:     document.SCORE.submit();
 1582:     return;
 1583:   }
 1584: 
 1585: //===================== Script to add keyword(s) ==================
 1586:   function getSel() {
 1587:     if (document.getSelection) txt = document.getSelection();
 1588:     else if (document.selection) txt = document.selection.createRange().text;
 1589:     else return;
 1590:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1591:     if (cleantxt=="") {
 1592: 	alert("$js_lt{'plse'}");
 1593: 	return;
 1594:     }
 1595:     var nret = prompt("$js_lt{'adds'}",cleantxt);
 1596:     if (nret==null) return;
 1597:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1598:     if (document.SCORE.keywords.value != "") {
 1599: 	document.SCORE.refresh.value = "on";
 1600: 	document.SCORE.submit();
 1601:     }
 1602:     return;
 1603:   }
 1604: 
 1605: //====================== Script for composing message ==============
 1606:    // preload images
 1607:    img1 = new Image();
 1608:    img1.src = "$iconpath/mailbkgrd.gif";
 1609:    img2 = new Image();
 1610:    img2.src = "$iconpath/mailto.gif";
 1611: 
 1612:   function msgCenter(msgform,usrctr,fullname) {
 1613:     var Nmsg  = msgform.savemsgN.value;
 1614:     savedMsgHeader(Nmsg,usrctr,fullname);
 1615:     var subject = msgform.msgsub.value;
 1616:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1617:     re = /msgsub/;
 1618:     var shwsel = "";
 1619:     if (re.test(msgchk)) { shwsel = "checked" }
 1620:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1621:     displaySubject(checkEntities(subject),shwsel);
 1622:     for (var i=1; i<=Nmsg; i++) {
 1623: 	var testmsg = "savemsg"+i+",";
 1624: 	re = new RegExp(testmsg,"g");
 1625: 	shwsel = "";
 1626: 	if (re.test(msgchk)) { shwsel = "checked" }
 1627: 	var message = document.SCORE["savemsg"+i].value;
 1628: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1629: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1630: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1631:     }
 1632:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1633:     shwsel = "";
 1634:     re = /newmsg/;
 1635:     if (re.test(msgchk)) { shwsel = "checked" }
 1636:     newMsg(newmsg,shwsel);
 1637:     msgTail(); 
 1638:     return;
 1639:   }
 1640: 
 1641:   function checkEntities(strx) {
 1642:     if (strx.length == 0) return strx;
 1643:     var orgStr = ["&", "<", ">", '"']; 
 1644:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1645:     var counter = 0;
 1646:     while (counter < 4) {
 1647: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1648: 	counter++;
 1649:     }
 1650:     return strx;
 1651:   }
 1652: 
 1653:   function strReplace(strx, orgStr, newStr) {
 1654:     return strx.split(orgStr).join(newStr);
 1655:   }
 1656: 
 1657:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1658:     var height = 70*Nmsg+250;
 1659:     if (height > 600) {
 1660: 	height = 600;
 1661:     }
 1662:     var xpos = (screen.width-600)/2;
 1663:     xpos = (xpos < 0) ? '0' : xpos;
 1664:     var ypos = (screen.height-height)/2-30;
 1665:     ypos = (ypos < 0) ? '0' : ypos;
 1666: 
 1667:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
 1668:     pWin.focus();
 1669:     pDoc = pWin.document;
 1670:     pDoc.$docopen;
 1671:     pDoc.write('$start_page_msg_central');
 1672: 
 1673:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1674:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1675:     pDoc.write("<h1>&nbsp;$html_js_lt{'comp'}\"+fullname+\"<\\/h1>");
 1676: 
 1677:     pDoc.write('<table style="border:1px solid black;"><tr>');
 1678:     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>");
 1679: }
 1680:     function displaySubject(msg,shwsel) {
 1681:     pDoc = pWin.document;
 1682:     pDoc.write("<tr>");
 1683:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1684:     pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
 1685:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1686: }
 1687: 
 1688:   function displaySavedMsg(ctr,msg,shwsel) {
 1689:     pDoc = pWin.document;
 1690:     pDoc.write("<tr>");
 1691:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1692:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1693:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1694: }
 1695: 
 1696:   function newMsg(newmsg,shwsel) {
 1697:     pDoc = pWin.document;
 1698:     pDoc.write("<tr>");
 1699:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1700:     pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
 1701:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1702: }
 1703: 
 1704:   function msgTail() {
 1705:     pDoc = pWin.document;
 1706:     //pDoc.write("<\\/table>");
 1707:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1708:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1709:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
 1710:     pDoc.write("<\\/form>");
 1711:     pDoc.write('$end_page_msg_central');
 1712:     pDoc.close();
 1713: }
 1714: 
 1715: //====================== Script for keyword highlight options ==============
 1716:   function kwhighlight() {
 1717:     var kwclr    = document.SCORE.kwclr.value;
 1718:     var kwsize   = document.SCORE.kwsize.value;
 1719:     var kwstyle  = document.SCORE.kwstyle.value;
 1720:     var redsel = "";
 1721:     var grnsel = "";
 1722:     var blusel = "";
 1723:     var txtcol1 = "$js_lt{'col1'}";
 1724:     var txtcol2 = "$js_lt{'col2'}";
 1725:     var txtcol3 = "$js_lt{'col3'}";
 1726:     var txtsiz1 = "$js_lt{'siz1'}";
 1727:     var txtsiz2 = "$js_lt{'siz2'}";
 1728:     var txtsiz3 = "$js_lt{'siz3'}";
 1729:     var txtsty1 = "$js_lt{'sty1'}";
 1730:     var txtsty2 = "$js_lt{'sty2'}";
 1731:     var txtsty3 = "$js_lt{'sty3'}";
 1732:     if (kwclr=="red")   {var redsel="checked='checked'"};
 1733:     if (kwclr=="green") {var grnsel="checked='checked'"};
 1734:     if (kwclr=="blue")  {var blusel="checked='checked'"};
 1735:     var sznsel = "";
 1736:     var sz1sel = "";
 1737:     var sz2sel = "";
 1738:     if (kwsize=="0")  {var sznsel="checked='checked'"};
 1739:     if (kwsize=="+1") {var sz1sel="checked='checked'"};
 1740:     if (kwsize=="+2") {var sz2sel="checked='checked'"};
 1741:     var synsel = "";
 1742:     var syisel = "";
 1743:     var sybsel = "";
 1744:     if (kwstyle=="")    {var synsel="checked='checked'"};
 1745:     if (kwstyle=="<i>") {var syisel="checked='checked'"};
 1746:     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
 1747:     highlightCentral();
 1748:     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
 1749:     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
 1750:     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
 1751:     highlightend();
 1752:     return;
 1753:   }
 1754: 
 1755:   function highlightCentral() {
 1756: //    if (window.hwdWin) window.hwdWin.close();
 1757:     var xpos = (screen.width-400)/2;
 1758:     xpos = (xpos < 0) ? '0' : xpos;
 1759:     var ypos = (screen.height-330)/2-30;
 1760:     ypos = (ypos < 0) ? '0' : ypos;
 1761: 
 1762:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1763:     hwdWin.focus();
 1764:     var hDoc = hwdWin.document;
 1765:     hDoc.$docopen;
 1766:     hDoc.write('$start_page_highlight_central');
 1767:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1768:     hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
 1769: 
 1770:     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
 1771:     hDoc.write("<th>$html_js_lt{'txtc'}<\\/th><th>$html_js_lt{'font'}<\\/th><th>$html_js_lt{'fnst'}<\\/th><\\/tr>");
 1772:   }
 1773: 
 1774:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1775:     var hDoc = hwdWin.document;
 1776:     hDoc.write("<tr>");
 1777:     hDoc.write("<td align=\\"left\\">");
 1778:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
 1779:     hDoc.write("<td align=\\"left\\">");
 1780:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
 1781:     hDoc.write("<td align=\\"left\\">");
 1782:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
 1783:     hDoc.write("<\\/tr>");
 1784:   }
 1785: 
 1786:   function highlightend() { 
 1787:     var hDoc = hwdWin.document;
 1788:     hDoc.write("<\\/table><br \\/>");
 1789:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
 1790:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
 1791:     hDoc.write("<\\/form>");
 1792:     hDoc.write('$end_page_highlight_central');
 1793:     hDoc.close();
 1794:   }
 1795: 
 1796: SUBJAVASCRIPT
 1797: }
 1798: 
 1799: sub get_increment {
 1800:     my $increment = $env{'form.increment'};
 1801:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1802:         $increment != .1) {
 1803:         $increment = 1;
 1804:     }
 1805:     return $increment;
 1806: }
 1807: 
 1808: sub gradeBox_start {
 1809:     return (
 1810:         &Apache::loncommon::start_data_table()
 1811:        .&Apache::loncommon::start_data_table_header_row()
 1812:        .'<th>'.&mt('Part').'</th>'
 1813:        .'<th>'.&mt('Points').'</th>'
 1814:        .'<th>&nbsp;</th>'
 1815:        .'<th>'.&mt('Assign Grade').'</th>'
 1816:        .'<th>'.&mt('Weight').'</th>'
 1817:        .'<th>'.&mt('Grade Status').'</th>'
 1818:        .&Apache::loncommon::end_data_table_header_row()
 1819:     );
 1820: }
 1821: 
 1822: sub gradeBox_end {
 1823:     return (
 1824:         &Apache::loncommon::end_data_table()
 1825:     );
 1826: }
 1827: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1828: sub gradeBox {
 1829:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1830:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1831: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1832:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1833:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1834:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1835:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1836:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1837: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1838:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1839:     my $display_part= &get_display_part($partid,$symb);
 1840:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1841: 				       [$partid]);
 1842:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1843:     if ($last_resets{$partid}) {
 1844:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1845:     }
 1846:     my $result=&Apache::loncommon::start_data_table_row();
 1847:     my $ctr = 0;
 1848:     my $thisweight = 0;
 1849:     my $increment = &get_increment();
 1850: 
 1851:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1852:     while ($thisweight<=$wgt) {
 1853: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1854:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1855: 	    $thisweight.')" value="'.$thisweight.'" '.
 1856: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1857: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1858:         $thisweight += $increment;
 1859: 	$ctr++;
 1860:     }
 1861:     $radio.='</tr></table>';
 1862: 
 1863:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1864: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1865: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1866: 	$wgt.')" /></td>'."\n";
 1867:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1868: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1869: 	' </td>'."\n";
 1870:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1871: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1872:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1873: 	$line.='<option></option>'.
 1874: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1875:     } else {
 1876: 	$line.='<option selected="selected"></option>'.
 1877: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1878:     }
 1879:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1880: 
 1881: 
 1882:     $result .= 
 1883: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 1884:     $result.=&Apache::loncommon::end_data_table_row();
 1885:     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
 1886:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1887: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1888: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1889: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1890:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1891:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1892:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1893:         $aggtries.'" />'."\n";
 1894:     my $res_error;
 1895:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 1896:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
 1897:     if ($res_error) {
 1898:         return &navmap_errormsg();
 1899:     }
 1900:     return $result;
 1901: }
 1902: 
 1903: sub handback_box {
 1904:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
 1905:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
 1906:     my (@respids);
 1907:     my @part_response_id = &flatten_responseType($responseType);
 1908:     foreach my $part_response_id (@part_response_id) {
 1909:     	my ($part,$resp) = @{ $part_response_id };
 1910:         if ($part eq $partid) {
 1911:             push(@respids,$resp);
 1912:         }
 1913:     }
 1914:     my $result;
 1915:     foreach my $respid (@respids) {
 1916: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1917: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1918: 	next if (!@$files);
 1919: 	my $file_counter = 0;
 1920: 	foreach my $file (@$files) {
 1921: 	    if ($file =~ /\/portfolio\//) {
 1922:                 $file_counter++;
 1923:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1924:     	        my ($name,$version,$ext) = &Apache::lonnet::file_name_version_ext($file_disp);
 1925:     	        $file_disp = "$name.$ext";
 1926:     	        $file = $file_path.$file_disp;
 1927:     	        $result.=&mt('Return commented version of [_1] to student.',
 1928:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1929:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1930:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
 1931: 	    }
 1932: 	}
 1933:         if ($file_counter) {
 1934:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
 1935:                        '<span class="LC_info">'.
 1936:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
 1937:         }
 1938:     }
 1939:     return $result;    
 1940: }
 1941: 
 1942: sub show_problem {
 1943:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1944:     my $rendered;
 1945:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1946:     &Apache::lonxml::remember_problem_counter();
 1947:     if ($mode eq 'both' or $mode eq 'text') {
 1948: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1949: 						       $env{'request.course.id'},
 1950: 						       undef,\%form);
 1951:     }
 1952:     if ($removeform) {
 1953: 	$rendered=~s|<form(.*?)>||g;
 1954: 	$rendered=~s|</form>||g;
 1955: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1956:     }
 1957:     my $companswer;
 1958:     if ($mode eq 'both' or $mode eq 'answer') {
 1959: 	&Apache::lonxml::restore_problem_counter();
 1960: 	$companswer=
 1961: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1962: 						    $env{'request.course.id'},
 1963: 						    %form);
 1964:     }
 1965:     if ($removeform) {
 1966: 	$companswer=~s|<form(.*?)>||g;
 1967: 	$companswer=~s|</form>||g;
 1968: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1969:     }
 1970:     my $renderheading = &mt('View of the problem');
 1971:     my $answerheading = &mt('Correct answer');
 1972:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 1973:         my $stu_fullname = $env{'form.fullname'};
 1974:         if ($stu_fullname eq '') {
 1975:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
 1976:         }
 1977:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
 1978:         if ($forwhom ne '') {
 1979:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
 1980:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
 1981:         }
 1982:     }
 1983:     $rendered=
 1984:         '<div class="LC_Box">'
 1985:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
 1986:        .$rendered
 1987:        .'</div>';
 1988:     $companswer=
 1989:         '<div class="LC_Box">'
 1990:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
 1991:        .$companswer
 1992:        .'</div>';
 1993:     my $result;
 1994:     if ($mode eq 'both') {
 1995:         $result=$rendered.$companswer;
 1996:     } elsif ($mode eq 'text') {
 1997:         $result=$rendered;
 1998:     } elsif ($mode eq 'answer') {
 1999:         $result=$companswer;
 2000:     }
 2001:     return $result;
 2002: }
 2003: 
 2004: sub files_exist {
 2005:     my ($r, $symb) = @_;
 2006:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 2007:     foreach my $student (@students) {
 2008:         my ($uname,$udom,$fullname) = split(/:/,$student);
 2009:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 2010: 					      $udom,$uname);
 2011:         my ($string,$timestamp)= &get_last_submission(\%record);
 2012:         foreach my $submission (@$string) {
 2013:             my ($partid,$respid) =
 2014: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2015:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 2016: 					   \%record);
 2017:             return 1 if (@$files);
 2018:         }
 2019:     }
 2020:     return 0;
 2021: }
 2022: 
 2023: sub download_all_link {
 2024:     my ($r,$symb) = @_;
 2025:     unless (&files_exist($r, $symb)) {
 2026:        $r->print(&mt('There are currently no submitted documents.'));
 2027:        return;
 2028:     }
 2029:     my $all_students = 
 2030: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 2031: 
 2032:     my $parts =
 2033: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 2034: 
 2035:     my $identifier = &Apache::loncommon::get_cgi_id();
 2036:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 2037:                              'cgi.'.$identifier.'.symb' => $symb,
 2038:                              'cgi.'.$identifier.'.parts' => $parts,});
 2039:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 2040: 	      &mt('Download All Submitted Documents').'</a>');
 2041:     return;
 2042: }
 2043: 
 2044: sub submit_download_link {
 2045:     my ($request,$symb) = @_;
 2046:     if (!$symb) { return ''; }
 2047: #FIXME: Figure out which type of problem this is and provide appropriate download
 2048:     my $res_error;
 2049:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
 2050:     if (ref($res_error)) {
 2051:         if ($$res_error) {
 2052:             $request->print(&mt('An error occurred retrieving response types'));
 2053:             return;
 2054:         }
 2055:     }
 2056:     my ($numupload,$numessay) = (0,0);
 2057:     if (ref($responseType) eq 'HASH') {
 2058:         foreach my $part (sort(keys(%$responseType))) {
 2059:             foreach my $id (sort(keys(%{ $responseType->{$part} }))) {
 2060:                 my $responsetype = $responseType->{$part}->{$id};
 2061:                 if ($responsetype eq 'essay') {
 2062:                     my $uploadedfiletypes =
 2063:                         &Apache::lonnet::EXT("resource.$part".'_'."$id.uploadedfiletypes",$symb);
 2064:                     if ($uploadedfiletypes) {
 2065:                         $numupload++;
 2066:                     } else {
 2067:                         $numessay++;
 2068:                     }
 2069:                 }
 2070:             }
 2071:         }
 2072:     }
 2073:     if (($numupload) || ($numessay)) {
 2074:         my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
 2075:         my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 2076:         my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
 2077:         (undef,undef,my $fullname) = &getclasslist($getsec,1,$getgroup,$symb,$submitonly,1);
 2078:         if (ref($fullname) eq 'HASH') {
 2079:             my @students = map { $_.':'.$fullname->{$_} } (keys(%{$fullname}));
 2080:             if (@students) {
 2081:                 @{$env{'form.stuinfo'}} = @students;
 2082:                 if ($numupload) {
 2083:                     &download_all_link($request,$symb);
 2084:                 }
 2085: # FIXME Need to provide a mechanism to download essays, i.e., if $numessay > 0
 2086: # Needs to omit user's identity if resource instance is for an anonymous survey.
 2087:             } else {
 2088:                 $request->print(&mt('No students match the criteria you selected'));
 2089:             }
 2090:         } else {
 2091:             $request->print(&mt('Could not retrieve student information'));
 2092:         }
 2093:     } else {
 2094:         $request->print(&mt('No essayresponse items found'));
 2095:     }
 2096:     return;
 2097: }
 2098: 
 2099: sub build_section_inputs {
 2100:     my $section_inputs;
 2101:     if ($env{'form.section'} eq '') {
 2102:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 2103:     } else {
 2104:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 2105:         foreach my $section (@sections) {
 2106:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 2107:         }
 2108:     }
 2109:     return $section_inputs;
 2110: }
 2111: 
 2112: # --------------------------- show submissions of a student, option to grade 
 2113: sub submission {
 2114:     my ($request,$counter,$total,$symb) = @_;
 2115:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 2116:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 2117:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2118:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 2119: 
 2120:     my $probtitle=&Apache::lonnet::gettitle($symb); 
 2121:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 2122:     my $is_tool = ($symb =~ /ext\.tool$/);
 2123: 
 2124:     if (!&canview($usec)) {
 2125:         $request->print(
 2126:             '<span class="LC_warning">'.
 2127:             &mt('Unable to view requested student.').
 2128:             ' '.&mt('([_1] in section [_2] in course id [_3])',
 2129:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
 2130:             '</span>');
 2131: 	return;
 2132:     }
 2133: 
 2134:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 2135:     unless ($is_tool) { 
 2136:         if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 2137:         if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 2138:     }
 2139:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 2140:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 2141: 	'" src="'.$request->dir_config('lonIconsURL').
 2142: 	'/check.gif" height="16" border="0" />';
 2143: 
 2144:     # header info
 2145:     if ($counter == 0) {
 2146: 	&sub_page_js($request);
 2147: 	&sub_page_kw_js($request);
 2148: 
 2149: 	# option to display problem, only once else it cause problems 
 2150:         # with the form later since the problem has a form.
 2151: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 2152: 	    my $mode;
 2153: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 2154: 		$mode='both';
 2155: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 2156: 		$mode='text';
 2157: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 2158: 		$mode='answer';
 2159: 	    }
 2160: 	    &Apache::lonxml::clear_problem_counter();
 2161: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 2162: 	}
 2163: 
 2164: 	# kwclr is the only variable that is guaranteed not to be blank 
 2165:         # if this subroutine has been called once.
 2166: 	my %keyhash = ();
 2167: #	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 2168:         if (1) {
 2169: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 2170: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 2171: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 2172: 
 2173: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2174: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 2175: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 2176: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 2177: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 2178: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 2179: 		$keyhash{$symb.'_subject'} : $probtitle;
 2180: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 2181: 	}
 2182: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 2183: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 2184: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 2185: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 2186: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 2187: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 2188: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 2189: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 2190: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 2191: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 2192: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 2193: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 2194: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 2195: 			&build_section_inputs().
 2196: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 2197: 			'<input type="hidden" name="NCT"'.
 2198: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 2199: #	if ($env{'form.handgrade'} eq 'yes') {
 2200:         if (1) {
 2201: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 2202: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 2203: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 2204: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 2205: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2206: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2207: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2208: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 2209: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 2210: 	    }
 2211: 	}
 2212: 	
 2213: 	my ($cts,$prnmsg) = (1,'');
 2214: 	while ($cts <= $env{'form.savemsgN'}) {
 2215: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2216: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2217: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2218: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2219: 		'" />'."\n".
 2220: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2221: 	    $cts++;
 2222: 	}
 2223: 	$request->print($prnmsg);
 2224: 
 2225: #	if ($env{'form.handgrade'} eq 'yes') {
 2226:         unless ($is_tool) {
 2227: 
 2228:             my %lt = &Apache::lonlocal::texthash(
 2229:                           keyh => 'Keyword Highlighting for Essays',
 2230:                           keyw => 'Keyword Options',
 2231:                           list => 'List',
 2232:                           past => 'Paste Selection to List',
 2233:                           high => 'Highlight Attribute',
 2234:                      );    
 2235: #
 2236: # Print out the keyword options line
 2237: #
 2238: 	    $request->print(
 2239:                 '<div class="LC_columnSection">'
 2240:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
 2241:                .&Apache::lonhtmlcommon::funclist_from_array(
 2242:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
 2243:                      '<a href="#" onmousedown="javascript:getSel(); return false"
 2244:  class="page">'.$lt{'past'}.'</a>',
 2245:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
 2246:                     {legend => $lt{'keyw'}})
 2247:                .'</fieldset></div>'
 2248:             );
 2249: 
 2250: #
 2251: # Load the other essays for similarity check
 2252: #
 2253:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2254: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2255: 	    $apath=&escape($apath);
 2256: 	    $apath=~s/\W/\_/gs;
 2257:             &init_old_essays($symb,$apath,$adom,$aname);
 2258:         }
 2259:     }
 2260: 
 2261: # This is where output for one specific student would start
 2262:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2263:     $request->print(
 2264:         "\n\n"
 2265:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2266:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2267:        ."\n"
 2268:     );
 2269: 
 2270:     # Show additional functions if allowed
 2271:     if ($perm{'vgr'}) {
 2272:         $request->print(
 2273:             &Apache::loncommon::track_student_link(
 2274:                 'View recent activity',
 2275:                 $uname,$udom,'check')
 2276:            .' '
 2277:         );
 2278:     }
 2279:     if ($perm{'opa'}) {
 2280:         $request->print(
 2281:             &Apache::loncommon::pprmlink(
 2282:                 &mt('Set/Change parameters'),
 2283:                 $uname,$udom,$symb,'check'));
 2284:     }
 2285: 
 2286:     # Show Problem
 2287:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2288: 	my $mode;
 2289: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2290: 	    $mode='both';
 2291: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2292: 	    $mode='text';
 2293: 	} elsif ($env{'form.vAns'} eq 'all') {
 2294: 	    $mode='answer';
 2295: 	}
 2296: 	&Apache::lonxml::clear_problem_counter();
 2297: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2298:     }
 2299: 
 2300:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2301:     my $res_error;
 2302:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2303:     if ($res_error) {
 2304:         $request->print(&navmap_errormsg());
 2305:         return;
 2306:     }
 2307: 
 2308:     # Display student info
 2309:     $request->print(($counter == 0 ? '' : '<br />'));
 2310: 
 2311:     my $boxtitle = &mt('Submissions');
 2312:     if ($is_tool) {
 2313:         $boxtitle = &mt('Transactions')
 2314:     }
 2315:     my $result='<div class="LC_Box">'
 2316:               .'<h3 class="LC_hcell">'.$boxtitle.'</h3>';
 2317:     $result.='<input type="hidden" name="name'.$counter.
 2318:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2319: #    if ($env{'form.handgrade'} eq 'no') {
 2320:     unless ($is_tool) {
 2321:         $result.='<p class="LC_info">'
 2322:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2323:                 ."</p>\n";
 2324:     }
 2325: 
 2326:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2327:     my $fullname;
 2328:     my $col_fullnames = [];
 2329: #    if ($env{'form.handgrade'} eq 'yes') {
 2330:     unless ($is_tool) {
 2331: 	(my $sub_result,$fullname,$col_fullnames)=
 2332: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2333: 				 $counter);
 2334: 	$result.=$sub_result;
 2335:     }
 2336:     $request->print($result."\n");
 2337:     
 2338:     # print student answer/submission
 2339:     # Options are (1) Handgraded submission only
 2340:     #             (2) Last submission, includes submission that is not handgraded 
 2341:     #                  (for multi-response type part)
 2342:     #             (3) Last submission plus the parts info
 2343:     #             (4) The whole record for this student
 2344:     
 2345:     my ($string,$timestamp)= &get_last_submission(\%record,$is_tool);
 2346: 	
 2347:     my $lastsubonly;
 2348: 
 2349:     if ($$timestamp eq '') {
 2350:         $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2351:     } elsif ($is_tool) {
 2352:         $lastsubonly =
 2353:             '<div class="LC_grade_submissions_body">'
 2354:            .'<b>'.&mt('Date Grade Passed Back:').'</b> '.$$timestamp."</div>\n";
 2355:     } else {
 2356:         $lastsubonly =
 2357:             '<div class="LC_grade_submissions_body">'
 2358:            .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
 2359: 
 2360: 	my %seenparts;
 2361: 	my @part_response_id = &flatten_responseType($responseType);
 2362: 	foreach my $part (@part_response_id) {
 2363: 	    next if ($env{'form.lastSub'} eq 'hdgrade' 
 2364: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2365: 
 2366: 	    my ($partid,$respid) = @{ $part };
 2367: 	    my $display_part=&get_display_part($partid,$symb);
 2368: 	    if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2369: 		if (exists($seenparts{$partid})) { next; }
 2370: 		$seenparts{$partid}=1;
 2371:                 $request->print(
 2372:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2373:                     ' <b>'.&mt('Collaborative submission by: [_1]',
 2374:                                '<a href="javascript:viewSubmitter(\''.
 2375:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
 2376:                                '\');" target="_self">'.
 2377:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
 2378:                     '<br />');
 2379: 		next;
 2380: 		}
 2381: 	    my $responsetype = $responseType->{$partid}->{$respid};
 2382: 	    if (!exists($record{"resource.$partid.$respid.submission"})) {
 2383:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2384:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2385:                     ' <span class="LC_internal_info">'.
 2386:                     '('.&mt('Response ID: [_1]',$respid).')'.
 2387:                     '</span>&nbsp; &nbsp;'.
 2388: 	       	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2389: 		next;
 2390: 	    }
 2391: 	    foreach my $submission (@$string) {
 2392: 		my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2393: 		if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2394: 		my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
 2395: 		# Similarity check
 2396:                 my $similar='';
 2397:                 my ($type,$trial,$rndseed);
 2398:                 if ($hide eq 'rand') {
 2399:                     $type = 'randomizetry';
 2400:                     $trial = $record{"resource.$partid.tries"};
 2401:                     $rndseed = $record{"resource.$partid.rndseed"};
 2402:                 }
 2403: 	        if ($env{'form.checkPlag'}) {
 2404:     		    my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2405: 		        &most_similar($uname,$udom,$symb,$subval);
 2406: 		    if ($osim) {
 2407: 			$osim=int($osim*100.0);
 2408: 			my %old_course_desc = 
 2409: 			    &Apache::lonnet::coursedescription($ocrsid,
 2410: 							{'one_time' => 1});
 2411: 
 2412:                         if ($hide eq 'anon') {
 2413:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2414:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2415:                         } else {
 2416: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
 2417: 				&mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2418: 				    $osim,
 2419: 				    &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2420: 				        $old_course_desc{'description'},
 2421: 				        $old_course_desc{'num'},
 2422: 				        $old_course_desc{'domain'}).
 2423: 				    '</span></h3><blockquote><i>'.
 2424: 				    &keywords_highlight($oessay).
 2425: 				    '</i></blockquote><hr />';
 2426:                         }
 2427: 	            }
 2428: 		}
 2429: 		my $order=&get_order($partid,$respid,$symb,$uname,$udom,
 2430:                                      undef,$type,$trial,$rndseed);
 2431:                 if ($env{'form.lastSub'} eq 'lastonly' || $env{'form.lastSub'} eq 'datesub' || $env{'form.lastSub'} =~ /^(last|all)$/ || ($env{'form.lastSub'} eq 'hdgrade' && 
 2432: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2433: 		    my $display_part=&get_display_part($partid,$symb);
 2434:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
 2435:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2436:                         ' <span class="LC_internal_info">'.
 2437:                         '('.&mt('Response ID: [_1]',$respid).')'.
 2438:                         '</span>&nbsp; &nbsp;';
 2439: 		    my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2440:                         
 2441: 		    if (@$files) {
 2442:                         if ($hide eq 'anon') {
 2443:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2444:                         } else {
 2445:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
 2446:                                         .'<br /><span class="LC_warning">';
 2447:                             if(@$files == 1) {
 2448:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
 2449:                             } else {
 2450:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
 2451:                             }
 2452:                             $lastsubonly .= '</span>';                         
 2453:                             foreach my $file (@$files) {
 2454:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2455:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
 2456:                             }
 2457:                         }
 2458: 			$lastsubonly.='<br />';
 2459:                     }
 2460:                     if ($hide eq 'anon') {
 2461:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
 2462:                     } else {
 2463:              	        $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
 2464:                         if ($draft) {
 2465:                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
 2466:                         }
 2467:                         $subval =
 2468: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
 2469: 					 $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
 2470:                         if ($responsetype eq 'essay') {
 2471:                             $subval =~ s{\n}{<br />}g;
 2472:                         }
 2473:                         $lastsubonly.=$subval."\n";
 2474:                     }
 2475: 	            if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2476: 		    $lastsubonly.='</div>';
 2477: 		}
 2478:             }
 2479: 	}
 2480: 	$lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2481:     }
 2482:     $request->print($lastsubonly);
 2483:     if ($env{'form.lastSub'} eq 'datesub') {
 2484:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2485: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2486:   
 2487:     } 
 2488:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2489:         my $identifier = (&canmodify($usec)? $counter : '');
 2490:         $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2491: 								 $env{'request.course.id'},
 2492: 								 $last,'.submission',
 2493: 								 'Apache::grades::keywords_highlight',
 2494:                                                                  $usec,$identifier));
 2495:     }
 2496:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2497: 	.$udom.'" />'."\n");
 2498:     # return if view submission with no grading option
 2499:     if (!&canmodify($usec)) {
 2500: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
 2501: 	return;
 2502:     } else {
 2503: 	$request->print('</div>'."\n");
 2504:     }
 2505: 
 2506:     # essay grading message center
 2507: #    if ($env{'form.handgrade'} eq 'yes') {
 2508:     if (1) {
 2509: 	my $result='<div class="LC_grade_message_center">';
 2510:     
 2511: 	$result.='<div class="LC_grade_message_center_header">'.
 2512: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2513: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2514: 	my $msgfor = $givenn.' '.$lastname;
 2515: 	if (scalar(@$col_fullnames) > 0) {
 2516: 	    my $lastone = pop(@$col_fullnames);
 2517: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2518: 	}
 2519: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2520: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2521: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2522: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2523: 	    ',\''.$msgfor.'\');" target="_self">'.
 2524: 	    &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
 2525: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2526: 	    ' <img src="'.$request->dir_config('lonIconsURL').
 2527: 	    '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
 2528: 	    '<br />&nbsp;('.
 2529: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2530: 	$result.='</div></div>';
 2531: 	$request->print($result);
 2532:     }
 2533: 
 2534:     my %seen = ();
 2535:     my @partlist;
 2536:     my @gradePartRespid;
 2537:     my @part_response_id;
 2538:     if ($is_tool) {
 2539:         @part_response_id = ([0,'']);
 2540:     } else {
 2541:         @part_response_id = &flatten_responseType($responseType);
 2542:     }
 2543:     $request->print(
 2544:         '<div class="LC_Box">'
 2545:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2546:     );
 2547:     $request->print(&gradeBox_start());
 2548:     foreach my $part_response_id (@part_response_id) {
 2549:     	my ($partid,$respid) = @{ $part_response_id };
 2550: 	my $part_resp = join('_',@{ $part_response_id });
 2551: 	next if ($seen{$partid} > 0);
 2552: 	$seen{$partid}++;
 2553: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2554: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2555: 	push(@partlist,$partid);
 2556: 	push(@gradePartRespid,$partid.'.'.$respid);
 2557: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2558:     }
 2559:     $request->print(&gradeBox_end()); # </div>
 2560:     $request->print('</div>');
 2561: 
 2562:     $request->print('<div class="LC_grade_info_links">');
 2563:     $request->print('</div>');
 2564: 
 2565:     $result='<input type="hidden" name="partlist'.$counter.
 2566: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2567:     $result.='<input type="hidden" name="gradePartRespid'.
 2568: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2569:     my $ctr = 0;
 2570:     while ($ctr < scalar(@partlist)) {
 2571: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2572: 	    $partlist[$ctr].'" />'."\n";
 2573: 	$ctr++;
 2574:     }
 2575:     $request->print($result.''."\n");
 2576: 
 2577: # Done with printing info for one student
 2578: 
 2579:     $request->print('</div>');#LC_grade_show_user
 2580: 
 2581: 
 2582:     # print end of form
 2583:     if ($counter == $total) {
 2584:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2585: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2586: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2587: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2588: 	my $ntstu ='<select name="NTSTU">'.
 2589: 	    '<option>1</option><option>2</option>'.
 2590: 	    '<option>3</option><option>5</option>'.
 2591: 	    '<option>7</option><option>10</option></select>'."\n";
 2592: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2593: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2594:         $endform.=&mt('[_1]student(s)',$ntstu);
 2595: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2596: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2597: 	    '<input type="button" value="'.&mt('Next').'" '.
 2598: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2599:         $endform.='<span class="LC_warning">'.
 2600:                   &mt('(Next and Previous (student) do not save the scores.)').
 2601:                   '</span>'."\n" ;
 2602:         $endform.="<input type='hidden' value='".&get_increment().
 2603:             "' name='increment' />";
 2604: 	$endform.='</td></tr></table></form>';
 2605: 	$request->print($endform);
 2606:     }
 2607:     return '';
 2608: }
 2609: 
 2610: sub check_collaborators {
 2611:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2612:     my ($result,@col_fullnames);
 2613:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2614:     foreach my $part (keys(%$handgrade)) {
 2615: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2616: 					'.maxcollaborators',
 2617: 					$symb,$udom,$uname);
 2618: 	next if ($ncol <= 0);
 2619: 	$part =~ s/\_/\./g;
 2620: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2621: 	my (@good_collaborators, @bad_collaborators);
 2622: 	foreach my $possible_collaborator
 2623: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2624: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2625: 	    next if ($possible_collaborator eq '');
 2626: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
 2627: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2628: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2629: 	    # Doing this grep allows 'fuzzy' specification
 2630: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2631: 			       keys(%$classlist));
 2632: 	    if (! scalar(@matches)) {
 2633: 		push(@bad_collaborators, $possible_collaborator);
 2634: 	    } else {
 2635: 		push(@good_collaborators, @matches);
 2636: 	    }
 2637: 	}
 2638: 	if (scalar(@good_collaborators) != 0) {
 2639: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
 2640: 	    foreach my $name (@good_collaborators) {
 2641: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2642: 		push(@col_fullnames, $givenn.' '.$lastname);
 2643: 		$result.='<li>'.$fullname->{$name}.'</li>';
 2644: 	    }
 2645: 	    $result.='</ol><br />'."\n";
 2646: 	    my ($part)=split(/\./,$part);
 2647: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2648: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2649: 		"\n";
 2650: 	}
 2651: 	if (scalar(@bad_collaborators) > 0) {
 2652: 	    $result.='<div class="LC_warning">';
 2653: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2654: 	    $result .= '</div>';
 2655: 	}         
 2656: 	if (scalar(@bad_collaborators > $ncol)) {
 2657: 	    $result .= '<div class="LC_warning">';
 2658: 	    $result .= &mt('This student has submitted too many '.
 2659: 		'collaborators.  Maximum is [_1].',$ncol);
 2660: 	    $result .= '</div>';
 2661: 	}
 2662:     }
 2663:     return ($result,$fullname,\@col_fullnames);
 2664: }
 2665: 
 2666: #--- Retrieve the last submission for all the parts
 2667: sub get_last_submission {
 2668:     my ($returnhash,$is_tool)=@_;
 2669:     my (@string,$timestamp,%lasthidden);
 2670:     if ($$returnhash{'version'}) {
 2671: 	my %lasthash=();
 2672: 	my ($version);
 2673: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2674: 	    foreach my $key (sort(split(/\:/,
 2675: 					$$returnhash{$version.':keys'}))) {
 2676: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2677: 		$timestamp = 
 2678: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2679: 	    }
 2680: 	}
 2681:         my (%typeparts,%randombytry);
 2682:         my $showsurv = 
 2683:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2684:         foreach my $key (sort(keys(%lasthash))) {
 2685:             if ($key =~ /\.type$/) {
 2686:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2687:                     ($lasthash{$key} eq 'anonsurveycred') ||
 2688:                     ($lasthash{$key} eq 'randomizetry')) {
 2689:                     my ($ign,@parts) = split(/\./,$key);
 2690:                     pop(@parts);
 2691:                     my $id = join('.',@parts);
 2692:                     if ($lasthash{$key} eq 'randomizetry') {
 2693:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
 2694:                     } else {
 2695:                         unless ($showsurv) {
 2696:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2697:                         }
 2698:                     }
 2699:                     delete($lasthash{$key});
 2700:                 }
 2701:             }
 2702:         }
 2703:         my @hidden = keys(%typeparts);
 2704:         my @randomize = keys(%randombytry);
 2705: 	foreach my $key (keys(%lasthash)) {
 2706: 	    next if ($key !~ /\.submission$/);
 2707:             my $hide;
 2708:             if (@hidden) {
 2709:                 foreach my $id (@hidden) {
 2710:                     if ($key =~ /^\Q$id\E/) {
 2711:                         $hide = 'anon';
 2712:                         last;
 2713:                     }
 2714:                 }
 2715:             }
 2716:             unless ($hide) {
 2717:                 if (@randomize) {
 2718:                     foreach my $id (@randomize) {
 2719:                         if ($key =~ /^\Q$id\E/) {
 2720:                             $hide = 'rand';
 2721:                             last;
 2722:                         }
 2723:                     }
 2724:                 }
 2725:             }
 2726: 	    my ($partid,$foo) = split(/submission$/,$key);
 2727: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
 2728:             push(@string, join(':', $key, $hide, $draft, (
 2729:                 ref($lasthash{$key}) eq 'ARRAY' ?
 2730:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
 2731: 	}
 2732:     }
 2733:     if (!@string) {
 2734:         my $msg;
 2735:         if ($is_tool) {
 2736:             $msg = &mt('No grade passed back.');
 2737:         } else {
 2738:             $msg = &mt('Nothing submitted - no attempts.');
 2739:         }
 2740: 	$string[0] =
 2741: 	    '<span class="LC_warning">'.$msg.'</span>';
 2742:     }
 2743:     return (\@string,\$timestamp);
 2744: }
 2745: 
 2746: #--- High light keywords, with style choosen by user.
 2747: sub keywords_highlight {
 2748:     my $string    = shift;
 2749:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2750:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2751:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2752:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2753:     foreach my $keyword (@keylist) {
 2754: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2755:     }
 2756:     return $string;
 2757: }
 2758: 
 2759: # For Tasks provide a mechanism to display previous version for one specific student
 2760: 
 2761: sub show_previous_task_version {
 2762:     my ($request,$symb) = @_;
 2763:     if ($symb eq '') {
 2764:         $request->print(
 2765:             '<span class="LC_error">'.
 2766:             &mt('Unable to handle ambiguous references.').
 2767:             '</span>');
 2768:         return '';
 2769:     }
 2770:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
 2771:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2772:     if (!&canview($usec)) {
 2773:         $request->print(
 2774:             '<span class="LC_warning">'.
 2775:             &mt('Unable to view previous version for requested student.').
 2776:             ' '.&mt('([_1] in section [_2] in course id [_3])',
 2777:                     $uname.':'.$udom,$usec,$env{'request.course.id'}).
 2778:             '</span>');
 2779:         return;
 2780:     }
 2781:     my $mode = 'both';
 2782:     my $isTask = ($symb =~/\.task$/);
 2783:     if ($isTask) {
 2784:         if ($env{'form.previousversion'} =~ /^\d+$/) {
 2785:             if ($env{'form.fullname'} eq '') {
 2786:                 $env{'form.fullname'} =
 2787:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
 2788:             }
 2789:             my $probtitle=&Apache::lonnet::gettitle($symb);
 2790:             $request->print("\n\n".
 2791:                             '<div class="LC_grade_show_user">'.
 2792:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 2793:                             '</h2>'."\n");
 2794:             &Apache::lonxml::clear_problem_counter();
 2795:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
 2796:                             {'previousversion' => $env{'form.previousversion'} }));
 2797:             $request->print("\n</div>");
 2798:         }
 2799:     }
 2800:     return;
 2801: }
 2802: 
 2803: sub choose_task_version_form {
 2804:     my ($symb,$uname,$udom,$nomenu) = @_;
 2805:     my $isTask = ($symb =~/\.task$/);
 2806:     my ($current,$version,$result,$js,$displayed,$rowtitle);
 2807:     if ($isTask) {
 2808:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 2809:                                               $udom,$uname);
 2810:         if (($record{'resource.0.version'} eq '') ||
 2811:             ($record{'resource.0.version'} < 2)) {
 2812:             return ($record{'resource.0.version'},
 2813:                     $record{'resource.0.version'},$result,$js);
 2814:         } else {
 2815:             $current = $record{'resource.0.version'};
 2816:         }
 2817:         if ($env{'form.previousversion'}) {
 2818:             $displayed = $env{'form.previousversion'};
 2819:             $rowtitle = &mt('Choose another version:')
 2820:         } else {
 2821:             $displayed = $current;
 2822:             $rowtitle = &mt('Show earlier version:');
 2823:         }
 2824:         $result = '<div class="LC_left_float">';
 2825:         my $list;
 2826:         my $numversions = 0;
 2827:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
 2828:             if ($i == $current) {
 2829:                 if (!$env{'form.previousversion'} || $nomenu) {
 2830:                     next;
 2831:                 } else {
 2832:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
 2833:                     $numversions ++;
 2834:                 }
 2835:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
 2836:                 unless ($i == $env{'form.previousversion'}) {
 2837:                     $numversions ++;
 2838:                 }
 2839:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
 2840:             }
 2841:         }
 2842:         if ($numversions) {
 2843:             $symb = &HTML::Entities::encode($symb,'<>"&');
 2844:             $result .=
 2845:                 '<form name="getprev" method="post" action=""'.
 2846:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
 2847:                 &Apache::loncommon::start_data_table().
 2848:                 &Apache::loncommon::start_data_table_row().
 2849:                 '<th align="left">'.$rowtitle.'</th>'.
 2850:                 '<td><select name="version">'.
 2851:                 '<option>'.&mt('Select').'</option>'.
 2852:                 $list.
 2853:                 '</select></td>'.
 2854:                 &Apache::loncommon::end_data_table_row();
 2855:             unless ($nomenu) {
 2856:                 $result .= &Apache::loncommon::start_data_table_row().
 2857:                 '<th align="left">'.&mt('Open in new window').'</th>'.
 2858:                 '<td><span class="LC_nobreak">'.
 2859:                 '<label><input type="radio" name="prevwin" value="1" />'.
 2860:                 &mt('Yes').'</label>'.
 2861:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
 2862:                 '</span></td>'.
 2863:                 &Apache::loncommon::end_data_table_row();
 2864:             }
 2865:             $result .=
 2866:                 &Apache::loncommon::start_data_table_row().
 2867:                 '<th align="left">&nbsp;</th>'.
 2868:                 '<td>'.
 2869:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
 2870:                 '</td>'.
 2871:                 &Apache::loncommon::end_data_table_row().
 2872:                 &Apache::loncommon::end_data_table().
 2873:                 '</form>';
 2874:             $js = &previous_display_javascript($nomenu,$current);
 2875:         } elsif ($displayed && $nomenu) {
 2876:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
 2877:         } else {
 2878:             $result .= &mt('No previous versions to show for this student');
 2879:         }
 2880:         $result .= '</div>';
 2881:     }
 2882:     return ($current,$displayed,$result,$js);
 2883: }
 2884: 
 2885: sub previous_display_javascript {
 2886:     my ($nomenu,$current) = @_;
 2887:     my $js = <<"JSONE";
 2888: <script type="text/javascript">
 2889: // <![CDATA[
 2890: function previousVersion(uname,udom,symb) {
 2891:     var current = '$current';
 2892:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
 2893:     var prevstr = new RegExp("^\\\\d+\$");
 2894:     if (!prevstr.test(version)) {
 2895:         return false;
 2896:     }
 2897:     var url = '';
 2898:     if (version == current) {
 2899:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
 2900:     } else {
 2901:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
 2902:     }
 2903: JSONE
 2904:     if ($nomenu) {
 2905:         $js .= <<"JSTWO";
 2906:     document.location.href = url;
 2907: JSTWO
 2908:     } else {
 2909:         $js .= <<"JSTHREE";
 2910:     var newwin = 0;
 2911:     for (var i=0; i<document.getprev.prevwin.length; i++) {
 2912:         if (document.getprev.prevwin[i].checked == true) {
 2913:             newwin = document.getprev.prevwin[i].value;
 2914:         }
 2915:     }
 2916:     if (newwin == 1) {
 2917:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
 2918:         url = url+'&inhibitmenu=yes';
 2919:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
 2920:             previousWin = window.open(url,'',options,1);
 2921:         } else {
 2922:             previousWin.location.href = url;
 2923:         }
 2924:         previousWin.focus();
 2925:         return false;
 2926:     } else {
 2927:         document.location.href = url;
 2928:         return false;
 2929:     }
 2930: JSTHREE
 2931:     }
 2932:     $js .= <<"ENDJS";
 2933:     return false;
 2934: }
 2935: // ]]>
 2936: </script>
 2937: ENDJS
 2938: 
 2939: }
 2940: 
 2941: #--- Called from submission routine
 2942: sub processHandGrade {
 2943:     my ($request,$symb) = @_;
 2944:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2945:     my $button = $env{'form.gradeOpt'};
 2946:     my $ngrade = $env{'form.NCT'};
 2947:     my $ntstu  = $env{'form.NTSTU'};
 2948:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2949:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2950: 
 2951:     if ($button eq 'Save & Next') {
 2952: 	my $ctr = 0;
 2953: 	while ($ctr < $ngrade) {
 2954: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2955: 	    my ($errorflag,$pts,$wgt,$numhidden) = 
 2956:                 &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2957: 	    if ($errorflag eq 'no_score') {
 2958: 		$ctr++;
 2959: 		next;
 2960: 	    }
 2961: 	    if ($errorflag eq 'not_allowed') {
 2962: 		$request->print(
 2963:                     '<span class="LC_error">'
 2964:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
 2965:                    .'</span>');
 2966: 		$ctr++;
 2967: 		next;
 2968: 	    }
 2969:             if ($numhidden) {
 2970:                 $request->print(
 2971:                     '<span class="LC_info">'
 2972:                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
 2973:                    .'</span><br />');
 2974:             }
 2975: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2976: 	    my ($subject,$message,$msgstatus) = ('','','');
 2977: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2978:             my ($feedurl,$showsymb) =
 2979: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2980: 	    my $messagetail;
 2981: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2982: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2983: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2984: 		$subject.=' ['.$restitle.']';
 2985: 		my (@msgnum) = split(/,/,$includemsg);
 2986: 		foreach (@msgnum) {
 2987: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2988: 		}
 2989: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2990: 		if ($env{'form.withgrades'.$ctr}) {
 2991: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2992: 		    $messagetail = " for <a href=\"".
 2993: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
 2994: 		}
 2995: 		$msgstatus = 
 2996:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2997: 						     $message.$messagetail,
 2998:                                                      undef,$feedurl,undef,
 2999:                                                      undef,undef,$showsymb,
 3000:                                                      $restitle);
 3001: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 3002: 				$msgstatus.'<br />');
 3003: 	    }
 3004: 	    if ($env{'form.collaborator'.$ctr}) {
 3005: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 3006: 		foreach my $collabstr (@collabstrs) {
 3007: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 3008: 		    foreach my $collaborator (@collaborators) {
 3009: 			my ($errorflag,$pts,$wgt) = 
 3010: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 3011: 					   $env{'form.unamedom'.$ctr},$part);
 3012: 			if ($errorflag eq 'not_allowed') {
 3013: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 3014: 			    next;
 3015: 			} elsif ($message ne '') {
 3016: 			    my ($baseurl,$showsymb) = 
 3017: 				&get_feedurl_and_symb($symb,$collaborator,
 3018: 						      $udom);
 3019: 			    if ($env{'form.withgrades'.$ctr}) {
 3020: 				$messagetail = " for <a href=\"".
 3021:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
 3022: 			    }
 3023: 			    $msgstatus = 
 3024: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 3025: 			}
 3026: 		    }
 3027: 		}
 3028: 	    }
 3029: 	    $ctr++;
 3030: 	}
 3031:     }
 3032: 
 3033: #    if ($env{'form.handgrade'} eq 'yes') {
 3034:     if (1) {
 3035: 	# Keywords sorted in alphabatical order
 3036: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 3037: 	my %keyhash = ();
 3038: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 3039: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 3040: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 3041: 	$env{'form.keywords'} = join(' ',@keywords);
 3042: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 3043: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 3044: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 3045: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 3046: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 3047: 
 3048: 	# message center - Order of message gets changed. Blank line is eliminated.
 3049: 	# New messages are saved in env for the next student.
 3050: 	# All messages are saved in nohist_handgrade.db
 3051: 	my ($ctr,$idx) = (1,1);
 3052: 	while ($ctr <= $env{'form.savemsgN'}) {
 3053: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 3054: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 3055: 		$idx++;
 3056: 	    }
 3057: 	    $ctr++;
 3058: 	}
 3059: 	$ctr = 0;
 3060: 	while ($ctr < $ngrade) {
 3061: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 3062: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 3063: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 3064: 		$idx++;
 3065: 	    }
 3066: 	    $ctr++;
 3067: 	}
 3068: 	$env{'form.savemsgN'} = --$idx;
 3069: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 3070: 	my $putresult = &Apache::lonnet::put
 3071: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 3072:     }
 3073:     # Called by Save & Refresh from Highlight Attribute Window
 3074:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3075:     if ($env{'form.refresh'} eq 'on') {
 3076: 	my ($ctr,$total) = (0,0);
 3077: 	while ($ctr < $ngrade) {
 3078: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 3079: 	    $ctr++;
 3080: 	}
 3081: 	$env{'form.NTSTU'}=$ngrade;
 3082: 	$ctr = 0;
 3083: 	while ($ctr < $total) {
 3084: 	    my $processUser = $env{'form.unamedom'.$ctr};
 3085: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 3086: 	    $env{'form.fullname'} = $$fullname{$processUser};
 3087: 	    &submission($request,$ctr,$total-1,$symb);
 3088: 	    $ctr++;
 3089: 	}
 3090: 	return '';
 3091:     }
 3092: 
 3093:     # Get the next/previous one or group of students
 3094:     my $firststu = $env{'form.unamedom0'};
 3095:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 3096:     my $ctr = 2;
 3097:     while ($laststu eq '') {
 3098: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 3099: 	$ctr++;
 3100: 	$laststu = $firststu if ($ctr > $ngrade);
 3101:     }
 3102: 
 3103:     my (@parsedlist,@nextlist);
 3104:     my ($nextflg) = 0;
 3105:     foreach my $item (sort 
 3106: 	     {
 3107: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3108: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3109: 		 }
 3110: 		 return $a cmp $b;
 3111: 	     } (keys(%$fullname))) {
 3112: # FIXME: this is fishy, looks like the button label
 3113: 	if ($nextflg == 1 && $button =~ /Next$/) {
 3114: 	    push(@parsedlist,$item);
 3115: 	}
 3116: 	$nextflg = 1 if ($item eq $laststu);
 3117: 	if ($button eq 'Previous') {
 3118: 	    last if ($item eq $firststu);
 3119: 	    push(@parsedlist,$item);
 3120: 	}
 3121:     }
 3122:     $ctr = 0;
 3123: # FIXME: this is fishy, looks like the button label
 3124:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 3125:     my $res_error;
 3126:     my ($partlist) = &response_type($symb,\$res_error);
 3127:     if ($res_error) {
 3128:         $request->print(&navmap_errormsg());
 3129:         return;
 3130:     }
 3131:     foreach my $student (@parsedlist) {
 3132: 	my $submitonly=$env{'form.submitonly'};
 3133: 	my ($uname,$udom) = split(/:/,$student);
 3134: 	
 3135: 	if ($submitonly eq 'queued') {
 3136: 	    my %queue_status = 
 3137: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 3138: 							$udom,$uname);
 3139: 	    next if (!defined($queue_status{'gradingqueue'}));
 3140: 	}
 3141: 
 3142: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 3143: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 3144: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 3145: 	    my $submitted = 0;
 3146: 	    my $ungraded = 0;
 3147: 	    my $incorrect = 0;
 3148: 	    foreach my $item (keys(%status)) {
 3149: 		$submitted = 1 if ($status{$item} ne 'nothing');
 3150: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 3151: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 3152: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 3153: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 3154: 		    $submitted = 0;
 3155: 		}
 3156: 	    }
 3157: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 3158: 				     $submitonly eq 'incorrect' ||
 3159: 				     $submitonly eq 'graded'));
 3160: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 3161: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 3162: 	}
 3163: 	push(@nextlist,$student) if ($ctr < $ntstu);
 3164: 	last if ($ctr == $ntstu);
 3165: 	$ctr++;
 3166:     }
 3167: 
 3168:     $ctr = 0;
 3169:     my $total = scalar(@nextlist)-1;
 3170: 
 3171:     foreach (sort(@nextlist)) {
 3172: 	my ($uname,$udom,$submitter) = split(/:/);
 3173: 	$env{'form.student'}  = $uname;
 3174: 	$env{'form.userdom'}  = $udom;
 3175: 	$env{'form.fullname'} = $$fullname{$_};
 3176: 	&submission($request,$ctr,$total,$symb);
 3177: 	$ctr++;
 3178:     }
 3179:     if ($total < 0) {
 3180: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
 3181: 	$request->print($the_end);
 3182:     }
 3183:     return '';
 3184: }
 3185: 
 3186: #---- Save the score and award for each student, if changed
 3187: sub saveHandGrade {
 3188:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 3189:     my @version_parts;
 3190:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 3191: 					   $env{'request.course.id'});
 3192:     if (!&canmodify($usec)) { return('not_allowed'); }
 3193:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 3194:     my @parts_graded;
 3195:     my %newrecord  = ();
 3196:     my ($pts,$wgt,$totchg) = ('','',0);
 3197:     my %aggregate = ();
 3198:     my $aggregateflag = 0;
 3199:     if ($env{'form.HIDE'.$newflg}) {
 3200:         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
 3201:         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
 3202:         $totchg += $numchgs;
 3203:     }
 3204:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 3205:     foreach my $new_part (@parts) {
 3206: 	#collaborator ($submi may vary for different parts
 3207: 	if ($submitter && $new_part ne $part) { next; }
 3208: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 3209: 	if ($dropMenu eq 'excused') {
 3210: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 3211: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 3212: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 3213: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 3214: 		}
 3215: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3216: 	    }
 3217: 	} elsif ($dropMenu eq 'reset status'
 3218: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 3219: 	    foreach my $key (keys(%record)) {
 3220: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 3221: 	    }
 3222: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3223: 		"$env{'user.name'}:$env{'user.domain'}";
 3224:             my $totaltries = $record{'resource.'.$part.'.tries'};
 3225: 
 3226:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 3227: 					       [$new_part]);
 3228:             my $aggtries =$totaltries;
 3229:             if ($last_resets{$new_part}) {
 3230:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 3231: 					   $new_part);
 3232:             }
 3233: 
 3234:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 3235:             if ($aggtries > 0) {
 3236:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3237:                 $aggregateflag = 1;
 3238:             }
 3239: 	} elsif ($dropMenu eq '') {
 3240: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 3241: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 3242: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 3243: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 3244: 		next;
 3245: 	    }
 3246: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 3247: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 3248: 	    my $partial= $pts/$wgt;
 3249: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 3250: 		#do not update score for part if not changed.
 3251:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 3252: 		next;
 3253: 	    } else {
 3254: 	        push(@parts_graded,$new_part);
 3255: 	    }
 3256: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 3257: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 3258: 	    }
 3259: 	    my $reckey = 'resource.'.$new_part.'.solved';
 3260: 	    if ($partial == 0) {
 3261: 		if ($record{$reckey} ne 'incorrect_by_override') {
 3262: 		    $newrecord{$reckey} = 'incorrect_by_override';
 3263: 		}
 3264: 	    } else {
 3265: 		if ($record{$reckey} ne 'correct_by_override') {
 3266: 		    $newrecord{$reckey} = 'correct_by_override';
 3267: 		}
 3268: 	    }	    
 3269: 	    if ($submitter && 
 3270: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 3271: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 3272: 	    }
 3273: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3274: 		"$env{'user.name'}:$env{'user.domain'}";
 3275: 	}
 3276: 	# unless problem has been graded, set flag to version the submitted files
 3277: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 3278: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 3279: 	        $dropMenu eq 'reset status')
 3280: 	   {
 3281: 	    push(@version_parts,$new_part);
 3282: 	}
 3283:     }
 3284:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3285:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3286: 
 3287:     if (%newrecord) {
 3288:         if (@version_parts) {
 3289:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 3290:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 3291: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 3292: 	    foreach my $new_part (@version_parts) {
 3293: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 3294: 				$new_part,\%newrecord);
 3295: 	    }
 3296:         }
 3297: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 3298: 				$env{'request.course.id'},$domain,$stuname);
 3299: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 3300: 				     $cdom,$cnum,$domain,$stuname);
 3301:     }
 3302:     if ($aggregateflag) {
 3303:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3304: 			      $cdom,$cnum);
 3305:     }
 3306:     return ('',$pts,$wgt,$totchg);
 3307: }
 3308: 
 3309: sub makehidden {
 3310:     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
 3311:     return unless (ref($record) eq 'HASH');
 3312:     my %modified;
 3313:     my $numchanged = 0;
 3314:     if (exists($record->{$version.':keys'})) {
 3315:         my $partsregexp = $parts;
 3316:         $partsregexp =~ s/,/|/g;
 3317:         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
 3318:             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
 3319:                  my $item = $1;
 3320:                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
 3321:                      $modified{$key} = $record->{$version.':'.$key};
 3322:                  }
 3323:             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
 3324:                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
 3325:             } elsif ($key =~ /^(ip|timestamp|host)$/) {
 3326:                 $modified{$key} = $record->{$version.':'.$key};
 3327:             }
 3328:         }
 3329:         if (keys(%modified)) {
 3330:             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
 3331:                                           $domain,$stuname,$tolog) eq 'ok') {
 3332:                 $numchanged ++;
 3333:             }
 3334:         }
 3335:     }
 3336:     return $numchanged;
 3337: }
 3338: 
 3339: sub check_and_remove_from_queue {
 3340:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 3341:     my @ungraded_parts;
 3342:     foreach my $part (@{$parts}) {
 3343: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 3344: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 3345: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 3346: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 3347: 		) {
 3348: 	    push(@ungraded_parts, $part);
 3349: 	}
 3350:     }
 3351:     if ( !@ungraded_parts ) {
 3352: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 3353: 					       $cnum,$domain,$stuname);
 3354:     }
 3355: }
 3356: 
 3357: sub handback_files {
 3358:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 3359:     my $portfolio_root = '/userfiles/portfolio';
 3360:     my $res_error;
 3361:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3362:     if ($res_error) {
 3363:         $request->print('<br />'.&navmap_errormsg().'<br />');
 3364:         return;
 3365:     }
 3366:     my @handedback;
 3367:     my $file_msg;
 3368:     my @part_response_id = &flatten_responseType($responseType);
 3369:     foreach my $part_response_id (@part_response_id) {
 3370:     	my ($part_id,$resp_id) = @{ $part_response_id };
 3371: 	my $part_resp = join('_',@{ $part_response_id });
 3372:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
 3373:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
 3374:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
 3375:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
 3376:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
 3377:                     my ($directory,$answer_file) = 
 3378:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
 3379:                     my ($answer_name,$answer_ver,$answer_ext) =
 3380: 		        &Apache::lonnet::file_name_version_ext($answer_file);
 3381: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 3382:                     my $getpropath = 1;
 3383:                     my ($dir_list,$listerror) = 
 3384:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
 3385:                                                  $domain,$stuname,$getpropath);
 3386: 		    my $version = &Apache::lonnet::get_next_version($answer_name,$answer_ext,$dir_list);
 3387:                     # fix filename
 3388:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 3389:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 3390:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
 3391:             	                                $save_file_name);
 3392:                     if ($result !~ m|^/uploaded/|) {
 3393:                         $request->print('<br /><span class="LC_error">'.
 3394:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 3395:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
 3396:                                         '</span>');
 3397:                     } else {
 3398:                         # mark the file as read only
 3399:                         push(@handedback,$save_file_name);
 3400: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 3401: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 3402: 			}
 3403:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 3404: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
 3405:                     }
 3406:                     $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>'));
 3407:                 }
 3408:             }
 3409:         }
 3410:     }
 3411:     if (@handedback > 0) {
 3412:         $request->print('<br />');
 3413:         my @what = ($symb,$env{'request.course.id'},'handback');
 3414:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
 3415:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
 3416:         my ($subject,$message);
 3417:         if (scalar(@handedback) == 1) {
 3418:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
 3419:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
 3420:         } else {
 3421:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
 3422:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
 3423:         }
 3424:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
 3425:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
 3426:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
 3427:         my ($feedurl,$showsymb) =
 3428:             &get_feedurl_and_symb($symb,$domain,$stuname);
 3429:         my $restitle = &Apache::lonnet::gettitle($symb);
 3430:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
 3431:         my $msgstatus =
 3432:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
 3433:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
 3434:                  $restitle);
 3435:         if ($msgstatus) {
 3436:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
 3437:         }
 3438:     }
 3439:     return;
 3440: }
 3441: 
 3442: sub get_feedurl_and_symb {
 3443:     my ($symb,$uname,$udom) = @_;
 3444:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3445:     $url = &Apache::lonnet::clutter($url);
 3446:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 3447: 					$symb,$udom,$uname);
 3448:     if ($encrypturl =~ /^yes$/i) {
 3449: 	&Apache::lonenc::encrypted(\$url,1);
 3450: 	&Apache::lonenc::encrypted(\$symb,1);
 3451:     }
 3452:     return ($url,$symb);
 3453: }
 3454: 
 3455: sub get_submitted_files {
 3456:     my ($udom,$uname,$partid,$respid,$record) = @_;
 3457:     my @files;
 3458:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 3459:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 3460:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 3461:     	    push(@files,$file_url.$file);
 3462:         }
 3463:     }
 3464:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 3465:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 3466:     }
 3467:     return (\@files);
 3468: }
 3469: 
 3470: # ----------- Provides number of tries since last reset.
 3471: sub get_num_tries {
 3472:     my ($record,$last_reset,$part) = @_;
 3473:     my $timestamp = '';
 3474:     my $num_tries = 0;
 3475:     if ($$record{'version'}) {
 3476:         for (my $version=$$record{'version'};$version>=1;$version--) {
 3477:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 3478:                 $timestamp = $$record{$version.':timestamp'};
 3479:                 if ($timestamp > $last_reset) {
 3480:                     $num_tries ++;
 3481:                 } else {
 3482:                     last;
 3483:                 }
 3484:             }
 3485:         }
 3486:     }
 3487:     return $num_tries;
 3488: }
 3489: 
 3490: # ----------- Determine decrements required in aggregate totals 
 3491: sub decrement_aggs {
 3492:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 3493:     my %decrement = (
 3494:                         attempts => 0,
 3495:                         users => 0,
 3496:                         correct => 0
 3497:                     );
 3498:     $decrement{'attempts'} = $aggtries;
 3499:     if ($solvedstatus =~ /^correct/) {
 3500:         $decrement{'correct'} = 1;
 3501:     }
 3502:     if ($aggtries == $totaltries) {
 3503:         $decrement{'users'} = 1;
 3504:     }
 3505:     foreach my $type (keys(%decrement)) {
 3506:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 3507:     }
 3508:     return;
 3509: }
 3510: 
 3511: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3512: sub get_last_resets {
 3513:     my ($symb,$courseid,$partids) =@_;
 3514:     my %last_resets;
 3515:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3516:     my $cname = $env{'course.'.$courseid.'.num'};
 3517:     my @keys;
 3518:     foreach my $part (@{$partids}) {
 3519: 	push(@keys,"$symb\0$part\0resettime");
 3520:     }
 3521:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3522: 				     $cdom,$cname);
 3523:     foreach my $part (@{$partids}) {
 3524: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3525:     }
 3526:     return %last_resets;
 3527: }
 3528: 
 3529: # ----------- Handles creating versions for portfolio files as answers
 3530: sub version_portfiles {
 3531:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3532:     my $version_parts = join('|',@$v_flag);
 3533:     my @returned_keys;
 3534:     my $parts = join('|', @$parts_graded);
 3535:     foreach my $key (keys(%$record)) {
 3536:         my $new_portfiles;
 3537:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3538:             my @versioned_portfiles;
 3539:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3540:             if (@portfiles) {
 3541:                 &Apache::lonnet::portfiles_versioning($symb,$domain,$stu_name,\@portfiles,
 3542:                                                       \@versioned_portfiles);
 3543:             }
 3544:             $$record{$key} = join(',',@versioned_portfiles);
 3545:             push(@returned_keys,$key);
 3546:         }
 3547:     } 
 3548:     return (@returned_keys);   
 3549: }
 3550: 
 3551: #--------------------------------------------------------------------------------------
 3552: #
 3553: #-------------------------- Next few routines handles grading by section or whole class
 3554: #
 3555: #--- Javascript to handle grading by section or whole class
 3556: sub viewgrades_js {
 3557:     my ($request) = shift;
 3558: 
 3559:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3560:     &js_escape(\$alertmsg);
 3561:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
 3562:    function writePoint(partid,weight,point) {
 3563: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3564: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3565: 	if (point == "textval") {
 3566: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3567: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3568: 		alert("$alertmsg"+parseFloat(point));
 3569: 		var resetbox = false;
 3570: 		for (var i=0; i<radioButton.length; i++) {
 3571: 		    if (radioButton[i].checked) {
 3572: 			textbox.value = i;
 3573: 			resetbox = true;
 3574: 		    }
 3575: 		}
 3576: 		if (!resetbox) {
 3577: 		    textbox.value = "";
 3578: 		}
 3579: 		return;
 3580: 	    }
 3581: 	    if (parseFloat(point) > parseFloat(weight)) {
 3582: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3583: 				   ") greater than the weight for the part. Accept?");
 3584: 		if (resp == false) {
 3585: 		    textbox.value = "";
 3586: 		    return;
 3587: 		}
 3588: 	    }
 3589: 	    for (var i=0; i<radioButton.length; i++) {
 3590: 		radioButton[i].checked=false;
 3591: 		if (parseFloat(point) == i) {
 3592: 		    radioButton[i].checked=true;
 3593: 		}
 3594: 	    }
 3595: 
 3596: 	} else {
 3597: 	    textbox.value = parseFloat(point);
 3598: 	}
 3599: 	for (i=0;i<document.classgrade.total.value;i++) {
 3600: 	    var user = document.classgrade["ctr"+i].value;
 3601: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3602: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3603: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3604: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3605: 	    if (saveval != "correct") {
 3606: 		scorename.value = point;
 3607: 		if (selname[0].selected != true) {
 3608: 		    selname[0].selected = true;
 3609: 		}
 3610: 	    }
 3611: 	}
 3612: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3613:     }
 3614: 
 3615:     function writeRadText(partid,weight) {
 3616: 	var selval   = document.classgrade["SELVAL_"+partid];
 3617: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3618:         var override = document.classgrade["FORCE_"+partid].checked;
 3619: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3620: 	if (selval[1].selected || selval[2].selected) {
 3621: 	    for (var i=0; i<radioButton.length; i++) {
 3622: 		radioButton[i].checked=false;
 3623: 
 3624: 	    }
 3625: 	    textbox.value = "";
 3626: 
 3627: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3628: 		var user = document.classgrade["ctr"+i].value;
 3629: 		user = user.replace(new RegExp(':', 'g'),"_");
 3630: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3631: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3632: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3633: 		if ((saveval != "correct") || override) {
 3634: 		    scorename.value = "";
 3635: 		    if (selval[1].selected) {
 3636: 			selname[1].selected = true;
 3637: 		    } else {
 3638: 			selname[2].selected = true;
 3639: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3640: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3641: 		    }
 3642: 		}
 3643: 	    }
 3644: 	} else {
 3645: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3646: 		var user = document.classgrade["ctr"+i].value;
 3647: 		user = user.replace(new RegExp(':', 'g'),"_");
 3648: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3649: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3650: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3651: 		if ((saveval != "correct") || override) {
 3652: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3653: 		    selname[0].selected = true;
 3654: 		}
 3655: 	    }
 3656: 	}	    
 3657:     }
 3658: 
 3659:     function changeSelect(partid,user) {
 3660: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3661: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3662: 	var point  = textbox.value;
 3663: 	var weight = document.classgrade["weight_"+partid].value;
 3664: 
 3665: 	if (isNaN(point) || parseFloat(point) < 0) {
 3666: 	    alert("$alertmsg"+parseFloat(point));
 3667: 	    textbox.value = "";
 3668: 	    return;
 3669: 	}
 3670: 	if (parseFloat(point) > parseFloat(weight)) {
 3671: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3672: 			       ") greater than the weight of the part. Accept?");
 3673: 	    if (resp == false) {
 3674: 		textbox.value = "";
 3675: 		return;
 3676: 	    }
 3677: 	}
 3678: 	selval[0].selected = true;
 3679:     }
 3680: 
 3681:     function changeOneScore(partid,user) {
 3682: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3683: 	if (selval[1].selected || selval[2].selected) {
 3684: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3685: 	    if (selval[2].selected) {
 3686: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3687: 	    }
 3688:         }
 3689:     }
 3690: 
 3691:     function resetEntry(numpart) {
 3692: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3693: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3694: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3695: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3696: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3697: 	    for (var i=0; i<radioButton.length; i++) {
 3698: 		radioButton[i].checked=false;
 3699: 
 3700: 	    }
 3701: 	    textbox.value = "";
 3702: 	    selval[0].selected = true;
 3703: 
 3704: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3705: 		var user = document.classgrade["ctr"+i].value;
 3706: 		user = user.replace(new RegExp(':', 'g'),"_");
 3707: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3708: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3709: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3710: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3711: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3712: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3713: 		if (saveselval == "excused") {
 3714: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3715: 		} else {
 3716: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3717: 		}
 3718: 	    }
 3719: 	}
 3720:     }
 3721: 
 3722: VIEWJAVASCRIPT
 3723: }
 3724: 
 3725: #--- show scores for a section or whole class w/ option to change/update a score
 3726: sub viewgrades {
 3727:     my ($request,$symb) = @_;
 3728:     my ($is_tool,$toolsymb);
 3729:     if ($symb =~ /ext\.tool$/) {
 3730:         $is_tool = 1;
 3731:         $toolsymb = $symb;
 3732:     }
 3733:     &viewgrades_js($request);
 3734: 
 3735:     #need to make sure we have the correct data for later EXT calls, 
 3736:     #thus invalidate the cache
 3737:     &Apache::lonnet::devalidatecourseresdata(
 3738:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3739:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3740:     &Apache::lonnet::clear_EXT_cache_status();
 3741: 
 3742:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3743: 
 3744:     #view individual student submission form - called using Javascript viewOneStudent
 3745:     $result.=&jscriptNform($symb);
 3746: 
 3747:     #beginning of class grading form
 3748:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3749:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3750: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3751: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3752: 	&build_section_inputs().
 3753: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3754: 
 3755:     #retrieve selected groups
 3756:     my (@groups,$group_display);
 3757:     @groups = &Apache::loncommon::get_env_multiple('form.group');
 3758:     if (grep(/^all$/,@groups)) {
 3759:         @groups = ('all');
 3760:     } elsif (grep(/^none$/,@groups)) {
 3761:         @groups = ('none');
 3762:     } elsif (@groups > 0) {
 3763:         $group_display = join(', ',@groups);
 3764:     }
 3765: 
 3766:     my ($common_header,$specific_header,@sections,$section_display);
 3767:     @sections = &Apache::loncommon::get_env_multiple('form.section');
 3768:     if (grep(/^all$/,@sections)) {
 3769:         @sections = ('all');
 3770:         if ($group_display) {
 3771:             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
 3772:             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
 3773:         } elsif (grep(/^none$/,@groups)) {
 3774:             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
 3775:             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
 3776:         } else {
 3777: 	    $common_header = &mt('Assign Common Grade to Class');
 3778:             $specific_header = &mt('Assign Grade to Specific Students in Class');
 3779:         }
 3780:     } elsif (grep(/^none$/,@sections)) {
 3781:         @sections = ('none');
 3782:         if ($group_display) {
 3783:             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
 3784:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
 3785:         } elsif (grep(/^none$/,@groups)) {
 3786:             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
 3787:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
 3788:         } else {
 3789:             $common_header = &mt('Assign Common Grade to Students in no Section');
 3790: 	    $specific_header = &mt('Assign Grade to Specific Students in no Section');
 3791:         }
 3792:     } else {
 3793:         $section_display = join (", ",@sections);
 3794:         if ($group_display) {
 3795:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
 3796:                                  $section_display,$group_display);
 3797:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
 3798:                                    $section_display,$group_display);
 3799:         } elsif (grep(/^none$/,@groups)) {
 3800:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
 3801:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
 3802:         } else {
 3803:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3804: 	    $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3805:         }
 3806:     }
 3807:     my %submit_types = &substatus_options();
 3808:     my $submission_status = $submit_types{$env{'form.submitonly'}};
 3809: 
 3810:     if ($env{'form.submitonly'} eq 'all') {
 3811:         $result.= '<h3>'.$common_header.'</h3>';
 3812:     } else {
 3813:         my $text;
 3814:         if ($is_tool) {
 3815:             $text = &mt('(transaction status: "[_1]")',$submission_status);
 3816:         } else {
 3817:             $text = &mt('(submission status: "[_1]")',$submission_status);
 3818:         }
 3819:         $result.= '<h3>'.$common_header.'&nbsp;'.$text.'</h3>';
 3820:     }
 3821:     $result .= &Apache::loncommon::start_data_table();
 3822:     #radio buttons/text box for assigning points for a section or class.
 3823:     #handles different parts of a problem
 3824:     my $res_error;
 3825:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3826:     if ($res_error) {
 3827:         return &navmap_errormsg();
 3828:     }
 3829:     my %weight = ();
 3830:     my $ctsparts = 0;
 3831:     my %seen = ();
 3832:     my @part_response_id;
 3833:     if ($is_tool) {
 3834:         @part_response_id = ([0,'']);
 3835:     } else {
 3836:         @part_response_id = &flatten_responseType($responseType);
 3837:     }
 3838:     foreach my $part_response_id (@part_response_id) {
 3839:     	my ($partid,$respid) = @{ $part_response_id };
 3840: 	my $part_resp = join('_',@{ $part_response_id });
 3841: 	next if $seen{$partid};
 3842: 	$seen{$partid}++;
 3843: #	my $handgrade=$$handgrade{$part_resp};
 3844: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3845: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3846: 
 3847: 	my $display_part=&get_display_part($partid,$symb);
 3848: 	my $radio.='<table border="0"><tr>';  
 3849: 	my $ctr = 0;
 3850: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3851: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3852: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3853: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3854: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3855: 	    $ctr++;
 3856: 	}
 3857: 	$radio.='</tr></table>';
 3858: 	my $line = '<input type="text" name="TEXTVAL_'.
 3859: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 3860: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3861: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3862:         $line.= '<td><b>'.&mt('Grade Status').':</b>'.
 3863:             '<select name="SELVAL_'.$partid.'" '.
 3864:             'onchange="javascript:writeRadText(\''.$partid.'\','.
 3865:                 $weight{$partid}.')"> '.
 3866: 	    '<option selected="selected"> </option>'.
 3867: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3868: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3869: 	    '</select></td>'.
 3870:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3871: 	$line.='<input type="hidden" name="partid_'.
 3872: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3873: 	$line.='<input type="hidden" name="weight_'.
 3874: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3875: 
 3876: 	$result.=
 3877: 	    &Apache::loncommon::start_data_table_row()."\n".
 3878: 	    '<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>'.
 3879: 	    &Apache::loncommon::end_data_table_row()."\n";
 3880: 	$ctsparts++;
 3881:     }
 3882:     $result.=&Apache::loncommon::end_data_table()."\n".
 3883: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3884:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3885: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 3886: 
 3887:     #table listing all the students in a section/class
 3888:     #header of table
 3889:     if ($env{'form.submitonly'} eq 'all') {
 3890:         $result.= '<h3>'.$specific_header.'</h3>';
 3891:     } else {
 3892:         my $text;
 3893:         if ($is_tool) {
 3894:             $text = &mt('(transaction status: "[_1]")',$submission_status);
 3895:         } else {
 3896:             $text = &mt('(submission status: "[_1]")',$submission_status);
 3897:         }
 3898:         $result.= '<h3>'.$specific_header.'&nbsp;'.$text.'</h3>';
 3899:     }
 3900:     $result.= &Apache::loncommon::start_data_table().
 3901: 	      &Apache::loncommon::start_data_table_header_row().
 3902: 	      '<th>'.&mt('No.').'</th>'.
 3903: 	      '<th>'.&nameUserString('header')."</th>\n";
 3904:     my $partserror;
 3905:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3906:     if ($partserror) {
 3907:         return &navmap_errormsg();
 3908:     }
 3909:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3910:     my @partids = ();
 3911:     foreach my $part (@parts) {
 3912: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
 3913:         my $narrowtext = &mt('Tries');
 3914: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3915: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name',$toolsymb); }
 3916: 	my ($partid) = &split_part_type($part);
 3917:         push(@partids,$partid);
 3918: #
 3919: # FIXME: Looks like $display looks at English text
 3920: #
 3921: 	my $display_part=&get_display_part($partid,$symb);
 3922: 	if ($display =~ /^Partial Credit Factor/) {
 3923: 	    $result.='<th>'.
 3924: 		&mt('Score Part: [_1][_2](weight = [_3])',
 3925: 		    $display_part,'<br />',$weight{$partid}).'</th>'."\n";
 3926: 	    next;
 3927: 	    
 3928: 	} else {
 3929: 	    if ($display =~ /Problem Status/) {
 3930: 		my $grade_status_mt = &mt('Grade Status');
 3931: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3932: 	    }
 3933: 	    my $part_mt = &mt('Part:');
 3934: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3935: 	}
 3936: 
 3937: 	$result.='<th>'.$display.'</th>'."\n";
 3938:     }
 3939:     $result.=&Apache::loncommon::end_data_table_header_row();
 3940: 
 3941:     my %last_resets = 
 3942: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3943: 
 3944:     #get info for each student
 3945:     #list all the students - with points and grade status
 3946:     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
 3947:     my $ctr = 0;
 3948:     foreach (sort 
 3949: 	     {
 3950: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3951: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3952: 		 }
 3953: 		 return $a cmp $b;
 3954: 	     } (keys(%$fullname))) {
 3955: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3956: 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets,$is_tool);
 3957:     }
 3958:     $result.=&Apache::loncommon::end_data_table();
 3959:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3960:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3961: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 3962:     if ($ctr == 0) {
 3963:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3964:         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
 3965:                 '<span class="LC_warning">';
 3966:         if ($env{'form.submitonly'} eq 'all') {
 3967:             if (grep(/^all$/,@sections)) {
 3968:                 if (grep(/^all$/,@groups)) {
 3969:                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
 3970:                                    $stu_status);
 3971:                 } elsif (grep(/^none$/,@groups)) {
 3972:                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
 3973:                                    $stu_status); 
 3974:                 } else {
 3975:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
 3976:                                    $group_display,$stu_status);
 3977:                 }
 3978:             } elsif (grep(/^none$/,@sections)) {
 3979:                 if (grep(/^all$/,@groups)) {
 3980:                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
 3981:                                    $stu_status);
 3982:                 } elsif (grep(/^none$/,@groups)) {
 3983:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
 3984:                                    $stu_status);
 3985:                 } else {
 3986:                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
 3987:                                    $group_display,$stu_status);
 3988:                 }
 3989:             } else {
 3990:                 if (grep(/^all$/,@groups)) {
 3991:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3992:                                    $section_display,$stu_status);
 3993:                 } elsif (grep(/^none$/,@groups)) {
 3994:                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
 3995:                                    $section_display,$stu_status);
 3996:                 } else {
 3997:                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
 3998:                                    $section_display,$group_display,$stu_status);
 3999:                 }
 4000:             }
 4001:         } else {
 4002:             if (grep(/^all$/,@sections)) {
 4003:                 if (grep(/^all$/,@groups)) {
 4004:                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4005:                                    $stu_status,$submission_status);
 4006:                 } elsif (grep(/^none$/,@groups)) {
 4007:                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4008:                                    $stu_status,$submission_status);
 4009:                 } else {
 4010:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 4011:                                    $group_display,$stu_status,$submission_status);
 4012:                 }
 4013:             } elsif (grep(/^none$/,@sections)) {
 4014:                 if (grep(/^all$/,@groups)) {
 4015:                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4016:                                    $stu_status,$submission_status);
 4017:                 } elsif (grep(/^none$/,@groups)) {
 4018:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4019:                                    $stu_status,$submission_status);
 4020:                 } else {
 4021:                     $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.',
 4022:                                    $group_display,$stu_status,$submission_status);
 4023:                 }
 4024:             } else {
 4025:                 if (grep(/^all$/,@groups)) {
 4026: 	            $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 4027: 	                           $section_display,$stu_status,$submission_status);
 4028:                 } elsif (grep(/^none$/,@groups)) {
 4029:                     $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.',
 4030:                                    $section_display,$stu_status,$submission_status);
 4031:                 } else {
 4032:                     $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.',
 4033:                                    $section_display,$group_display,$stu_status,$submission_status);
 4034:                 }
 4035:             }
 4036:         }
 4037: 	$result .= '</span><br />';
 4038:     }
 4039:     return $result;
 4040: }
 4041: 
 4042: #--- call by previous routine to display each student who satisfies submission filter. 
 4043: sub viewstudentgrade {
 4044:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets,$is_tool) = @_;
 4045:     my ($uname,$udom) = split(/:/,$student);
 4046:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 4047:     my $submitonly = $env{'form.submitonly'};
 4048:     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
 4049:         my %partstatus = ();
 4050:         if (ref($parts) eq 'ARRAY') {
 4051:             foreach my $apart (@{$parts}) {
 4052:                 my ($part,$type) = &split_part_type($apart);
 4053:                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
 4054:                 $status = 'nothing' if ($status eq '');
 4055:                 $partstatus{$part}      = $status;
 4056:                 my $subkey = "resource.$part.submitted_by";
 4057:                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
 4058:             }
 4059:             my $submitted = 0;
 4060:             my $graded = 0;
 4061:             my $incorrect = 0;
 4062:             foreach my $key (keys(%partstatus)) {
 4063:                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
 4064:                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
 4065:                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
 4066: 
 4067:                 my $partid = (split(/\./,$key))[1];
 4068:                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
 4069:                     $submitted = 0;
 4070:                 }
 4071:             }
 4072:             return if (!$submitted && ($submitonly eq 'yes' ||
 4073:                                        $submitonly eq 'incorrect' ||
 4074:                                        $submitonly eq 'graded'));
 4075:             return if (!$graded && ($submitonly eq 'graded'));
 4076:             return if (!$incorrect && $submitonly eq 'incorrect');
 4077:         }
 4078:     }
 4079:     if ($submitonly eq 'queued') {
 4080:         my ($cdom,$cnum) = split(/_/,$courseid);
 4081:         my %queue_status =
 4082:             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 4083:                                                     $udom,$uname);
 4084:         return if (!defined($queue_status{'gradingqueue'}));
 4085:     }
 4086:     $$ctr++;
 4087:     my %aggregates = ();
 4088:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 4089: 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
 4090: 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
 4091: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 4092: 	'\');" target="_self">'.$fullname.'</a> '.
 4093: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 4094:     $student=~s/:/_/; # colon doen't work in javascript for names
 4095:     foreach my $apart (@$parts) {
 4096: 	my ($part,$type) = &split_part_type($apart);
 4097: 	my $score=$record{"resource.$part.$type"};
 4098:         $result.='<td align="center">';
 4099:         my ($aggtries,$totaltries);
 4100:         unless (exists($aggregates{$part})) {
 4101: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 4102: 	    $aggtries = $totaltries;
 4103:             if ($$last_resets{$part}) {  
 4104:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 4105: 					   $part);
 4106:             }
 4107:             $result.='<input type="hidden" name="'.
 4108:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 4109:             $result.='<input type="hidden" name="'.
 4110:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 4111:             $aggregates{$part} = 1;
 4112:         }
 4113: 	if ($type eq 'awarded') {
 4114: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 4115: 	    $result.='<input type="hidden" name="'.
 4116: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 4117: 	    $result.='<input type="text" name="'.
 4118: 		'GD_'.$student.'_'.$part.'_awarded" '.
 4119:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 4120: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 4121: 	} elsif ($type eq 'solved') {
 4122: 	    my ($status,$foo)=split(/_/,$score,2);
 4123: 	    $status = 'nothing' if ($status eq '');
 4124: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 4125: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 4126: 	    $result.='&nbsp;<select name="'.
 4127: 		'GD_'.$student.'_'.$part.'_solved" '.
 4128:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 4129: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 4130: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 4131: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 4132: 	    $result.="</select>&nbsp;</td>\n";
 4133: 	} else {
 4134: 	    $result.='<input type="hidden" name="'.
 4135: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 4136: 		    "\n";
 4137: 	    $result.='<input type="text" name="'.
 4138: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 4139: 		'value="'.$score.'" size="4" /></td>'."\n";
 4140: 	}
 4141:     }
 4142:     $result.=&Apache::loncommon::end_data_table_row();
 4143:     return $result;
 4144: }
 4145: 
 4146: #--- change scores for all the students in a section/class
 4147: #    record does not get update if unchanged
 4148: sub editgrades {
 4149:     my ($request,$symb) = @_;
 4150:     my $toolsymb;
 4151:     if ($symb =~ /ext\.tool$/) {
 4152:         $toolsymb = $symb;
 4153:     }
 4154: 
 4155:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 4156:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 4157:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 4158: 
 4159:     my $result= &Apache::loncommon::start_data_table().
 4160: 	&Apache::loncommon::start_data_table_header_row().
 4161: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 4162: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 4163:     my %scoreptr = (
 4164: 		    'correct'  =>'correct_by_override',
 4165: 		    'incorrect'=>'incorrect_by_override',
 4166: 		    'excused'  =>'excused',
 4167: 		    'ungraded' =>'ungraded_attempted',
 4168:                     'credited' =>'credit_attempted',
 4169: 		    'nothing'  => '',
 4170: 		    );
 4171:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 4172: 
 4173:     my (@partid);
 4174:     my %weight = ();
 4175:     my %columns = ();
 4176:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 4177: 
 4178:     my $partserror;
 4179:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 4180:     if ($partserror) {
 4181:         return &navmap_errormsg();
 4182:     }
 4183:     my $header;
 4184:     while ($ctr < $env{'form.totalparts'}) {
 4185: 	my $partid = $env{'form.partid_'.$ctr};
 4186: 	push(@partid,$partid);
 4187: 	$weight{$partid} = $env{'form.weight_'.$partid};
 4188: 	$ctr++;
 4189:     }
 4190:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4191:     my $totcolspan = 0;
 4192:     foreach my $partid (@partid) {
 4193: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 4194: 	    '<th align="center">'.&mt('New Score').'</th>';
 4195: 	$columns{$partid}=2;
 4196: 	foreach my $stores (@parts) {
 4197: 	    my ($part,$type) = &split_part_type($stores);
 4198: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 4199: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 4200: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display',$toolsymb);
 4201: 	    $display =~ s/\[Part: \Q$part\E\]//;
 4202:             my $narrowtext = &mt('Tries');
 4203: 	    $display =~ s/Number of Attempts/$narrowtext/;
 4204: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 4205: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 4206: 	    $columns{$partid}+=2;
 4207: 	}
 4208:         $totcolspan += $columns{$partid};
 4209:     }
 4210:     foreach my $partid (@partid) {
 4211: 	my $display_part=&get_display_part($partid,$symb);
 4212: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 4213: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 4214: 	    '</th>';
 4215: 
 4216:     }
 4217:     $result .= &Apache::loncommon::end_data_table_header_row().
 4218: 	&Apache::loncommon::start_data_table_header_row().
 4219: 	$header.
 4220: 	&Apache::loncommon::end_data_table_header_row();
 4221:     my @noupdate;
 4222:     my ($updateCtr,$noupdateCtr) = (1,1);
 4223:     for ($i=0; $i<$env{'form.total'}; $i++) {
 4224: 	my $user = $env{'form.ctr'.$i};
 4225: 	my ($uname,$udom)=split(/:/,$user);
 4226: 	my %newrecord;
 4227: 	my $updateflag = 0;
 4228: 	my $usec=$classlist->{"$uname:$udom"}[5];
 4229: 	my $canmodify = &canmodify($usec);
 4230: 	my $line = '<td'.($canmodify?'':' colspan="2"').'>'.
 4231: 		   &nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 4232: 	if (!$canmodify) {
 4233: 	    push(@noupdate,
 4234: 		 $line."<td colspan=\"$totcolspan\"><span class=\"LC_warning\">".
 4235: 		 &mt('Not allowed to modify student')."</span></td>");
 4236: 	    next;
 4237: 	}
 4238:         my %aggregate = ();
 4239:         my $aggregateflag = 0;
 4240: 	$user=~s/:/_/; # colon doen't work in javascript for names
 4241: 	foreach (@partid) {
 4242: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 4243: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 4244: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 4245: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 4246: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 4247: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 4248: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 4249: 	    my $score;
 4250: 	    if ($partial eq '') {
 4251: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 4252: 	    } elsif ($partial > 0) {
 4253: 		$score = 'correct_by_override';
 4254: 	    } elsif ($partial == 0) {
 4255: 		$score = 'incorrect_by_override';
 4256: 	    }
 4257: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 4258: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 4259: 
 4260: 	    $newrecord{'resource.'.$_.'.regrader'}=
 4261: 		"$env{'user.name'}:$env{'user.domain'}";
 4262: 	    if ($dropMenu eq 'reset status' &&
 4263: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 4264: 		$newrecord{'resource.'.$_.'.tries'} = '';
 4265: 		$newrecord{'resource.'.$_.'.solved'} = '';
 4266: 		$newrecord{'resource.'.$_.'.award'} = '';
 4267: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 4268: 		$updateflag = 1;
 4269:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 4270:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 4271:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 4272:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 4273:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4274:                     $aggregateflag = 1;
 4275:                 }
 4276: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 4277: 		$updateflag = 1;
 4278: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 4279: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 4280: 		$rec_update++;
 4281: 	    }
 4282: 
 4283: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4284: 		'<td align="center">'.$awarded.
 4285: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 4286: 
 4287: 
 4288: 	    my $partid=$_;
 4289: 	    foreach my $stores (@parts) {
 4290: 		my ($part,$type) = &split_part_type($stores);
 4291: 		if ($part !~ m/^\Q$partid\E/) { next;}
 4292: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 4293: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 4294: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 4295: 		if ($awarded ne '' && $awarded ne $old_aw) {
 4296: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 4297: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 4298: 		    $updateflag=1;
 4299: 		}
 4300: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4301: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 4302: 	    }
 4303: 	}
 4304: 	$line.="\n";
 4305: 
 4306: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4307: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4308: 
 4309: 	if ($updateflag) {
 4310: 	    $count++;
 4311: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 4312: 				    $udom,$uname);
 4313: 
 4314: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 4315: 					      $cnum,$udom,$uname)) {
 4316: 		# need to figure out if should be in queue.
 4317: 		my %record =  
 4318: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 4319: 					     $udom,$uname);
 4320: 		my $all_graded = 1;
 4321: 		my $none_graded = 1;
 4322: 		foreach my $part (@parts) {
 4323: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 4324: 			$all_graded = 0;
 4325: 		    } else {
 4326: 			$none_graded = 0;
 4327: 		    }
 4328: 		}
 4329: 
 4330: 		if ($all_graded || $none_graded) {
 4331: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 4332: 							   $symb,$cdom,$cnum,
 4333: 							   $udom,$uname);
 4334: 		}
 4335: 	    }
 4336: 
 4337: 	    $result.=&Apache::loncommon::start_data_table_row().
 4338: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 4339: 		&Apache::loncommon::end_data_table_row();
 4340: 	    $updateCtr++;
 4341: 	} else {
 4342: 	    push(@noupdate,
 4343: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 4344: 	    $noupdateCtr++;
 4345: 	}
 4346:         if ($aggregateflag) {
 4347:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4348: 				  $cdom,$cnum);
 4349:         }
 4350:     }
 4351:     if (@noupdate) {
 4352:         my $numcols=$totcolspan+2;
 4353: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 4354: 	    '<td align="center" colspan="'.$numcols.'">'.
 4355: 	    &mt('No Changes Occurred For the Students Below').
 4356: 	    '</td>'.
 4357: 	    &Apache::loncommon::end_data_table_row();
 4358: 	foreach my $line (@noupdate) {
 4359: 	    $result.=
 4360: 		&Apache::loncommon::start_data_table_row().
 4361: 		$line.
 4362: 		&Apache::loncommon::end_data_table_row();
 4363: 	}
 4364:     }
 4365:     $result .= &Apache::loncommon::end_data_table();
 4366:     my $msg = '<p><b>'.
 4367: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 4368: 	    $rec_update,$count).'</b><br />'.
 4369: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 4370: 	'</b></p>';
 4371:     return $title.$msg.$result;
 4372: }
 4373: 
 4374: sub split_part_type {
 4375:     my ($partstr) = @_;
 4376:     my ($temp,@allparts)=split(/_/,$partstr);
 4377:     my $type=pop(@allparts);
 4378:     my $part=join('_',@allparts);
 4379:     return ($part,$type);
 4380: }
 4381: 
 4382: #------------- end of section for handling grading by section/class ---------
 4383: #
 4384: #----------------------------------------------------------------------------
 4385: 
 4386: 
 4387: #----------------------------------------------------------------------------
 4388: #
 4389: #-------------------------- Next few routines handles grading by csv upload
 4390: #
 4391: #--- Javascript to handle csv upload
 4392: sub csvupload_javascript_reverse_associate {
 4393:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
 4394:     my $error2=&mt('You need to specify at least one grading field');
 4395:   &js_escape(\$error1);
 4396:   &js_escape(\$error2);
 4397:   return(<<ENDPICK);
 4398:   function verify(vf) {
 4399:     var foundsomething=0;
 4400:     var founduname=0;
 4401:     var foundID=0;
 4402:     var foundclicker=0;
 4403:     for (i=0;i<=vf.nfields.value;i++) {
 4404:       tw=eval('vf.f'+i+'.selectedIndex');
 4405:       if (i==0 && tw!=0) { foundID=1; }
 4406:       if (i==1 && tw!=0) { founduname=1; }
 4407:       if (i==2 && tw!=0) { foundclicker=1; }
 4408:       if (i!=0 && i!=1 && i!=2 && i!=3 && tw!=0) { foundsomething=1; }
 4409:     }
 4410:     if (founduname==0 && foundID==0 && foundclicker==0) {
 4411: 	alert('$error1');
 4412: 	return;
 4413:     }
 4414:     if (foundsomething==0) {
 4415: 	alert('$error2');
 4416: 	return;
 4417:     }
 4418:     vf.submit();
 4419:   }
 4420:   function flip(vf,tf) {
 4421:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4422:     var i;
 4423:     for (i=0;i<=vf.nfields.value;i++) {
 4424:       //can not pick the same destination field for both name and domain
 4425:       if (((i ==0)||(i ==1)) && 
 4426:           ((tf==0)||(tf==1)) && 
 4427:           (i!=tf) &&
 4428:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4429:         eval('vf.f'+i+'.selectedIndex=0;')
 4430:       }
 4431:     }
 4432:   }
 4433: ENDPICK
 4434: }
 4435: 
 4436: sub csvupload_javascript_forward_associate {
 4437:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
 4438:     my $error2=&mt('You need to specify at least one grading field');
 4439:   &js_escape(\$error1);
 4440:   &js_escape(\$error2);
 4441:   return(<<ENDPICK);
 4442:   function verify(vf) {
 4443:     var foundsomething=0;
 4444:     var founduname=0;
 4445:     var foundID=0;
 4446:     var foundclicker=0;
 4447:     for (i=0;i<=vf.nfields.value;i++) {
 4448:       tw=eval('vf.f'+i+'.selectedIndex');
 4449:       if (tw==1) { foundID=1; }
 4450:       if (tw==2) { founduname=1; }
 4451:       if (tw==3) { foundclicker=1; }
 4452:       if (tw>4) { foundsomething=1; }
 4453:     }
 4454:     if (founduname==0 && foundID==0 && Æ’oundclicker==0) {
 4455: 	alert('$error1');
 4456: 	return;
 4457:     }
 4458:     if (foundsomething==0) {
 4459: 	alert('$error2');
 4460: 	return;
 4461:     }
 4462:     vf.submit();
 4463:   }
 4464:   function flip(vf,tf) {
 4465:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4466:     var i;
 4467:     //can not pick the same destination field twice
 4468:     for (i=0;i<=vf.nfields.value;i++) {
 4469:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4470:         eval('vf.f'+i+'.selectedIndex=0;')
 4471:       }
 4472:     }
 4473:   }
 4474: ENDPICK
 4475: }
 4476: 
 4477: sub csvuploadmap_header {
 4478:     my ($request,$symb,$datatoken,$distotal)= @_;
 4479:     my $javascript;
 4480:     if ($env{'form.upfile_associate'} eq 'reverse') {
 4481: 	$javascript=&csvupload_javascript_reverse_associate();
 4482:     } else {
 4483: 	$javascript=&csvupload_javascript_forward_associate();
 4484:     }
 4485: 
 4486:     $symb = &Apache::lonenc::check_encrypt($symb);
 4487:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
 4488:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
 4489:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
 4490:     my $reverse=&mt("Reverse Association");
 4491:     $request->print(<<ENDPICK);
 4492: <br />
 4493: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 4494: <input type="hidden" name="associate"  value="" />
 4495: <input type="hidden" name="phase"      value="three" />
 4496: <input type="hidden" name="datatoken"  value="$datatoken" />
 4497: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 4498: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 4499: <input type="hidden" name="upfile_associate" 
 4500:                                        value="$env{'form.upfile_associate'}" />
 4501: <input type="hidden" name="symb"       value="$symb" />
 4502: <input type="hidden" name="command"    value="csvuploadoptions" />
 4503: <hr />
 4504: ENDPICK
 4505:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
 4506:     return '';
 4507: 
 4508: }
 4509: 
 4510: sub csvupload_fields {
 4511:     my ($symb,$errorref) = @_;
 4512:     my $toolsymb;
 4513:     if ($symb =~ /ext\.tool$/) {
 4514:         $toolsymb = $symb;
 4515:     }
 4516:     my (@parts) = &getpartlist($symb,$errorref);
 4517:     if (ref($errorref)) {
 4518:         if ($$errorref) {
 4519:             return;
 4520:         }
 4521:     }
 4522: 
 4523:     my @fields=(['ID','Student/Employee ID'],
 4524: 		['username','Student Username'],
 4525: 		['clicker','Clicker ID'],
 4526: 		['domain','Student Domain']);
 4527:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4528:     foreach my $part (sort(@parts)) {
 4529: 	my @datum;
 4530: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
 4531: 	my $name=$part;
 4532: 	if (!$display) { $display = $name; }
 4533: 	@datum=($name,$display);
 4534: 	if ($name=~/^stores_(.*)_awarded/) {
 4535: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 4536: 	}
 4537: 	push(@fields,\@datum);
 4538:     }
 4539:     return (@fields);
 4540: }
 4541: 
 4542: sub csvuploadmap_footer {
 4543:     my ($request,$i,$keyfields) =@_;
 4544:     my $buttontext = &mt('Assign Grades');
 4545:     $request->print(<<ENDPICK);
 4546: </table>
 4547: <input type="hidden" name="nfields" value="$i" />
 4548: <input type="hidden" name="keyfields" value="$keyfields" />
 4549: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
 4550: </form>
 4551: ENDPICK
 4552: }
 4553: 
 4554: sub checkforfile_js {
 4555:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 4556:     &js_escape(\$alertmsg);
 4557:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
 4558:     function checkUpload(formname) {
 4559: 	if (formname.upfile.value == "") {
 4560: 	    alert("$alertmsg");
 4561: 	    return false;
 4562: 	}
 4563: 	formname.submit();
 4564:     }
 4565: CSVFORMJS
 4566:     return $result;
 4567: }
 4568: 
 4569: sub upcsvScores_form {
 4570:     my ($request,$symb) = @_;
 4571:     if (!$symb) {return '';}
 4572:     my $result=&checkforfile_js();
 4573:     $result.=&Apache::loncommon::start_data_table().
 4574:              &Apache::loncommon::start_data_table_header_row().
 4575:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
 4576:              &Apache::loncommon::end_data_table_header_row().
 4577:              &Apache::loncommon::start_data_table_row().'<td>';
 4578:     my $upload=&mt("Upload Scores");
 4579:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 4580:     my $ignore=&mt('Ignore First Line');
 4581:     $symb = &Apache::lonenc::check_encrypt($symb);
 4582:     $result.=<<ENDUPFORM;
 4583: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4584: <input type="hidden" name="symb" value="$symb" />
 4585: <input type="hidden" name="command" value="csvuploadmap" />
 4586: $upfile_select
 4587: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 4588: </form>
 4589: ENDUPFORM
 4590:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 4591:                            &mt("How do I create a CSV file from a spreadsheet")).
 4592:              '</td>'.
 4593:             &Apache::loncommon::end_data_table_row().
 4594:             &Apache::loncommon::end_data_table();
 4595:     return $result;
 4596: }
 4597: 
 4598: 
 4599: sub csvuploadmap {
 4600:     my ($request,$symb)= @_;
 4601:     if (!$symb) {return '';}
 4602: 
 4603:     my $datatoken;
 4604:     if (!$env{'form.datatoken'}) {
 4605: 	$datatoken=&Apache::loncommon::upfile_store($request);
 4606:     } else {
 4607: 	$datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
 4608:         if ($datatoken ne '') {
 4609: 	    &Apache::loncommon::load_tmp_file($request,$datatoken);
 4610:         }
 4611:     }
 4612:     my @records=&Apache::loncommon::upfile_record_sep();
 4613:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 4614:     my ($i,$keyfields);
 4615:     if (@records) {
 4616:         my $fieldserror;
 4617: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 4618:         if ($fieldserror) {
 4619:             $request->print(&navmap_errormsg());
 4620:             return;
 4621:         }
 4622: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 4623: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 4624: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 4625: 							  \@fields);
 4626: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 4627: 	    chop($keyfields);
 4628: 	} else {
 4629: 	    unshift(@fields,['none','']);
 4630: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 4631: 							    \@fields);
 4632:             foreach my $rec (@records) {
 4633:                 my %temp = &Apache::loncommon::record_sep($rec);
 4634:                 if (%temp) {
 4635:                     $keyfields=join(',',sort(keys(%temp)));
 4636:                     last;
 4637:                 }
 4638:             }
 4639: 	}
 4640:     }
 4641:     &csvuploadmap_footer($request,$i,$keyfields);
 4642: 
 4643:     return '';
 4644: }
 4645: 
 4646: sub csvuploadoptions {
 4647:     my ($request,$symb)= @_;
 4648:     my $overwrite=&mt('Overwrite any existing score');
 4649:     $request->print(<<ENDPICK);
 4650: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4651: <input type="hidden" name="command"    value="csvuploadassign" />
 4652: <p>
 4653: <label>
 4654:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4655:    $overwrite
 4656: </label>
 4657: </p>
 4658: ENDPICK
 4659:     my %fields=&get_fields();
 4660:     if (!defined($fields{'domain'})) {
 4661: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4662: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
 4663:     }
 4664:     foreach my $key (sort(keys(%env))) {
 4665: 	if ($key !~ /^form\.(.*)$/) { next; }
 4666: 	my $cleankey=$1;
 4667: 	if ($cleankey eq 'command') { next; }
 4668: 	$request->print('<input type="hidden" name="'.$cleankey.
 4669: 			'"  value="'.$env{$key}.'" />'."\n");
 4670:     }
 4671:     # FIXME do a check for any duplicated user ids...
 4672:     # FIXME do a check for any invalid user ids?...
 4673:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
 4674: <hr /></form>'."\n");
 4675:     return '';
 4676: }
 4677: 
 4678: sub get_fields {
 4679:     my %fields;
 4680:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4681:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4682: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4683: 	    if ($env{'form.f'.$i} ne 'none') {
 4684: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4685: 	    }
 4686: 	} else {
 4687: 	    if ($env{'form.f'.$i} ne 'none') {
 4688: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4689: 	    }
 4690: 	}
 4691:     }
 4692:     return %fields;
 4693: }
 4694: 
 4695: sub csvuploadassign {
 4696:     my ($request,$symb)= @_;
 4697:     if (!$symb) {return '';}
 4698:     my $error_msg = '';
 4699:     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
 4700:     if ($datatoken ne '') { 
 4701:         &Apache::loncommon::load_tmp_file($request,$datatoken);
 4702:     }
 4703:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4704:     my %fields=&get_fields();
 4705:     my $courseid=$env{'request.course.id'};
 4706:     my ($classlist) = &getclasslist('all',0);
 4707:     my @notallowed;
 4708:     my @skipped;
 4709:     my @warnings;
 4710:     my $countdone=0;
 4711:     foreach my $grade (@gradedata) {
 4712: 	my %entries=&Apache::loncommon::record_sep($grade);
 4713: 	my $domain;
 4714: 	if ($entries{$fields{'domain'}}) {
 4715: 	    $domain=$entries{$fields{'domain'}};
 4716: 	} else {
 4717: 	    $domain=$env{'form.default_domain'};
 4718: 	}
 4719: 	$domain=~s/\s//g;
 4720: 	my $username=$entries{$fields{'username'}};
 4721: 	$username=~s/\s//g;
 4722: 	if (!$username) {
 4723: 	    my $id=$entries{$fields{'ID'}};
 4724: 	    $id=~s/\s//g;
 4725:             if ($id ne '') {
 4726: 	        my %ids=&Apache::lonnet::idget($domain,[$id]);
 4727: 	        $username=$ids{$id};
 4728:             } else {
 4729:                 if ($entries{$fields{'clicker'}}) {
 4730:                     my $clicker = $entries{$fields{'clicker'}};
 4731:                     $clicker=~s/\s//g;
 4732:                     if ($clicker ne '') {
 4733:                         my %clickers = &Apache::lonnet::idget($domain,[$clicker],'clickers');
 4734:                         if ($clickers{$clicker} ne '') {  
 4735:                             my $match = 0;
 4736:                             my @inclass;
 4737:                             foreach my $poss (split(/,/,$clickers{$clicker})) {
 4738:                                 if (exists($$classlist{"$poss:$domain"})) {
 4739:                                     $username = $poss;
 4740:                                     push(@inclass,$poss);
 4741:                                     $match ++;
 4742:                                     
 4743:                                 }
 4744:                             }
 4745:                             if ($match > 1) {
 4746:                                 undef($username); 
 4747:                                 $request->print('<p class="LC_warning">'.
 4748:                                                 &mt('Score not saved for clicker: [_1] (matched multiple usernames: [_2])',
 4749:                                                 $clicker,join(', ',@inclass)).'</p>');
 4750:                             }
 4751:                         }
 4752:                     }
 4753:                 }
 4754:             }
 4755: 	}
 4756: 	if (!exists($$classlist{"$username:$domain"})) {
 4757: 	    my $id=$entries{$fields{'ID'}};
 4758: 	    $id=~s/\s//g;
 4759:             my $clicker = $entries{$fields{'clicker'}};
 4760:             $clicker=~s/\s//g;
 4761:             if ($clicker) {
 4762:                 push(@skipped,"$clicker:$domain");
 4763: 	    } elsif ($id) {
 4764: 		push(@skipped,"$id:$domain");
 4765: 	    } else {
 4766: 		push(@skipped,"$username:$domain");
 4767: 	    }
 4768: 	    next;
 4769: 	}
 4770: 	my $usec=$classlist->{"$username:$domain"}[5];
 4771: 	if (!&canmodify($usec)) {
 4772: 	    push(@notallowed,"$username:$domain");
 4773: 	    next;
 4774: 	}
 4775: 	my %points;
 4776: 	my %grades;
 4777: 	foreach my $dest (keys(%fields)) {
 4778: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4779: 		$dest eq 'domain') { next; }
 4780: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4781: 	    if ($dest=~/stores_(.*)_points/) {
 4782: 		my $part=$1;
 4783: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4784: 					      $symb,$domain,$username);
 4785:                 if ($wgt) {
 4786:                     $entries{$fields{$dest}}=~s/\s//g;
 4787:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4788:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4789:                                           : 'correct_by_override';
 4790:                     if ($pcr>1) {
 4791:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
 4792:                     }
 4793:                     $grades{"resource.$part.awarded"}=$pcr;
 4794:                     $grades{"resource.$part.solved"}=$award;
 4795:                     $points{$part}=1;
 4796:                 } else {
 4797:                     $error_msg = "<br />" .
 4798:                         &mt("Some point values were assigned"
 4799:                             ." for problems with a weight "
 4800:                             ."of zero. These values were "
 4801:                             ."ignored.");
 4802:                 }
 4803: 	    } else {
 4804: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4805: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4806: 		my $store_key=$dest;
 4807: 		$store_key=~s/^stores/resource/;
 4808: 		$store_key=~s/_/\./g;
 4809: 		$grades{$store_key}=$entries{$fields{$dest}};
 4810: 	    }
 4811: 	}
 4812: 	if (! %grades) { 
 4813:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4814:         } else {
 4815: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4816: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4817: 					   $env{'request.course.id'},
 4818: 					   $domain,$username);
 4819: 	   if ($result eq 'ok') {
 4820: # Successfully stored
 4821: 	      $request->print('.');
 4822: # Remove from grading queue
 4823:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
 4824:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
 4825:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
 4826:                                              $domain,$username);
 4827:               $countdone++;
 4828:            } else {
 4829: 	      $request->print("<p><span class=\"LC_error\">".
 4830:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4831:                                   "$username:$domain",$result)."</span></p>");
 4832: 	   }
 4833: 	   $request->rflush();
 4834:         }
 4835:     }
 4836:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 4837:     if (@warnings) {
 4838:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
 4839:         $request->print(join(', ',@warnings));
 4840:     }
 4841:     if (@skipped) {
 4842: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 4843:         $request->print(join(', ',@skipped));
 4844:     }
 4845:     if (@notallowed) {
 4846: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 4847: 	$request->print(join(', ',@notallowed));
 4848:     }
 4849:     $request->print("<br />\n");
 4850:     return $error_msg;
 4851: }
 4852: #------------- end of section for handling csv file upload ---------
 4853: #
 4854: #-------------------------------------------------------------------
 4855: #
 4856: #-------------- Next few routines handle grading by page/sequence
 4857: #
 4858: #--- Select a page/sequence and a student to grade
 4859: sub pickStudentPage {
 4860:     my ($request,$symb) = @_;
 4861: 
 4862:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4863:     &js_escape(\$alertmsg);
 4864:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
 4865: 
 4866: function checkPickOne(formname) {
 4867:     if (radioSelection(formname.student) == null) {
 4868: 	alert("$alertmsg");
 4869: 	return;
 4870:     }
 4871:     ptr = pullDownSelection(formname.selectpage);
 4872:     formname.page.value = formname["page"+ptr].value;
 4873:     formname.title.value = formname["title"+ptr].value;
 4874:     formname.submit();
 4875: }
 4876: 
 4877: LISTJAVASCRIPT
 4878:     &commonJSfunctions($request);
 4879: 
 4880:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4881:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4882:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4883: 
 4884:     my $result='<h3><span class="LC_info">&nbsp;'.
 4885: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4886: 
 4887:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4888:     my $map_error;
 4889:     my ($titles,$symbx) = &getSymbMap($map_error);
 4890:     if ($map_error) {
 4891:         $request->print(&navmap_errormsg());
 4892:         return; 
 4893:     }
 4894:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4895: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4896: #    my $type=($curpage =~ /\.(page|sequence)/);
 4897: 
 4898:     # Collection of hidden fields
 4899:     my $ctr=0;
 4900:     foreach (@$titles) {
 4901:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4902:         $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4903:         $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4904:         $ctr++;
 4905:     }
 4906:     $result.='<input type="hidden" name="page" />'."\n".
 4907:         '<input type="hidden" name="title" />'."\n";
 4908: 
 4909:     $result.=&build_section_inputs();
 4910:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4911:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4912: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4913: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 4914: 
 4915:     # Show grading options
 4916:     $result.=&Apache::lonhtmlcommon::start_pick_box();
 4917:     my $select = '<select name="selectpage">'."\n";
 4918:     $ctr=0;
 4919:     foreach (@$titles) {
 4920: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4921: 	$select.='<option value="'.$ctr.'"'.
 4922: 	    ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
 4923: 	    '>'.$showtitle.'</option>'."\n";
 4924: 	$ctr++;
 4925:     }
 4926:     $select.= '</select>';
 4927: 
 4928:     $result.=
 4929:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
 4930:        .$select
 4931:        .&Apache::lonhtmlcommon::row_closure();
 4932: 
 4933:     $result.=
 4934:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
 4935:        .'<label><input type="radio" name="vProb" value="no"'
 4936:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
 4937:        .'<label><input type="radio" name="vProb" value="yes" />'
 4938:            .&mt('yes').'</label>'."\n"
 4939:        .&Apache::lonhtmlcommon::row_closure();
 4940: 
 4941:     $result.=
 4942:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
 4943:        .'<label><input type="radio" name="lastSub" value="none" /> '
 4944:            .&mt('none').' </label>'."\n"
 4945:        .'<label><input type="radio" name="lastSub" value="datesub"'
 4946:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
 4947:        .'<label><input type="radio" name="lastSub" value="all" /> '
 4948:            .&mt('all submissions with details').' </label>'
 4949:        .&Apache::lonhtmlcommon::row_closure();
 4950:     
 4951:     $result.=
 4952:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
 4953:        .'<input type="text" name="CODE" value="" />'
 4954:        .&Apache::lonhtmlcommon::row_closure(1)
 4955:        .&Apache::lonhtmlcommon::end_pick_box();
 4956: 
 4957:     # Show list of students to select for grading
 4958:     $result.='<br /><input type="button" '.
 4959:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4960: 
 4961:     $request->print($result);
 4962: 
 4963:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4964: 	&Apache::loncommon::start_data_table().
 4965: 	&Apache::loncommon::start_data_table_header_row().
 4966: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4967: 	'<th>'.&nameUserString('header').'</th>'.
 4968: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4969: 	'<th>'.&nameUserString('header').'</th>'.
 4970: 	&Apache::loncommon::end_data_table_header_row();
 4971:  
 4972:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4973:     my $ptr = 1;
 4974:     foreach my $student (sort 
 4975: 			 {
 4976: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4977: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4978: 			     }
 4979: 			     return $a cmp $b;
 4980: 			 } (keys(%$fullname))) {
 4981: 	my ($uname,$udom) = split(/:/,$student);
 4982: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4983:                                   : '</td>');
 4984: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4985: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4986: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4987: 	$studentTable.=
 4988: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4989:                          : '');
 4990: 	$ptr++;
 4991:     }
 4992:     if ($ptr%2 == 0) {
 4993: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4994: 	    &Apache::loncommon::end_data_table_row();
 4995:     }
 4996:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4997:     $studentTable.='<input type="button" '.
 4998:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4999: 
 5000:     $request->print($studentTable);
 5001: 
 5002:     return '';
 5003: }
 5004: 
 5005: sub getSymbMap {
 5006:     my ($map_error) = @_;
 5007:     my $navmap = Apache::lonnavmaps::navmap->new();
 5008:     unless (ref($navmap)) {
 5009:         if (ref($map_error)) {
 5010:             $$map_error = 'navmap';
 5011:         }
 5012:         return;
 5013:     }
 5014:     my %symbx = ();
 5015:     my @titles = ();
 5016:     my $minder = 0;
 5017: 
 5018:     # Gather every sequence that has problems.
 5019:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 5020: 					       1,0,1);
 5021:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 5022: 	if ($navmap->hasResource($sequence, sub { shift->is_gradable(); }, 0) ) {
 5023: 	    my $title = $minder.'.'.
 5024: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 5025: 	    push(@titles, $title); # minder in case two titles are identical
 5026: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 5027: 	    $minder++;
 5028: 	}
 5029:     }
 5030:     return \@titles,\%symbx;
 5031: }
 5032: 
 5033: #
 5034: #--- Displays a page/sequence w/wo problems, w/wo submissions
 5035: sub displayPage {
 5036:     my ($request,$symb) = @_;
 5037:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5038:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5039:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5040:     my $pageTitle = $env{'form.page'};
 5041:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5042:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5043:     my $usec=$classlist->{$env{'form.student'}}[5];
 5044: 
 5045:     #need to make sure we have the correct data for later EXT calls, 
 5046:     #thus invalidate the cache
 5047:     &Apache::lonnet::devalidatecourseresdata(
 5048:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 5049:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 5050:     &Apache::lonnet::clear_EXT_cache_status();
 5051: 
 5052:     if (!&canview($usec)) {
 5053:         $request->print(
 5054:             '<span class="LC_warning">'.
 5055:             &mt('Unable to view requested student. ([_1])',
 5056:                     $env{'form.student'}).
 5057:             '</span>');
 5058:         return;
 5059:     }
 5060:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5061:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 5062: 	'</h3>'."\n";
 5063:     $env{'form.CODE'} = uc($env{'form.CODE'});
 5064:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 5065: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 5066:     } else {
 5067: 	delete($env{'form.CODE'});
 5068:     }
 5069:     &sub_page_js($request);
 5070:     $request->print($result);
 5071: 
 5072:     my $navmap = Apache::lonnavmaps::navmap->new();
 5073:     unless (ref($navmap)) {
 5074:         $request->print(&navmap_errormsg());
 5075:         return;
 5076:     }
 5077:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 5078:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5079:     if (!$map) {
 5080: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 5081: 	return; 
 5082:     }
 5083:     my $iterator = $navmap->getIterator($map->map_start(),
 5084: 					$map->map_finish());
 5085: 
 5086:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 5087: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 5088: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 5089: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 5090: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 5091: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 5092: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 5093: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
 5094: 
 5095:     if (defined($env{'form.CODE'})) {
 5096: 	$studentTable.=
 5097: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 5098:     }
 5099:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 5100: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 5101: 
 5102:     $studentTable.='&nbsp;<span class="LC_info">'.
 5103:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 5104:         '</span>'."\n".
 5105: 	&Apache::loncommon::start_data_table().
 5106: 	&Apache::loncommon::start_data_table_header_row().
 5107: 	'<th>'.&mt('Prob.').'</th>'.
 5108: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 5109: 	&Apache::loncommon::end_data_table_header_row();
 5110: 
 5111:     &Apache::lonxml::clear_problem_counter();
 5112:     my ($depth,$question,$prob) = (1,1,1);
 5113:     $iterator->next(); # skip the first BEGIN_MAP
 5114:     my $curRes = $iterator->next(); # for "current resource"
 5115:     while ($depth > 0) {
 5116:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5117:         if($curRes == $iterator->END_MAP) { $depth--; }
 5118: 
 5119:         if (ref($curRes) && $curRes->is_gradable()) {
 5120: 	    my $parts = $curRes->parts();
 5121:             my $title = $curRes->compTitle();
 5122: 	    my $symbx = $curRes->symb();
 5123:             my $is_tool = ($symbx =~ /ext\.tool$/);
 5124: 	    $studentTable.=
 5125: 		&Apache::loncommon::start_data_table_row().
 5126: 		'<td align="center" valign="top" >'.$prob.
 5127: 		(scalar(@{$parts}) == 1 ? '' 
 5128: 		                        : '<br />('.&mt('[_1]parts',
 5129: 							scalar(@{$parts}).'&nbsp;').')'
 5130: 		 ).
 5131: 		 '</td>';
 5132: 	    $studentTable.='<td valign="top">';
 5133: 	    my %form = ('CODE' => $env{'form.CODE'},);
 5134:             if ($is_tool) {
 5135:                 $studentTable.='&nbsp;<b>'.$title.'</b><br />';
 5136:             } else {
 5137: 	        if ($env{'form.vProb'} eq 'yes' ) {
 5138: 		    $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 5139: 					         undef,'both',\%form);
 5140: 	        } else {
 5141: 		    my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 5142: 		    $companswer =~ s|<form(.*?)>||g;
 5143: 		    $companswer =~ s|</form>||g;
 5144: #		    while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 5145: #		        $companswer =~ s/$1/ /ms;
 5146: #		        $request->print('match='.$1."<br />\n");
 5147: #		    }
 5148: #		    $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 5149: 		    $studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 5150: 		}
 5151: 	    }
 5152: 
 5153: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 5154: 
 5155: 	    if ($env{'form.lastSub'} eq 'datesub') {
 5156: 		if ($record{'version'} eq '') {
 5157:                     my $msg = &mt('No recorded submission for this problem.');
 5158:                     if ($is_tool) {
 5159:                         $msg = &mt('No recorded transactions for this external tool');
 5160:                     }
 5161: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.$msg.'</span><br />';
 5162: 		} else {
 5163: 		    my %responseType = ();
 5164: 		    foreach my $partid (@{$parts}) {
 5165: 			my @responseIds =$curRes->responseIds($partid);
 5166: 			my @responseType =$curRes->responseType($partid);
 5167: 			my %responseIds;
 5168: 			for (my $i=0;$i<=$#responseIds;$i++) {
 5169: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 5170: 			}
 5171: 			$responseType{$partid} = \%responseIds;
 5172: 		    }
 5173: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 5174: 		}
 5175: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 5176: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 5177:                 my $identifier = (&canmodify($usec)? $prob : ''); 
 5178: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 5179: 									$env{'request.course.id'},
 5180: 									'','.submission',undef,
 5181:                                                                         $usec,$identifier);
 5182:  
 5183: 	    }
 5184: 	    if (&canmodify($usec)) {
 5185:             $studentTable.=&gradeBox_start();
 5186: 		foreach my $partid (@{$parts}) {
 5187: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 5188: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 5189: 		    $question++;
 5190: 		}
 5191:             $studentTable.=&gradeBox_end();
 5192: 		$prob++;
 5193: 	    }
 5194: 	    $studentTable.='</td></tr>';
 5195: 
 5196: 	}
 5197:         $curRes = $iterator->next();
 5198:     }
 5199: 
 5200:     $studentTable.=
 5201:         '</table>'."\n".
 5202:         '<input type="button" value="'.&mt('Save').'" '.
 5203:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 5204:         '</form>'."\n";
 5205:     $request->print($studentTable);
 5206: 
 5207:     return '';
 5208: }
 5209: 
 5210: sub displaySubByDates {
 5211:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 5212:     my $isCODE=0;
 5213:     my $isTask = ($symb =~/\.task$/);
 5214:     my $is_tool = ($symb =~/\.tool$/);
 5215:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 5216:     my $studentTable=&Apache::loncommon::start_data_table().
 5217: 	&Apache::loncommon::start_data_table_header_row().
 5218: 	'<th>'.&mt('Date/Time').'</th>'.
 5219: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 5220:         ($isTask?'<th>'.&mt('Version').'</th>':'').
 5221: 	'<th>'.($is_tool?&mt('Grade'):&mt('Submission')).'</th>'.
 5222: 	'<th>'.&mt('Status').'</th>'.
 5223: 	&Apache::loncommon::end_data_table_header_row();
 5224:     my ($version);
 5225:     my %mark;
 5226:     my %orders;
 5227:     $mark{'correct_by_student'} = $checkIcon;
 5228:     if (!exists($$record{'1:timestamp'})) {
 5229:         if ($is_tool) {
 5230:             return '<br />&nbsp;<span class="LC_warning">'.&mt('No grade passed back.').'</span><br />';
 5231:         } else {
 5232:             return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 5233:         }
 5234:     }
 5235: 
 5236:     my $interaction;
 5237:     my $no_increment = 1;
 5238:     my (%lastrndseed,%lasttype);
 5239:     for ($version=1;$version<=$$record{'version'};$version++) {
 5240: 	my $timestamp = 
 5241: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 5242: 	if (exists($$record{$version.':resource.0.version'})) {
 5243: 	    $interaction = $$record{$version.':resource.0.version'};
 5244: 	}
 5245:         if ($isTask && $env{'form.previousversion'}) {
 5246:             next unless ($interaction == $env{'form.previousversion'});
 5247:         }
 5248: 	my $where = ($isTask ? "$version:resource.$interaction"
 5249: 		             : "$version:resource");
 5250: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 5251: 	    '<td>'.$timestamp.'</td>';
 5252: 	if ($isCODE) {
 5253: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 5254: 	}
 5255:         if ($isTask) {
 5256:             $studentTable.='<td>'.$interaction.'</td>';
 5257:         }
 5258: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 5259: 	my @displaySub = ();
 5260: 	foreach my $partid (@{$parts}) {
 5261:             my ($hidden,$type);
 5262:             $type = $$record{$version.':resource.'.$partid.'.type'};
 5263:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
 5264:                 $hidden = 1;
 5265:             }
 5266:             my @matchKey;
 5267:             if ($isTask) {
 5268:                 @matchKey = sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys);
 5269:             } elsif ($is_tool) {
 5270:                 @matchKey = sort(grep /^resource\.\Q$partid\E\.awarded$/,@versionKeys);
 5271:             } else {
 5272:                 @matchKey = sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys);
 5273:             }
 5274: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 5275: 	    my $display_part=&get_display_part($partid,$symb);
 5276: 	    foreach my $matchKey (@matchKey) {
 5277: 		if (exists($$record{$version.':'.$matchKey}) &&
 5278: 		    $$record{$version.':'.$matchKey} ne '') {
 5279:                     if ($is_tool) {
 5280:                         $displaySub[0].=$$record{"$version:resource.$partid.awarded"};
 5281:                     } else {
 5282: 		        my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 5283: 				                   : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 5284:                         $displaySub[0].='<span class="LC_nobreak">';
 5285:                         $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 5286:                                        .' <span class="LC_internal_info">'
 5287:                                        .'('.&mt('Response ID: [_1]',$responseId).')'
 5288:                                        .'</span>'
 5289:                                        .' <b>';
 5290:                         if ($hidden) {
 5291:                             $displaySub[0].= &mt('Anonymous Survey').'</b>';
 5292:                         } else {
 5293:                             my ($trial,$rndseed,$newvariation);
 5294:                             if ($type eq 'randomizetry') {
 5295:                                 $trial = $$record{"$where.$partid.tries"};
 5296:                                 $rndseed = $$record{"$where.$partid.rndseed"};
 5297:                             }
 5298: 		            if ($$record{"$where.$partid.tries"} eq '') {
 5299: 			        $displaySub[0].=&mt('Trial not counted');
 5300: 		            } else {
 5301: 			        $displaySub[0].=&mt('Trial: [_1]',
 5302: 					        $$record{"$where.$partid.tries"});
 5303:                                 if (($rndseed ne '') && ($lastrndseed{$partid} ne '')) {
 5304:                                     if (($rndseed ne $lastrndseed{$partid}) &&
 5305:                                         (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
 5306:                                         $newvariation = '&nbsp;('.&mt('New variation this try').')';
 5307:                                     }
 5308:                                 }
 5309:                                 $lastrndseed{$partid} = $rndseed;
 5310:                                 $lasttype{$partid} = $type;
 5311: 		            }
 5312: 		            my $responseType=($isTask ? 'Task'
 5313:                                               : $responseType->{$partid}->{$responseId});
 5314: 		            if (!exists($orders{$partid})) { $orders{$partid}={}; }
 5315: 		            if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
 5316: 			        $orders{$partid}->{$responseId}=
 5317: 			            &get_order($partid,$responseId,$symb,$uname,$udom,
 5318:                                                $no_increment,$type,$trial,$rndseed);
 5319: 		            }
 5320: 		            $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
 5321: 		            $displaySub[0].='&nbsp; '.
 5322: 			        &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
 5323:                         }
 5324:                     }
 5325: 		}
 5326: 	    }
 5327: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 5328: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 5329: 				    $$record{"$where.$partid.checkedin"},
 5330: 				    $$record{"$where.$partid.checkedin.slot"}).
 5331: 					'<br />';
 5332: 	    }
 5333: 	    if (exists $$record{"$where.$partid.award"}) {
 5334: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 5335: 		    lc($$record{"$where.$partid.award"}).' '.
 5336: 		    $mark{$$record{"$where.$partid.solved"}}.
 5337: 		    '<br />';
 5338: 	    } elsif (($is_tool) && (exists($$record{"$version:resource.$partid.solved"}))) {
 5339: 		if ($$record{"$version:resource.$partid.solved"} =~ /^(in|)correct_by_passback$/) {
 5340: 		    $displaySub[1].=&mt('Grade passed back by external tool');
 5341: 		}
 5342: 	    }
 5343: 	    if (exists $$record{"$where.$partid.regrader"}) {
 5344: 		$displaySub[2].=$$record{"$where.$partid.regrader"};
 5345: 		unless ($is_tool) {
 5346: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5347: 		}
 5348: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 5349: 		$displaySub[2].=
 5350: 		    $$record{"$version:resource.$partid.regrader"};
 5351:                 unless ($is_tool) {
 5352: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5353:                 }
 5354: 	    }
 5355: 	}
 5356: 	# needed because old essay regrader has not parts info
 5357: 	if (exists $$record{"$version:resource.regrader"}) {
 5358: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 5359: 	}
 5360: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 5361: 	if ($displaySub[2]) {
 5362: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 5363: 	}
 5364: 	$studentTable.='&nbsp;</td>'.
 5365: 	    &Apache::loncommon::end_data_table_row();
 5366:     }
 5367:     $studentTable.=&Apache::loncommon::end_data_table();
 5368:     return $studentTable;
 5369: }
 5370: 
 5371: sub updateGradeByPage {
 5372:     my ($request,$symb) = @_;
 5373: 
 5374:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5375:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5376:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5377:     my $pageTitle = $env{'form.page'};
 5378:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5379:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5380:     my $usec=$classlist->{$env{'form.student'}}[5];
 5381:     if (!&canmodify($usec)) {
 5382: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 5383: 	return;
 5384:     }
 5385:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5386:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 5387: 	'</h3>'."\n";
 5388: 
 5389:     $request->print($result);
 5390: 
 5391: 
 5392:     my $navmap = Apache::lonnavmaps::navmap->new();
 5393:     unless (ref($navmap)) {
 5394:         $request->print(&navmap_errormsg());
 5395:         return;
 5396:     }
 5397:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 5398:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5399:     if (!$map) {
 5400: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 5401: 	return; 
 5402:     }
 5403:     my $iterator = $navmap->getIterator($map->map_start(),
 5404: 					$map->map_finish());
 5405: 
 5406:     my $studentTable=
 5407: 	&Apache::loncommon::start_data_table().
 5408: 	&Apache::loncommon::start_data_table_header_row().
 5409: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 5410: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 5411: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 5412: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 5413: 	&Apache::loncommon::end_data_table_header_row();
 5414: 
 5415:     $iterator->next(); # skip the first BEGIN_MAP
 5416:     my $curRes = $iterator->next(); # for "current resource"
 5417:     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
 5418:     while ($depth > 0) {
 5419:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5420:         if($curRes == $iterator->END_MAP) { $depth--; }
 5421: 
 5422:         if (ref($curRes) && $curRes->is_problem()) {
 5423: 	    my $parts = $curRes->parts();
 5424:             my $title = $curRes->compTitle();
 5425: 	    my $symbx = $curRes->symb();
 5426: 	    $studentTable.=
 5427: 		&Apache::loncommon::start_data_table_row().
 5428: 		'<td align="center" valign="top" >'.$prob.
 5429: 		(scalar(@{$parts}) == 1 ? '' 
 5430:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
 5431: 		.')').'</td>';
 5432: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 5433: 
 5434: 	    my %newrecord=();
 5435: 	    my @displayPts=();
 5436:             my %aggregate = ();
 5437:             my $aggregateflag = 0;
 5438:             if ($env{'form.HIDE'.$prob}) {
 5439:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 5440:                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
 5441:                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
 5442:                 $hideflag += $numchgs;
 5443:             }
 5444: 	    foreach my $partid (@{$parts}) {
 5445: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 5446: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 5447: 
 5448: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 5449: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 5450: 		my $partial = $newpts/$wgt;
 5451: 		my $score;
 5452: 		if ($partial > 0) {
 5453: 		    $score = 'correct_by_override';
 5454: 		} elsif ($newpts ne '') { #empty is taken as 0
 5455: 		    $score = 'incorrect_by_override';
 5456: 		}
 5457: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 5458: 		if ($dropMenu eq 'excused') {
 5459: 		    $partial = '';
 5460: 		    $score = 'excused';
 5461: 		} elsif ($dropMenu eq 'reset status'
 5462: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 5463: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 5464: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 5465: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 5466: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 5467: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 5468: 		    $changeflag++;
 5469: 		    $newpts = '';
 5470:                     
 5471:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 5472:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 5473:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 5474:                     if ($aggtries > 0) {
 5475:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 5476:                         $aggregateflag = 1;
 5477:                     }
 5478: 		}
 5479: 		my $display_part=&get_display_part($partid,$curRes->symb());
 5480: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 5481: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5482: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 5483: 		    '&nbsp;<br />';
 5484: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5485: 		     (($score eq 'excused') ? 'excused' : $newpts).
 5486: 		    '&nbsp;<br />';
 5487: 		$question++;
 5488: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 5489: 
 5490: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 5491: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 5492: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 5493: 		    if (scalar(keys(%newrecord)) > 0);
 5494: 
 5495: 		$changeflag++;
 5496: 	    }
 5497: 	    if (scalar(keys(%newrecord)) > 0) {
 5498: 		my %record = 
 5499: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 5500: 					     $udom,$uname);
 5501: 
 5502: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 5503: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 5504: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 5505: 		    $newrecord{'resource.CODE'} = '';
 5506: 		}
 5507: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 5508: 					$udom,$uname);
 5509: 		%record = &Apache::lonnet::restore($symbx,
 5510: 						   $env{'request.course.id'},
 5511: 						   $udom,$uname);
 5512: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 5513: 					     $cdom,$cnum,$udom,$uname);
 5514: 	    }
 5515: 	    
 5516:             if ($aggregateflag) {
 5517:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 5518:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 5519:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 5520:             }
 5521: 
 5522: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 5523: 		'<td valign="top">'.$displayPts[1].'</td>'.
 5524: 		&Apache::loncommon::end_data_table_row();
 5525: 
 5526: 	    $prob++;
 5527: 	}
 5528:         $curRes = $iterator->next();
 5529:     }
 5530: 
 5531:     $studentTable.=&Apache::loncommon::end_data_table();
 5532:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 5533: 		  &mt('The scores were changed for [quant,_1,problem].',
 5534: 		  $changeflag).'<br />');
 5535:     my $hidemsg=($hideflag == 0 ? '' :
 5536:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
 5537:                      $hideflag).'<br />');
 5538:     $request->print($hidemsg.$grademsg.$studentTable);
 5539: 
 5540:     return '';
 5541: }
 5542: 
 5543: #-------- end of section for handling grading by page/sequence ---------
 5544: #
 5545: #-------------------------------------------------------------------
 5546: 
 5547: #-------------------- Bubblesheet (Scantron) Grading -------------------
 5548: #
 5549: #------ start of section for handling grading by page/sequence ---------
 5550: 
 5551: =pod
 5552: 
 5553: =head1 Bubble sheet grading routines
 5554: 
 5555:   For this documentation:
 5556: 
 5557:    'scanline' refers to the full line of characters
 5558:    from the file that we are parsing that represents one entire sheet
 5559: 
 5560:    'bubble line' refers to the data
 5561:    representing the line of bubbles that are on the physical bubblesheet
 5562: 
 5563: 
 5564: The overall process is that a scanned in bubblesheet data is uploaded
 5565: into a course. When a user wants to grade, they select a
 5566: sequence/folder of resources, a file of bubblesheet info, and pick
 5567: one of the predefined configurations for what each scanline looks
 5568: like.
 5569: 
 5570: Next each scanline is checked for any errors of either 'missing
 5571: bubbles' (it's an error because it may have been mis-scanned
 5572: because too light bubbling), 'double bubble' (each bubble line should
 5573: have no more than one letter picked), invalid or duplicated CODE,
 5574: invalid student/employee ID
 5575: 
 5576: If the CODE option is used that determines the randomization of the
 5577: homework problems, either way the student/employee ID is looked up into a
 5578: username:domain.
 5579: 
 5580: During the validation phase the instructor can choose to skip scanlines. 
 5581: 
 5582: After the validation phase, there are now 3 bubblesheet files
 5583: 
 5584:   scantron_original_filename (unmodified original file)
 5585:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 5586:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 5587: 
 5588: Also there is a separate hash nohist_scantrondata that contains extra
 5589: correction information that isn't representable in the bubblesheet
 5590: file (see &scantron_getfile() for more information)
 5591: 
 5592: After all scanlines are either valid, marked as valid or skipped, then
 5593: foreach line foreach problem in the picked sequence, an ssi request is
 5594: made that simulates a user submitting their selected letter(s) against
 5595: the homework problem.
 5596: 
 5597: =over 4
 5598: 
 5599: 
 5600: 
 5601: =item defaultFormData
 5602: 
 5603:   Returns html hidden inputs used to hold context/default values.
 5604: 
 5605:  Arguments:
 5606:   $symb - $symb of the current resource 
 5607: 
 5608: =cut
 5609: 
 5610: sub defaultFormData {
 5611:     my ($symb)=@_;
 5612:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
 5613: }
 5614: 
 5615: 
 5616: =pod 
 5617: 
 5618: =item getSequenceDropDown
 5619: 
 5620:    Return html dropdown of possible sequences to grade
 5621:  
 5622:  Arguments:
 5623:    $symb - $symb of the current resource
 5624:    $map_error - ref to scalar which will container error if
 5625:                 $navmap object is unavailable in &getSymbMap().
 5626: 
 5627: =cut
 5628: 
 5629: sub getSequenceDropDown {
 5630:     my ($symb,$map_error)=@_;
 5631:     my $result='<select name="selectpage">'."\n";
 5632:     my ($titles,$symbx) = &getSymbMap($map_error);
 5633:     if (ref($map_error)) {
 5634:         return if ($$map_error);
 5635:     }
 5636:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 5637:     my $ctr=0;
 5638:     foreach (@$titles) {
 5639: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5640: 	$result.='<option value="'.$$symbx{$_}.'" '.
 5641: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 5642: 	    '>'.$showtitle.'</option>'."\n";
 5643: 	$ctr++;
 5644:     }
 5645:     $result.= '</select>';
 5646:     return $result;
 5647: }
 5648: 
 5649: my %bubble_lines_per_response;     # no. bubble lines for each response.
 5650:                                    # key is zero-based index - 0, 1, 2 ...
 5651: 
 5652: my %first_bubble_line;             # First bubble line no. for each bubble.
 5653: 
 5654: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 5655:                                    # matchresponse or rankresponse, where 
 5656:                                    # an individual response can have multiple 
 5657:                                    # lines
 5658: 
 5659: my %responsetype_per_response;     # responsetype for each response
 5660: 
 5661: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
 5662:                                    # numbered response. Needed when randomorder
 5663:                                    # or randompick are in use. Key is ID, value 
 5664:                                    # is response number.
 5665: 
 5666: # Save and restore the bubble lines array to the form env.
 5667: 
 5668: 
 5669: sub save_bubble_lines {
 5670:     foreach my $line (keys(%bubble_lines_per_response)) {
 5671: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 5672: 	$env{"form.scantron.first_bubble_line.$line"} =
 5673: 	    $first_bubble_line{$line};
 5674:         $env{"form.scantron.sub_bubblelines.$line"} = 
 5675:             $subdivided_bubble_lines{$line};
 5676:         $env{"form.scantron.responsetype.$line"} =
 5677:             $responsetype_per_response{$line};
 5678:     }
 5679:     foreach my $resid (keys(%masterseq_id_responsenum)) {
 5680:         my $line = $masterseq_id_responsenum{$resid};
 5681:         $env{"form.scantron.residpart.$line"} = $resid;
 5682:     }
 5683: }
 5684: 
 5685: 
 5686: sub restore_bubble_lines {
 5687:     my $line = 0;
 5688:     %bubble_lines_per_response = ();
 5689:     %masterseq_id_responsenum = ();
 5690:     while ($env{"form.scantron.bubblelines.$line"}) {
 5691: 	my $value = $env{"form.scantron.bubblelines.$line"};
 5692: 	$bubble_lines_per_response{$line} = $value;
 5693: 	$first_bubble_line{$line}  =
 5694: 	    $env{"form.scantron.first_bubble_line.$line"};
 5695:         $subdivided_bubble_lines{$line} =
 5696:             $env{"form.scantron.sub_bubblelines.$line"};
 5697:         $responsetype_per_response{$line} =
 5698:             $env{"form.scantron.responsetype.$line"};
 5699:         my $id = $env{"form.scantron.residpart.$line"};
 5700:         $masterseq_id_responsenum{$id} = $line;
 5701: 	$line++;
 5702:     }
 5703: }
 5704: 
 5705: =pod 
 5706: 
 5707: =item scantron_filenames
 5708: 
 5709:    Returns a list of the scantron files in the current course 
 5710: 
 5711: =cut
 5712: 
 5713: sub scantron_filenames {
 5714:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5715:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5716:     my $getpropath = 1;
 5717:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
 5718:                                                         $cname,$getpropath);
 5719:     my @possiblenames;
 5720:     if (ref($dirlist) eq 'ARRAY') {
 5721:         foreach my $filename (sort(@{$dirlist})) {
 5722: 	    ($filename)=split(/&/,$filename);
 5723: 	    if ($filename!~/^scantron_orig_/) { next ; }
 5724: 	    $filename=~s/^scantron_orig_//;
 5725: 	    push(@possiblenames,$filename);
 5726:         }
 5727:     }
 5728:     return @possiblenames;
 5729: }
 5730: 
 5731: =pod 
 5732: 
 5733: =item scantron_uploads
 5734: 
 5735:    Returns  html drop-down list of scantron files in current course.
 5736: 
 5737:  Arguments:
 5738:    $file2grade - filename to set as selected in the dropdown
 5739: 
 5740: =cut
 5741: 
 5742: sub scantron_uploads {
 5743:     my ($file2grade) = @_;
 5744:     my $result=	'<select name="scantron_selectfile">';
 5745:     $result.="<option></option>";
 5746:     foreach my $filename (sort(&scantron_filenames())) {
 5747: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 5748:     }
 5749:     $result.="</select>";
 5750:     return $result;
 5751: }
 5752: 
 5753: =pod 
 5754: 
 5755: =item scantron_scantab
 5756: 
 5757:   Returns html drop down of the scantron formats in the scantronformat.tab
 5758:   file.
 5759: 
 5760: =cut
 5761: 
 5762: sub scantron_scantab {
 5763:     my $result='<select name="scantron_format">'."\n";
 5764:     $result.='<option></option>'."\n";
 5765:     my @lines = &get_scantronformat_file();
 5766:     if (@lines > 0) {
 5767:         foreach my $line (@lines) {
 5768:             next if (($line =~ /^\#/) || ($line eq ''));
 5769: 	    my ($name,$descrip)=split(/:/,$line);
 5770: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 5771:         }
 5772:     }
 5773:     $result.='</select>'."\n";
 5774:     return $result;
 5775: }
 5776: 
 5777: =pod
 5778: 
 5779: =item get_scantronformat_file
 5780: 
 5781:   Returns an array containing lines from the scantron format file for
 5782:   the domain of the course.
 5783: 
 5784:   If a url for a custom.tab file is listed in domain's configuration.db, 
 5785:   lines are from this file.
 5786: 
 5787:   Otherwise, if a default.tab has been published in RES space by the 
 5788:   domainconfig user, lines are from this file.
 5789: 
 5790:   Otherwise, fall back to getting lines from the legacy file on the
 5791:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 5792: 
 5793: =cut
 5794: 
 5795: sub get_scantronformat_file {
 5796:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5797:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 5798:     my $gottab = 0;
 5799:     my @lines;
 5800:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5801:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5802:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5803:             if ($formatfile ne '-1') {
 5804:                 @lines = split("\n",$formatfile,-1);
 5805:                 $gottab = 1;
 5806:             }
 5807:         }
 5808:     }
 5809:     if (!$gottab) {
 5810:         my $confname = $cdom.'-domainconfig';
 5811:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5812:         my $formatfile =  &Apache::lonnet::getfile($default);
 5813:         if ($formatfile ne '-1') {
 5814:             @lines = split("\n",$formatfile,-1);
 5815:             $gottab = 1;
 5816:         }
 5817:     }
 5818:     if (!$gottab) {
 5819:         my @domains = &Apache::lonnet::current_machine_domains();
 5820:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5821:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5822:             @lines = <$fh>;
 5823:             close($fh);
 5824:         } else {
 5825:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 5826:             @lines = <$fh>;
 5827:             close($fh);
 5828:         }
 5829:     }
 5830:     return @lines;
 5831: }
 5832: 
 5833: =pod 
 5834: 
 5835: =item scantron_CODElist
 5836: 
 5837:   Returns html drop down of the saved CODE lists from current course,
 5838:   generated from earlier printings.
 5839: 
 5840: =cut
 5841: 
 5842: sub scantron_CODElist {
 5843:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5844:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5845:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5846:     my $namechoice='<option></option>';
 5847:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5848: 	if ($name =~ /^error: 2 /) { next; }
 5849: 	if ($name =~ /^type\0/) { next; }
 5850: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5851:     }
 5852:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5853:     return $namechoice;
 5854: }
 5855: 
 5856: =pod 
 5857: 
 5858: =item scantron_CODEunique
 5859: 
 5860:   Returns the html for "Each CODE to be used once" radio.
 5861: 
 5862: =cut
 5863: 
 5864: sub scantron_CODEunique {
 5865:     my $result='<span class="LC_nobreak">
 5866:                  <label><input type="radio" name="scantron_CODEunique"
 5867:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5868:                 </span>
 5869:                 <span class="LC_nobreak">
 5870:                  <label><input type="radio" name="scantron_CODEunique"
 5871:                         value="no" />'.&mt('No').' </label>
 5872:                 </span>';
 5873:     return $result;
 5874: }
 5875: 
 5876: =pod 
 5877: 
 5878: =item scantron_selectphase
 5879: 
 5880:   Generates the initial screen to start the bubblesheet process.
 5881:   Allows for - starting a grading run.
 5882:              - downloading existing scan data (original, corrected
 5883:                                                 or skipped info)
 5884: 
 5885:              - uploading new scan data
 5886: 
 5887:  Arguments:
 5888:   $r          - The Apache request object
 5889:   $file2grade - name of the file that contain the scanned data to score
 5890: 
 5891: =cut
 5892: 
 5893: sub scantron_selectphase {
 5894:     my ($r,$file2grade,$symb) = @_;
 5895:     if (!$symb) {return '';}
 5896:     my $map_error;
 5897:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 5898:     if ($map_error) {
 5899:         $r->print('<br />'.&navmap_errormsg().'<br />');
 5900:         return;
 5901:     }
 5902:     my $default_form_data=&defaultFormData($symb);
 5903:     my $file_selector=&scantron_uploads($file2grade);
 5904:     my $format_selector=&scantron_scantab();
 5905:     my $CODE_selector=&scantron_CODElist();
 5906:     my $CODE_unique=&scantron_CODEunique();
 5907:     my $result;
 5908: 
 5909:     $ssi_error = 0;
 5910: 
 5911:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5912:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5913: 
 5914: 	# Chunk of form to prompt for a scantron file upload.
 5915: 
 5916:         $r->print('
 5917:     <br />
 5918:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5919:        '.&Apache::loncommon::start_data_table_header_row().'
 5920:             <th>
 5921:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 5922:             </th>
 5923:        '.&Apache::loncommon::end_data_table_header_row().'
 5924:        '.&Apache::loncommon::start_data_table_row().'
 5925:             <td>
 5926: ');
 5927:     my $default_form_data=&defaultFormData($symb);
 5928:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5929:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5930:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 5931:     &js_escape(\$alertmsg);
 5932:     $r->print(&Apache::lonhtmlcommon::scripttag('
 5933:     function checkUpload(formname) {
 5934: 	if (formname.upfile.value == "") {
 5935: 	    alert("'.$alertmsg.'");
 5936: 	    return false;
 5937: 	}
 5938: 	formname.submit();
 5939:     }'));
 5940:     $r->print('
 5941:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5942:                 '.$default_form_data.'
 5943:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5944:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5945:                 <input name="command" value="scantronupload_save" type="hidden" />
 5946:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5947:                 <br />
 5948:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 5949:               </form>
 5950: ');
 5951: 
 5952:         $r->print('
 5953:             </td>
 5954:        '.&Apache::loncommon::end_data_table_row().'
 5955:        '.&Apache::loncommon::end_data_table().'
 5956: ');
 5957:     }
 5958: 
 5959:     # Chunk of form to prompt for a file to grade and how:
 5960: 
 5961:     $result.= '
 5962:     <br />
 5963:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5964:     <input type="hidden" name="command" value="scantron_warning" />
 5965:     '.$default_form_data.'
 5966:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5967:        '.&Apache::loncommon::start_data_table_header_row().'
 5968:             <th colspan="2">
 5969:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5970:             </th>
 5971:        '.&Apache::loncommon::end_data_table_header_row().'
 5972:        '.&Apache::loncommon::start_data_table_row().'
 5973:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5974:        '.&Apache::loncommon::end_data_table_row().'
 5975:        '.&Apache::loncommon::start_data_table_row().'
 5976:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 5977:        '.&Apache::loncommon::end_data_table_row().'
 5978:        '.&Apache::loncommon::start_data_table_row().'
 5979:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 5980:        '.&Apache::loncommon::end_data_table_row().'
 5981:        '.&Apache::loncommon::start_data_table_row().'
 5982:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5983:        '.&Apache::loncommon::end_data_table_row().'
 5984:        '.&Apache::loncommon::start_data_table_row().'
 5985:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5986:        '.&Apache::loncommon::end_data_table_row().'
 5987:        '.&Apache::loncommon::start_data_table_row().'
 5988: 	    <td> '.&mt('Options:').' </td>
 5989:             <td>
 5990: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5991:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5992:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5993: 	    </td>
 5994:        '.&Apache::loncommon::end_data_table_row().'
 5995:        '.&Apache::loncommon::start_data_table_row().'
 5996:             <td colspan="2">
 5997:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 5998:             </td>
 5999:        '.&Apache::loncommon::end_data_table_row().'
 6000:     '.&Apache::loncommon::end_data_table().'
 6001:     </form>
 6002: ';
 6003:    
 6004:     $r->print($result);
 6005: 
 6006: 
 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 get_scantron_config
 6072: 
 6073:    Parse and return the bubblesheet configuration line selected as a
 6074:    hash of configuration file fields.
 6075: 
 6076:  Arguments:
 6077:     which - the name of the configuration to parse from the file.
 6078: 
 6079: 
 6080:  Returns:
 6081:             If the named configuration is not in the file, an empty
 6082:             hash is returned.
 6083:     a hash with the fields
 6084:       name         - internal name for the this configuration setup
 6085:       description  - text to display to operator that describes this config
 6086:       CODElocation - if 0 or the string 'none'
 6087:                           - no CODE exists for this config
 6088:                      if -1 || the string 'letter'
 6089:                           - a CODE exists for this config and is
 6090:                             a string of letters
 6091:                      Unsupported value (but planned for future support)
 6092:                           if a positive integer
 6093:                                - The CODE exists as the first n items from
 6094:                                  the question section of the form
 6095:                           if the string 'number'
 6096:                                - The CODE exists for this config and is
 6097:                                  a string of numbers
 6098:       CODEstart   - (only matter if a CODE exists) column in the line where
 6099:                      the CODE starts
 6100:       CODElength  - length of the CODE
 6101:       IDstart     - column where the student/employee ID starts
 6102:       IDlength    - length of the student/employee ID info
 6103:       Qstart      - column where the information from the bubbled
 6104:                     'questions' start
 6105:       Qlength     - number of columns comprising a single bubble line from
 6106:                     the sheet. (usually either 1 or 10)
 6107:       Qon         - either a single character representing the character used
 6108:                     to signal a bubble was chosen in the positional setup, or
 6109:                     the string 'letter' if the letter of the chosen bubble is
 6110:                     in the final, or 'number' if a number representing the
 6111:                     chosen bubble is in the file (1->A 0->J)
 6112:       Qoff        - the character used to represent that a bubble was
 6113:                     left blank
 6114:       PaperID     - if the scanning process generates a unique number for each
 6115:                     sheet scanned the column that this ID number starts in
 6116:       PaperIDlength - number of columns that comprise the unique ID number
 6117:                       for the sheet of paper
 6118:       FirstName   - column that the first name starts in
 6119:       FirstNameLength - number of columns that the first name spans
 6120:  
 6121:       LastName    - column that the last name starts in
 6122:       LastNameLength - number of columns that the last name spans
 6123:       BubblesPerRow - number of bubbles available in each row used to 
 6124:                       bubble an answer. (If not specified, 10 assumed).
 6125: 
 6126: =cut
 6127: 
 6128: sub get_scantron_config {
 6129:     my ($which) = @_;
 6130:     my @lines = &get_scantronformat_file();
 6131:     my %config;
 6132:     #FIXME probably should move to XML it has already gotten a bit much now
 6133:     foreach my $line (@lines) {
 6134: 	my ($name,$descrip)=split(/:/,$line);
 6135: 	if ($name ne $which ) { next; }
 6136: 	chomp($line);
 6137: 	my @config=split(/:/,$line);
 6138: 	$config{'name'}=$config[0];
 6139: 	$config{'description'}=$config[1];
 6140: 	$config{'CODElocation'}=$config[2];
 6141: 	$config{'CODEstart'}=$config[3];
 6142: 	$config{'CODElength'}=$config[4];
 6143: 	$config{'IDstart'}=$config[5];
 6144: 	$config{'IDlength'}=$config[6];
 6145: 	$config{'Qstart'}=$config[7];
 6146:  	$config{'Qlength'}=$config[8];
 6147: 	$config{'Qoff'}=$config[9];
 6148: 	$config{'Qon'}=$config[10];
 6149: 	$config{'PaperID'}=$config[11];
 6150: 	$config{'PaperIDlength'}=$config[12];
 6151: 	$config{'FirstName'}=$config[13];
 6152: 	$config{'FirstNamelength'}=$config[14];
 6153: 	$config{'LastName'}=$config[15];
 6154: 	$config{'LastNamelength'}=$config[16];
 6155:         $config{'BubblesPerRow'}=$config[17];
 6156: 	last;
 6157:     }
 6158:     return %config;
 6159: }
 6160: 
 6161: =pod 
 6162: 
 6163: =item username_to_idmap
 6164: 
 6165:     creates a hash keyed by student/employee ID with values of the corresponding
 6166:     student username:domain. If a single ID occurs for more than one student,
 6167:     the status of the student is checked, and if Active, the value in the hash
 6168:     will be set to the Active student.
 6169: 
 6170:   Arguments:
 6171: 
 6172:     $classlist - reference to the class list hash. This is a hash
 6173:                  keyed by student name:domain  whose elements are references
 6174:                  to arrays containing various chunks of information
 6175:                  about the student. (See loncoursedata for more info).
 6176: 
 6177:   Returns
 6178:     %idmap - the constructed hash
 6179: 
 6180: =cut
 6181: 
 6182: sub username_to_idmap {
 6183:     my ($classlist)= @_;
 6184:     my %idmap;
 6185:     foreach my $student (keys(%$classlist)) {
 6186:         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
 6187:         unless ($id eq '') {
 6188:             if (!exists($idmap{$id})) {
 6189:                 $idmap{$id} = $student;
 6190:             } else {
 6191:                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
 6192:                 if ($status eq 'Active') {
 6193:                     $idmap{$id} = $student;
 6194:                 }
 6195:             }
 6196:         }
 6197:     }
 6198:     return %idmap;
 6199: }
 6200: 
 6201: =pod
 6202: 
 6203: =item scantron_fixup_scanline
 6204: 
 6205:    Process a requested correction to a scanline.
 6206: 
 6207:   Arguments:
 6208:     $scantron_config   - hash from &get_scantron_config()
 6209:     $scan_data         - hash of correction information 
 6210:                           (see &scantron_getfile())
 6211:     $line              - existing scanline
 6212:     $whichline         - line number of the passed in scanline
 6213:     $field             - type of change to process 
 6214:                          (either 
 6215:                           'ID'     -> correct the student/employee ID
 6216:                           'CODE'   -> correct the CODE
 6217:                           'answer' -> fixup the submitted answers)
 6218:     
 6219:    $args               - hash of additional info,
 6220:                           - 'ID' 
 6221:                                'newid' -> studentID to use in replacement
 6222:                                           of existing one
 6223:                           - 'CODE' 
 6224:                                'CODE_ignore_dup' - set to true if duplicates
 6225:                                                    should be ignored.
 6226: 	                       'CODE' - is new code or 'use_unfound'
 6227:                                         if the existing unfound code should
 6228:                                         be used as is
 6229:                           - 'answer'
 6230:                                'response' - new answer or 'none' if blank
 6231:                                'question' - the bubble line to change
 6232:                                'questionnum' - the question identifier,
 6233:                                                may include subquestion. 
 6234: 
 6235:   Returns:
 6236:     $line - the modified scanline
 6237: 
 6238:   Side effects: 
 6239:     $scan_data - may be updated
 6240: 
 6241: =cut
 6242: 
 6243: 
 6244: sub scantron_fixup_scanline {
 6245:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 6246:     if ($field eq 'ID') {
 6247: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 6248: 	    return ($line,1,'New value too large');
 6249: 	}
 6250: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 6251: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 6252: 				     $args->{'newid'});
 6253: 	}
 6254: 	substr($line,$$scantron_config{'IDstart'}-1,
 6255: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 6256: 	if ($args->{'newid'}=~/^\s*$/) {
 6257: 	    &scan_data($scan_data,"$whichline.user",
 6258: 		       $args->{'username'}.':'.$args->{'domain'});
 6259: 	}
 6260:     } elsif ($field eq 'CODE') {
 6261: 	if ($args->{'CODE_ignore_dup'}) {
 6262: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 6263: 	}
 6264: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 6265: 	if ($args->{'CODE'} ne 'use_unfound') {
 6266: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 6267: 		return ($line,1,'New CODE value too large');
 6268: 	    }
 6269: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 6270: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 6271: 	    }
 6272: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 6273: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 6274: 	}
 6275:     } elsif ($field eq 'answer') {
 6276: 	my $length=$scantron_config->{'Qlength'};
 6277: 	my $off=$scantron_config->{'Qoff'};
 6278: 	my $on=$scantron_config->{'Qon'};
 6279: 	my $answer=${off}x$length;
 6280: 	if ($args->{'response'} eq 'none') {
 6281: 	    &scan_data($scan_data,
 6282: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 6283: 	} else {
 6284: 	    if ($on eq 'letter') {
 6285: 		my @alphabet=('A'..'Z');
 6286: 		$answer=$alphabet[$args->{'response'}];
 6287: 	    } elsif ($on eq 'number') {
 6288: 		$answer=$args->{'response'}+1;
 6289: 		if ($answer == 10) { $answer = '0'; }
 6290: 	    } else {
 6291: 		substr($answer,$args->{'response'},1)=$on;
 6292: 	    }
 6293: 	    &scan_data($scan_data,
 6294: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 6295: 	}
 6296: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 6297: 	substr($line,$where-1,$length)=$answer;
 6298:     }
 6299:     return $line;
 6300: }
 6301: 
 6302: =pod
 6303: 
 6304: =item scan_data
 6305: 
 6306:     Edit or look up  an item in the scan_data hash.
 6307: 
 6308:   Arguments:
 6309:     $scan_data  - The hash (see scantron_getfile)
 6310:     $key        - shorthand of the key to edit (actual key is
 6311:                   scantronfilename_key).
 6312:     $data        - New value of the hash entry.
 6313:     $delete      - If true, the entry is removed from the hash.
 6314: 
 6315:   Returns:
 6316:     The new value of the hash table field (undefined if deleted).
 6317: 
 6318: =cut
 6319: 
 6320: 
 6321: sub scan_data {
 6322:     my ($scan_data,$key,$value,$delete)=@_;
 6323:     my $filename=$env{'form.scantron_selectfile'};
 6324:     if (defined($value)) {
 6325: 	$scan_data->{$filename.'_'.$key} = $value;
 6326:     }
 6327:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 6328:     return $scan_data->{$filename.'_'.$key};
 6329: }
 6330: 
 6331: # ----- These first few routines are general use routines.----
 6332: 
 6333: # Return the number of occurences of a pattern in a string.
 6334: 
 6335: sub occurence_count {
 6336:     my ($string, $pattern) = @_;
 6337: 
 6338:     my @matches = ($string =~ /$pattern/g);
 6339: 
 6340:     return scalar(@matches);
 6341: }
 6342: 
 6343: 
 6344: # Take a string known to have digits and convert all the
 6345: # digits into letters in the range J,A..I.
 6346: 
 6347: sub digits_to_letters {
 6348:     my ($input) = @_;
 6349: 
 6350:     my @alphabet = ('J', 'A'..'I');
 6351: 
 6352:     my @input    = split(//, $input);
 6353:     my $output ='';
 6354:     for (my $i = 0; $i < scalar(@input); $i++) {
 6355: 	if ($input[$i] =~ /\d/) {
 6356: 	    $output .= $alphabet[$input[$i]];
 6357: 	} else {
 6358: 	    $output .= $input[$i];
 6359: 	}
 6360:     }
 6361:     return $output;
 6362: }
 6363: 
 6364: =pod 
 6365: 
 6366: =item scantron_parse_scanline
 6367: 
 6368:   Decodes a scanline from the selected bubblesheet file
 6369: 
 6370:  Arguments:
 6371:     line             - The text of the bubblesheet file line to process
 6372:     whichline        - Line number
 6373:     scantron_config  - Hash describing the format of the bubblesheet lines.
 6374:     scan_data        - Hash of extra information about the scanline
 6375:                        (see scantron_getfile for more information)
 6376:     just_header      - True if should not process question answers but only
 6377:                        the stuff to the left of the answers.
 6378:     randomorder      - True if randomorder in use
 6379:     randompick       - True if randompick in use
 6380:     sequence         - Exam folder URL
 6381:     master_seq       - Ref to array containing symbs in exam folder
 6382:     symb_to_resource - Ref to hash of symbs for resources in exam folder
 6383:                        (corresponding values are resource objects)
 6384:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
 6385:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
 6386:                        are refs to an array of resource objects, ordered
 6387:                        according to order used for CODE, when randomorder
 6388:                        and or randompick are in use.
 6389:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
 6390:                        for current line to question number used for same question
 6391:                         in "Master Sequence" (as seen by Course Coordinator).
 6392:     startline        - Ref to hash where key is question number (0 is first)
 6393:                        and value is number of first bubble line for current 
 6394:                        student or code-based randompick and/or randomorder.
 6395:     totalref         - Ref of scalar used to score total number of bubble
 6396:                        lines needed for responses in a scan line (used when
 6397:                        randompick in use. 
 6398:     
 6399:  Returns:
 6400:    Hash containing the result of parsing the scanline
 6401: 
 6402:    Keys are all proceeded by the string 'scantron.'
 6403: 
 6404:        CODE    - the CODE in use for this scanline
 6405:        useCODE - 1 if the CODE is invalid but it usage has been forced
 6406:                  by the operator
 6407:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 6408:                             CODEs were selected, but the usage has been
 6409:                             forced by the operator
 6410:        ID  - student/employee ID
 6411:        PaperID - if used, the ID number printed on the sheet when the 
 6412:                  paper was scanned
 6413:        FirstName - first name from the sheet
 6414:        LastName  - last name from the sheet
 6415: 
 6416:      if just_header was not true these key may also exist
 6417: 
 6418:        missingerror - a list of bubble ranges that are considered to be answers
 6419:                       to a single question that don't have any bubbles filled in.
 6420:                       Of the form questionnumber:firstbubblenumber:count.
 6421:        doubleerror  - a list of bubble ranges that are considered to be answers
 6422:                       to a single question that have more than one bubble filled in.
 6423:                       Of the form questionnumber::firstbubblenumber:count
 6424:    
 6425:                 In the above, count is the number of bubble responses in the
 6426:                 input line needed to represent the possible answers to the question.
 6427:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 6428:                 per line would have count = 2.
 6429: 
 6430:        maxquest     - the number of the last bubble line that was parsed
 6431: 
 6432:        (<number> starts at 1)
 6433:        <number>.answer - zero or more letters representing the selected
 6434:                          letters from the scanline for the bubble line 
 6435:                          <number>.
 6436:                          if blank there was either no bubble or there where
 6437:                          multiple bubbles, (consult the keys missingerror and
 6438:                          doubleerror if this is an error condition)
 6439: 
 6440: =cut
 6441: 
 6442: sub scantron_parse_scanline {
 6443:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
 6444:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
 6445:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
 6446: 
 6447:     my %record;
 6448:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
 6449:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 6450: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 6451: 	if ($$scantron_config{'CODElocation'} < 0 ||
 6452: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 6453: 	    $$scantron_config{'CODElocation'} eq 'number') {
 6454: 	    $record{'scantron.CODE'}=substr($data,
 6455: 					    $$scantron_config{'CODEstart'}-1,
 6456: 					    $$scantron_config{'CODElength'});
 6457: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 6458: 		$record{'scantron.useCODE'}=1;
 6459: 	    }
 6460: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 6461: 		$record{'scantron.CODE_ignore_dup'}=1;
 6462: 	    }
 6463: 	} else {
 6464: 	    #FIXME interpret first N questions
 6465: 	}
 6466:     }
 6467:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 6468: 				  $$scantron_config{'IDlength'});
 6469:     $record{'scantron.PaperID'}=
 6470: 	substr($data,$$scantron_config{'PaperID'}-1,
 6471: 	       $$scantron_config{'PaperIDlength'});
 6472:     $record{'scantron.FirstName'}=
 6473: 	substr($data,$$scantron_config{'FirstName'}-1,
 6474: 	       $$scantron_config{'FirstNamelength'});
 6475:     $record{'scantron.LastName'}=
 6476: 	substr($data,$$scantron_config{'LastName'}-1,
 6477: 	       $$scantron_config{'LastNamelength'});
 6478:     if ($just_header) { return \%record; }
 6479: 
 6480:     my @alphabet=('A'..'Z');
 6481:     my $questnum=0;
 6482:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 6483: 
 6484:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 6485:     if ($randompick || $randomorder) {
 6486:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
 6487:                                          $master_seq,$symb_to_resource,
 6488:                                          $partids_by_symb,$orderedforcode,
 6489:                                          $respnumlookup,$startline);
 6490:         if ($total) {
 6491:             $lastpos = $total*$$scantron_config{'Qlength'}; 
 6492:         }
 6493:         if (ref($totalref)) {
 6494:             $$totalref = $total;
 6495:         }
 6496:     }
 6497:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 6498:     chomp($questions);		# Get rid of any trailing \n.
 6499:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 6500:     while (length($questions)) {
 6501:         my $answers_needed;
 6502:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6503:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
 6504:         } else {
 6505: 	    $answers_needed = $bubble_lines_per_response{$questnum};
 6506:         }
 6507:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 6508:                              || 1;
 6509:         $questnum++;
 6510:         my $quest_id = $questnum;
 6511:         my $currentquest = substr($questions,0,$answer_length);
 6512:         $questions       = substr($questions,$answer_length);
 6513:         if (length($currentquest) < $answer_length) { next; }
 6514: 
 6515:         my $subdivided;
 6516:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6517:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
 6518:         } else {
 6519:             $subdivided = $subdivided_bubble_lines{$questnum-1};
 6520:         }
 6521:         if ($subdivided =~ /,/) {
 6522:             my $subquestnum = 1;
 6523:             my $subquestions = $currentquest;
 6524:             my @subanswers_needed = split(/,/,$subdivided);
 6525:             foreach my $subans (@subanswers_needed) {
 6526:                 my $subans_length =
 6527:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 6528:                 my $currsubquest = substr($subquestions,0,$subans_length);
 6529:                 $subquestions   = substr($subquestions,$subans_length);
 6530:                 $quest_id = "$questnum.$subquestnum";
 6531:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 6532:                     ($$scantron_config{'Qon'} eq 'number')) {
 6533:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 6534:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6535:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6536:                         $randomorder,$randompick,$respnumlookup);
 6537:                 } else {
 6538:                     $ansnum = &scantron_validator_positional($ansnum,
 6539:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6540:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6541:                         $randomorder,$randompick,$respnumlookup);
 6542:                 }
 6543:                 $subquestnum ++;
 6544:             }
 6545:         } else {
 6546:             if (($$scantron_config{'Qon'} eq 'letter') ||
 6547:                 ($$scantron_config{'Qon'} eq 'number')) {
 6548:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 6549:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6550:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6551:                     $randomorder,$randompick,$respnumlookup);
 6552:             } else {
 6553:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 6554:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6555:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6556:                     $randomorder,$randompick,$respnumlookup);
 6557:             }
 6558:         }
 6559:     }
 6560:     $record{'scantron.maxquest'}=$questnum;
 6561:     return \%record;
 6562: }
 6563: 
 6564: sub get_master_seq {
 6565:     my ($resources,$master_seq,$symb_to_resource) = @_;
 6566:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') && 
 6567:                    (ref($symb_to_resource) eq 'HASH'));
 6568:     my $resource_error;
 6569:     foreach my $resource (@{$resources}) {
 6570:         my $ressymb;
 6571:         if (ref($resource)) {
 6572:             $ressymb = $resource->symb();
 6573:             push(@{$master_seq},$ressymb);
 6574:             $symb_to_resource->{$ressymb} = $resource;
 6575:         } else {
 6576:             $resource_error = 1;
 6577:             last;
 6578:         }
 6579:     }
 6580:     return $resource_error;
 6581: }
 6582: 
 6583: sub get_respnum_lookups {
 6584:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
 6585:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
 6586:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
 6587:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
 6588:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
 6589:                    (ref($startline) eq 'HASH'));
 6590:     my ($user,$scancode);
 6591:     if ((exists($record->{'scantron.CODE'})) &&
 6592:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
 6593:         $scancode = $record->{'scantron.CODE'};
 6594:     } else {
 6595:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
 6596:     }
 6597:     my @mapresources =
 6598:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
 6599:                      $orderedforcode);
 6600:     my $total = 0;
 6601:     my $count = 0;
 6602:     foreach my $resource (@mapresources) {
 6603:         my $id = $resource->id();
 6604:         my $symb = $resource->symb();
 6605:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
 6606:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
 6607:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
 6608:                 if ($respnum ne '') {
 6609:                     $respnumlookup->{$count} = $respnum;
 6610:                     $startline->{$count} = $total;
 6611:                     $total += $bubble_lines_per_response{$respnum};
 6612:                     $count ++;
 6613:                 }
 6614:             }
 6615:         }
 6616:     }
 6617:     return $total;
 6618: }
 6619: 
 6620: sub scantron_validator_lettnum {
 6621:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 6622:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
 6623:         $randompick,$respnumlookup) = @_;
 6624: 
 6625:     # Qon 'letter' implies for each slot in currquest we have:
 6626:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 6627:     #    about anything else (esp. a value of Qoff) for missing
 6628:     #    bubbles.
 6629:     #
 6630:     # Qon 'number' implies each slot gives a digit that indexes the
 6631:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 6632:     #    and * or ? for double bubbles on a single line.
 6633:     #
 6634: 
 6635:     my $matchon;
 6636:     if ($$scantron_config{'Qon'} eq 'letter') {
 6637:         $matchon = '[A-Z]';
 6638:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 6639:         $matchon = '\d';
 6640:     }
 6641:     my $occurrences = 0;
 6642:     my $responsenum = $questnum-1;
 6643:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6644:        $responsenum = $respnumlookup->{$questnum-1} 
 6645:     }
 6646:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6647:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6648:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6649:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6650:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6651:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6652:         my @singlelines = split('',$currquest);
 6653:         foreach my $entry (@singlelines) {
 6654:             $occurrences = &occurence_count($entry,$matchon);
 6655:             if ($occurrences > 1) {
 6656:                 last;
 6657:             }
 6658:         }
 6659:     } else {
 6660:         $occurrences = &occurence_count($currquest,$matchon); 
 6661:     }
 6662:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 6663:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6664:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6665:             my $bubble = substr($currquest,$ans,1);
 6666:             if ($bubble =~ /$matchon/ ) {
 6667:                 if ($$scantron_config{'Qon'} eq 'number') {
 6668:                     if ($bubble == 0) {
 6669:                         $bubble = 10; 
 6670:                     }
 6671:                     $record->{"scantron.$ansnum.answer"} = 
 6672:                         $alphabet->[$bubble-1];
 6673:                 } else {
 6674:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 6675:                 }
 6676:             } else {
 6677:                 $record->{"scantron.$ansnum.answer"}='';
 6678:             }
 6679:             $ansnum++;
 6680:         }
 6681:     } elsif (!defined($currquest)
 6682:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 6683:             || (&occurence_count($currquest,$matchon) == 0)) {
 6684:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6685:             $record->{"scantron.$ansnum.answer"}='';
 6686:             $ansnum++;
 6687:         }
 6688:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6689:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 6690:         }
 6691:     } else {
 6692:         if ($$scantron_config{'Qon'} eq 'number') {
 6693:             $currquest = &digits_to_letters($currquest);            
 6694:         }
 6695:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6696:             my $bubble = substr($currquest,$ans,1);
 6697:             $record->{"scantron.$ansnum.answer"} = $bubble;
 6698:             $ansnum++;
 6699:         }
 6700:     }
 6701:     return $ansnum;
 6702: }
 6703: 
 6704: sub scantron_validator_positional {
 6705:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 6706:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
 6707:         $randomorder,$randompick,$respnumlookup) = @_;
 6708: 
 6709:     # Otherwise there's a positional notation;
 6710:     # each bubble line requires Qlength items, and there are filled in
 6711:     # bubbles for each case where there 'Qon' characters.
 6712:     #
 6713: 
 6714:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 6715: 
 6716:     # If the split only gives us one element.. the full length of the
 6717:     # answer string, no bubbles are filled in:
 6718: 
 6719:     if ($answers_needed eq '') {
 6720:         return;
 6721:     }
 6722: 
 6723:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 6724:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6725:             $record->{"scantron.$ansnum.answer"}='';
 6726:             $ansnum++;
 6727:         }
 6728:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6729:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 6730:         }
 6731:     } elsif (scalar(@array) == 2) {
 6732:         my $location = length($array[0]);
 6733:         my $line_num = int($location / $$scantron_config{'Qlength'});
 6734:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 6735:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6736:             if ($ans eq $line_num) {
 6737:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 6738:             } else {
 6739:                 $record->{"scantron.$ansnum.answer"} = ' ';
 6740:             }
 6741:             $ansnum++;
 6742:          }
 6743:     } else {
 6744:         #  If there's more than one instance of a bubble character
 6745:         #  That's a double bubble; with positional notation we can
 6746:         #  record all the bubbles filled in as well as the
 6747:         #  fact this response consists of multiple bubbles.
 6748:         #
 6749:         my $responsenum = $questnum-1;
 6750:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6751:             $responsenum = $respnumlookup->{$questnum-1}
 6752:         }
 6753:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6754:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6755:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6756:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6757:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6758:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6759:             my $doubleerror = 0;
 6760:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 6761:                    (!$doubleerror)) {
 6762:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 6763:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 6764:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 6765:                if (length(@currarray) > 2) {
 6766:                    $doubleerror = 1;
 6767:                } 
 6768:             }
 6769:             if ($doubleerror) {
 6770:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6771:             }
 6772:         } else {
 6773:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6774:         }
 6775:         my $item = $ansnum;
 6776:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6777:             $record->{"scantron.$item.answer"} = '';
 6778:             $item ++;
 6779:         }
 6780: 
 6781:         my @ans=@array;
 6782:         my $i=0;
 6783:         my $increment = 0;
 6784:         while ($#ans) {
 6785:             $i+=length($ans[0]) + $increment;
 6786:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 6787:             my $bubble = $i%$$scantron_config{'Qlength'};
 6788:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 6789:             shift(@ans);
 6790:             $increment = 1;
 6791:         }
 6792:         $ansnum += $answers_needed;
 6793:     }
 6794:     return $ansnum;
 6795: }
 6796: 
 6797: =pod
 6798: 
 6799: =item scantron_add_delay
 6800: 
 6801:    Adds an error message that occurred during the grading phase to a
 6802:    queue of messages to be shown after grading pass is complete
 6803: 
 6804:  Arguments:
 6805:    $delayqueue  - arrary ref of hash ref of error messages
 6806:    $scanline    - the scanline that caused the error
 6807:    $errormesage - the error message
 6808:    $errorcode   - a numeric code for the error
 6809: 
 6810:  Side Effects:
 6811:    updates the $delayqueue to have a new hash ref of the error
 6812: 
 6813: =cut
 6814: 
 6815: sub scantron_add_delay {
 6816:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 6817:     push(@$delayqueue,
 6818: 	 {'line' => $scanline, 'emsg' => $errormessage,
 6819: 	  'ecode' => $errorcode }
 6820: 	 );
 6821: }
 6822: 
 6823: =pod
 6824: 
 6825: =item scantron_find_student
 6826: 
 6827:    Finds the username for the current scanline
 6828: 
 6829:   Arguments:
 6830:    $scantron_record - hash result from scantron_parse_scanline
 6831:    $scan_data       - hash of correction information 
 6832:                       (see &scantron_getfile() form more information)
 6833:    $idmap           - hash from &username_to_idmap()
 6834:    $line            - number of current scanline
 6835:  
 6836:   Returns:
 6837:    Either 'username:domain' or undef if unknown
 6838: 
 6839: =cut
 6840: 
 6841: sub scantron_find_student {
 6842:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 6843:     my $scanID=$$scantron_record{'scantron.ID'};
 6844:     if ($scanID =~ /^\s*$/) {
 6845:  	return &scan_data($scan_data,"$line.user");
 6846:     }
 6847:     foreach my $id (keys(%$idmap)) {
 6848:  	if (lc($id) eq lc($scanID)) {
 6849:  	    return $$idmap{$id};
 6850:  	}
 6851:     }
 6852:     return undef;
 6853: }
 6854: 
 6855: =pod
 6856: 
 6857: =item scantron_filter
 6858: 
 6859:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 6860:    hidden resources was selected
 6861: 
 6862: =cut
 6863: 
 6864: sub scantron_filter {
 6865:     my ($curres)=@_;
 6866: 
 6867:     if (ref($curres) && $curres->is_problem()) {
 6868: 	# if the user has asked to not have either hidden
 6869: 	# or 'randomout' controlled resources to be graded
 6870: 	# don't include them
 6871: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6872: 	    && $curres->randomout) {
 6873: 	    return 0;
 6874: 	}
 6875: 	return 1;
 6876:     }
 6877:     return 0;
 6878: }
 6879: 
 6880: =pod
 6881: 
 6882: =item scantron_process_corrections
 6883: 
 6884:    Gets correction information out of submitted form data and corrects
 6885:    the scanline
 6886: 
 6887: =cut
 6888: 
 6889: sub scantron_process_corrections {
 6890:     my ($r) = @_;
 6891:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6892:     my ($scanlines,$scan_data)=&scantron_getfile();
 6893:     my $classlist=&Apache::loncoursedata::get_classlist();
 6894:     my $which=$env{'form.scantron_line'};
 6895:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 6896:     my ($skip,$err,$errmsg);
 6897:     if ($env{'form.scantron_skip_record'}) {
 6898: 	$skip=1;
 6899:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 6900: 	my $newstudent=$env{'form.scantron_username'}.':'.
 6901: 	    $env{'form.scantron_domain'};
 6902: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 6903: 	($line,$err,$errmsg)=
 6904: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6905: 				     'ID',{'newid'=>$newid,
 6906: 				    'username'=>$env{'form.scantron_username'},
 6907: 				    'domain'=>$env{'form.scantron_domain'}});
 6908:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 6909: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 6910: 	my $newCODE;
 6911: 	my %args;
 6912: 	if      ($resolution eq 'use_unfound') {
 6913: 	    $newCODE='use_unfound';
 6914: 	} elsif ($resolution eq 'use_found') {
 6915: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6916: 	} elsif ($resolution eq 'use_typed') {
 6917: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6918: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6919: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6920: 	}
 6921: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6922: 	    $args{'CODE_ignore_dup'}=1;
 6923: 	}
 6924: 	$args{'CODE'}=$newCODE;
 6925: 	($line,$err,$errmsg)=
 6926: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6927: 				     'CODE',\%args);
 6928:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6929: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6930: 	    ($line,$err,$errmsg)=
 6931: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6932: 					 $which,'answer',
 6933: 					 { 'question'=>$question,
 6934: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6935:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6936: 	    if ($err) { last; }
 6937: 	}
 6938:     }
 6939:     if ($err) {
 6940:         $r->print(
 6941:             '<p class="LC_error">'
 6942:            .&mt('Unable to accept last correction, an error occurred: [_1]',
 6943:                 $errmsg)
 6944:            .'</p>');
 6945:     } else {
 6946: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 6947: 	&scantron_putfile($scanlines,$scan_data);
 6948:     }
 6949: }
 6950: 
 6951: =pod
 6952: 
 6953: =item reset_skipping_status
 6954: 
 6955:    Forgets the current set of remember skipped scanlines (and thus
 6956:    reverts back to considering all lines in the
 6957:    scantron_skipped_<filename> file)
 6958: 
 6959: =cut
 6960: 
 6961: sub reset_skipping_status {
 6962:     my ($scanlines,$scan_data)=&scantron_getfile();
 6963:     &scan_data($scan_data,'remember_skipping',undef,1);
 6964:     &scantron_putfile(undef,$scan_data);
 6965: }
 6966: 
 6967: =pod
 6968: 
 6969: =item start_skipping
 6970: 
 6971:    Marks a scanline to be skipped. 
 6972: 
 6973: =cut
 6974: 
 6975: sub start_skipping {
 6976:     my ($scan_data,$i)=@_;
 6977:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6978:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6979: 	$remembered{$i}=2;
 6980:     } else {
 6981: 	$remembered{$i}=1;
 6982:     }
 6983:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6984: }
 6985: 
 6986: =pod
 6987: 
 6988: =item should_be_skipped
 6989: 
 6990:    Checks whether a scanline should be skipped.
 6991: 
 6992: =cut
 6993: 
 6994: sub should_be_skipped {
 6995:     my ($scanlines,$scan_data,$i)=@_;
 6996:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6997: 	# not redoing old skips
 6998: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6999: 	return 0;
 7000:     }
 7001:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 7002: 
 7003:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 7004: 	return 0;
 7005:     }
 7006:     return 1;
 7007: }
 7008: 
 7009: =pod
 7010: 
 7011: =item remember_current_skipped
 7012: 
 7013:    Discovers what scanlines are in the scantron_skipped_<filename>
 7014:    file and remembers them into scan_data for later use.
 7015: 
 7016: =cut
 7017: 
 7018: sub remember_current_skipped {
 7019:     my ($scanlines,$scan_data)=&scantron_getfile();
 7020:     my %to_remember;
 7021:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7022: 	if ($scanlines->{'skipped'}[$i]) {
 7023: 	    $to_remember{$i}=1;
 7024: 	}
 7025:     }
 7026: 
 7027:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 7028:     &scantron_putfile(undef,$scan_data);
 7029: }
 7030: 
 7031: =pod
 7032: 
 7033: =item check_for_error
 7034: 
 7035:     Checks if there was an error when attempting to remove a specific
 7036:     scantron_.. bubblesheet data file. Prints out an error if
 7037:     something went wrong.
 7038: 
 7039: =cut
 7040: 
 7041: sub check_for_error {
 7042:     my ($r,$result)=@_;
 7043:     if ($result ne 'ok' && $result ne 'not_found' ) {
 7044: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 7045:     }
 7046: }
 7047: 
 7048: =pod
 7049: 
 7050: =item scantron_warning_screen
 7051: 
 7052:    Interstitial screen to make sure the operator has selected the
 7053:    correct options before we start the validation phase.
 7054: 
 7055: =cut
 7056: 
 7057: sub scantron_warning_screen {
 7058:     my ($button_text,$symb)=@_;
 7059:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 7060:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7061:     my $CODElist;
 7062:     if ($scantron_config{'CODElocation'} &&
 7063: 	$scantron_config{'CODEstart'} &&
 7064: 	$scantron_config{'CODElength'}) {
 7065: 	$CODElist=$env{'form.scantron_CODElist'};
 7066: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
 7067: 	$CODElist=
 7068: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 7069: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 7070:     }
 7071:     my $lastbubblepoints;
 7072:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 7073:         $lastbubblepoints =
 7074:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
 7075:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
 7076:     }
 7077:     return ('
 7078: <p>
 7079: <span class="LC_warning">
 7080: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
 7081: </p>
 7082: <table>
 7083: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 7084: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 7085: '.$CODElist.$lastbubblepoints.'
 7086: </table>
 7087: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
 7088: '.&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>
 7089: 
 7090: <br />
 7091: ');
 7092: }
 7093: 
 7094: =pod
 7095: 
 7096: =item scantron_do_warning
 7097: 
 7098:    Check if the operator has picked something for all required
 7099:    fields. Error out if something is missing.
 7100: 
 7101: =cut
 7102: 
 7103: sub scantron_do_warning {
 7104:     my ($r,$symb)=@_;
 7105:     if (!$symb) {return '';}
 7106:     my $default_form_data=&defaultFormData($symb);
 7107:     $r->print(&scantron_form_start().$default_form_data);
 7108:     if ( $env{'form.selectpage'} eq '' ||
 7109: 	 $env{'form.scantron_selectfile'} eq '' ||
 7110: 	 $env{'form.scantron_format'} eq '' ) {
 7111: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
 7112: 	if ( $env{'form.selectpage'} eq '') {
 7113: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 7114: 	} 
 7115: 	if ( $env{'form.scantron_selectfile'} eq '') {
 7116: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
 7117: 	} 
 7118: 	if ( $env{'form.scantron_format'} eq '') {
 7119: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
 7120: 	} 
 7121:     } else {
 7122: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
 7123:         my $bubbledbyhand=&hand_bubble_option();
 7124: 	$r->print('
 7125: '.$warning.$bubbledbyhand.'
 7126: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 7127: <input type="hidden" name="command" value="scantron_validate" />
 7128: ');
 7129:     }
 7130:     $r->print("</form><br />");
 7131:     return '';
 7132: }
 7133: 
 7134: =pod
 7135: 
 7136: =item scantron_form_start
 7137: 
 7138:     html hidden input for remembering all selected grading options
 7139: 
 7140: =cut
 7141: 
 7142: sub scantron_form_start {
 7143:     my ($max_bubble)=@_;
 7144:     my $result= <<SCANTRONFORM;
 7145: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7146:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 7147:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 7148:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 7149:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 7150:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 7151:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 7152:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 7153:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 7154:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 7155: SCANTRONFORM
 7156: 
 7157:   my $line = 0;
 7158:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 7159:        my $chunk =
 7160: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 7161:        $chunk .=
 7162: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 7163:        $chunk .= 
 7164:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 7165:        $chunk .=
 7166:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 7167:        $chunk .=
 7168:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
 7169:        $result .= $chunk;
 7170:        $line++;
 7171:     }
 7172:     return $result;
 7173: }
 7174: 
 7175: =pod
 7176: 
 7177: =item scantron_validate_file
 7178: 
 7179:     Dispatch routine for doing validation of a bubblesheet data file.
 7180: 
 7181:     Also processes any necessary information resets that need to
 7182:     occur before validation begins (ignore previous corrections,
 7183:     restarting the skipped records processing)
 7184: 
 7185: =cut
 7186: 
 7187: sub scantron_validate_file {
 7188:     my ($r,$symb) = @_;
 7189:     if (!$symb) {return '';}
 7190:     my $default_form_data=&defaultFormData($symb);
 7191:     
 7192:     # do the detection of only doing skipped records first before we delete
 7193:     # them when doing the corrections reset
 7194:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 7195: 	&reset_skipping_status();
 7196:     }
 7197:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 7198: 	&remember_current_skipped();
 7199: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 7200:     }
 7201: 
 7202:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 7203: 	&check_for_error($r,&scantron_remove_file('corrected'));
 7204: 	&check_for_error($r,&scantron_remove_file('skipped'));
 7205: 	&check_for_error($r,&scantron_remove_scan_data());
 7206: 	$env{'form.scantron_options_ignore'}='done';
 7207:     }
 7208: 
 7209:     if ($env{'form.scantron_corrections'}) {
 7210: 	&scantron_process_corrections($r);
 7211:     }
 7212:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 7213:     #get the student pick code ready
 7214:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 7215:     my $nav_error;
 7216:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7217:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 7218:     if ($nav_error) {
 7219:         $r->print(&navmap_errormsg());
 7220:         return '';
 7221:     }
 7222:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 7223:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 7224:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
 7225:     }
 7226:     $r->print($result);
 7227:     
 7228:     my @validate_phases=( 'sequence',
 7229: 			  'ID',
 7230: 			  'CODE',
 7231: 			  'doublebubble',
 7232: 			  'missingbubbles');
 7233:     if (!$env{'form.validatepass'}) {
 7234: 	$env{'form.validatepass'} = 0;
 7235:     }
 7236:     my $currentphase=$env{'form.validatepass'};
 7237: 
 7238: 
 7239:     my $stop=0;
 7240:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 7241: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 7242: 	$r->rflush();
 7243:      
 7244: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 7245: 	{
 7246: 	    no strict 'refs';
 7247: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 7248: 	}
 7249:     }
 7250:     if (!$stop) {
 7251: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
 7252: 	$r->print(&mt('Validation process complete.').'<br />'.
 7253:                   $warning.
 7254:                   &mt('Perform verification for each student after storage of submissions?').
 7255:                   '&nbsp;<span class="LC_nobreak"><label>'.
 7256:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 7257:                   ('&nbsp;'x3).'<label>'.
 7258:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 7259:                   '</label></span><br />'.
 7260:                   &mt('Grading will take longer if you use verification.').'<br />'.
 7261:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
 7262:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 7263:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 7264:     } else {
 7265: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 7266: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 7267:     }
 7268:     if ($stop) {
 7269: 	if ($validate_phases[$currentphase] eq 'sequence') {
 7270: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 7271: 	    $r->print(' '.&mt('this error').' <br />');
 7272: 
 7273: 	    $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>');
 7274: 	} else {
 7275:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 7276: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 7277:             } else {
 7278:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 7279:             }
 7280: 	    $r->print(' '.&mt('using corrected info').' <br />');
 7281: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 7282: 	    $r->print(" ".&mt("this scanline saving it for later."));
 7283: 	}
 7284:     }
 7285:     $r->print(" </form><br />");
 7286:     return '';
 7287: }
 7288: 
 7289: 
 7290: =pod
 7291: 
 7292: =item scantron_remove_file
 7293: 
 7294:    Removes the requested bubblesheet data file, makes sure that
 7295:    scantron_original_<filename> is never removed
 7296: 
 7297: 
 7298: =cut
 7299: 
 7300: sub scantron_remove_file {
 7301:     my ($which)=@_;
 7302:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7303:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7304:     my $file='scantron_';
 7305:     if ($which eq 'corrected' || $which eq 'skipped') {
 7306: 	$file.=$which.'_';
 7307:     } else {
 7308: 	return 'refused';
 7309:     }
 7310:     $file.=$env{'form.scantron_selectfile'};
 7311:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 7312: }
 7313: 
 7314: 
 7315: =pod
 7316: 
 7317: =item scantron_remove_scan_data
 7318: 
 7319:    Removes all scan_data correction for the requested bubblesheet
 7320:    data file.  (In the case that both the are doing skipped records we need
 7321:    to remember the old skipped lines for the time being so that element
 7322:    persists for a while.)
 7323: 
 7324: =cut
 7325: 
 7326: sub scantron_remove_scan_data {
 7327:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7328:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7329:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 7330:     my @todelete;
 7331:     my $filename=$env{'form.scantron_selectfile'};
 7332:     foreach my $key (@keys) {
 7333: 	if ($key=~/^\Q$filename\E_/) {
 7334: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 7335: 		$key=~/remember_skipping/) {
 7336: 		next;
 7337: 	    }
 7338: 	    push(@todelete,$key);
 7339: 	}
 7340:     }
 7341:     my $result;
 7342:     if (@todelete) {
 7343: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 7344: 				       \@todelete,$cdom,$cname);
 7345:     } else {
 7346: 	$result = 'ok';
 7347:     }
 7348:     return $result;
 7349: }
 7350: 
 7351: 
 7352: =pod
 7353: 
 7354: =item scantron_getfile
 7355: 
 7356:     Fetches the requested bubblesheet data file (all 3 versions), and
 7357:     the scan_data hash
 7358:   
 7359:   Arguments:
 7360:     None
 7361: 
 7362:   Returns:
 7363:     2 hash references
 7364: 
 7365:      - first one has 
 7366:          orig      -
 7367:          corrected -
 7368:          skipped   -  each of which points to an array ref of the specified
 7369:                       file broken up into individual lines
 7370:          count     - number of scanlines
 7371:  
 7372:      - second is the scan_data hash possible keys are
 7373:        ($number refers to scanline numbered $number and thus the key affects
 7374:         only that scanline
 7375:         $bubline refers to the specific bubble line element and the aspects
 7376:         refers to that specific bubble line element)
 7377: 
 7378:        $number.user - username:domain to use
 7379:        $number.CODE_ignore_dup 
 7380:                     - ignore the duplicate CODE error 
 7381:        $number.useCODE
 7382:                     - use the CODE in the scanline as is
 7383:        $number.no_bubble.$bubline
 7384:                     - it is valid that there is no bubbled in bubble
 7385:                       at $number $bubline
 7386:        remember_skipping
 7387:                     - a frozen hash containing keys of $number and values
 7388:                       of either 
 7389:                         1 - we are on a 'do skipped records pass' and plan
 7390:                             on processing this line
 7391:                         2 - we are on a 'do skipped records pass' and this
 7392:                             scanline has been marked to skip yet again
 7393: 
 7394: =cut
 7395: 
 7396: sub scantron_getfile {
 7397:     #FIXME really would prefer a scantron directory
 7398:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7399:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7400:     my $lines;
 7401:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7402: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 7403:     my %scanlines;
 7404:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 7405:     my $temp=$scanlines{'orig'};
 7406:     $scanlines{'count'}=$#$temp;
 7407: 
 7408:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7409: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 7410:     if ($lines eq '-1') {
 7411: 	$scanlines{'corrected'}=[];
 7412:     } else {
 7413: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 7414:     }
 7415:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7416: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 7417:     if ($lines eq '-1') {
 7418: 	$scanlines{'skipped'}=[];
 7419:     } else {
 7420: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 7421:     }
 7422:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 7423:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 7424:     my %scan_data = @tmp;
 7425:     return (\%scanlines,\%scan_data);
 7426: }
 7427: 
 7428: =pod
 7429: 
 7430: =item lonnet_putfile
 7431: 
 7432:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 7433: 
 7434:  Arguments:
 7435:    $contents - data to store
 7436:    $filename - filename to store $contents into
 7437: 
 7438:  Returns:
 7439:    result value from &Apache::lonnet::finishuserfileupload
 7440: 
 7441: =cut
 7442: 
 7443: sub lonnet_putfile {
 7444:     my ($contents,$filename)=@_;
 7445:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7446:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7447:     $env{'form.sillywaytopassafilearound'}=$contents;
 7448:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 7449: 
 7450: }
 7451: 
 7452: =pod
 7453: 
 7454: =item scantron_putfile
 7455: 
 7456:     Stores the current version of the bubblesheet data files, and the
 7457:     scan_data hash. (Does not modify the original version only the
 7458:     corrected and skipped versions.
 7459: 
 7460:  Arguments:
 7461:     $scanlines - hash ref that looks like the first return value from
 7462:                  &scantron_getfile()
 7463:     $scan_data - hash ref that looks like the second return value from
 7464:                  &scantron_getfile()
 7465: 
 7466: =cut
 7467: 
 7468: sub scantron_putfile {
 7469:     my ($scanlines,$scan_data) = @_;
 7470:     #FIXME really would prefer a scantron directory
 7471:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7472:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7473:     if ($scanlines) {
 7474: 	my $prefix='scantron_';
 7475: # no need to update orig, shouldn't change
 7476: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 7477: #		    $env{'form.scantron_selectfile'});
 7478: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 7479: 			$prefix.'corrected_'.
 7480: 			$env{'form.scantron_selectfile'});
 7481: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 7482: 			$prefix.'skipped_'.
 7483: 			$env{'form.scantron_selectfile'});
 7484:     }
 7485:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 7486: }
 7487: 
 7488: =pod
 7489: 
 7490: =item scantron_get_line
 7491: 
 7492:    Returns the correct version of the scanline
 7493: 
 7494:  Arguments:
 7495:     $scanlines - hash ref that looks like the first return value from
 7496:                  &scantron_getfile()
 7497:     $scan_data - hash ref that looks like the second return value from
 7498:                  &scantron_getfile()
 7499:     $i         - number of the requested line (starts at 0)
 7500: 
 7501:  Returns:
 7502:    A scanline, (either the original or the corrected one if it
 7503:    exists), or undef if the requested scanline should be
 7504:    skipped. (Either because it's an skipped scanline, or it's an
 7505:    unskipped scanline and we are not doing a 'do skipped scanlines'
 7506:    pass.
 7507: 
 7508: =cut
 7509: 
 7510: sub scantron_get_line {
 7511:     my ($scanlines,$scan_data,$i)=@_;
 7512:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 7513:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 7514:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 7515:     return $scanlines->{'orig'}[$i]; 
 7516: }
 7517: 
 7518: =pod
 7519: 
 7520: =item scantron_todo_count
 7521: 
 7522:     Counts the number of scanlines that need processing.
 7523: 
 7524:  Arguments:
 7525:     $scanlines - hash ref that looks like the first return value from
 7526:                  &scantron_getfile()
 7527:     $scan_data - hash ref that looks like the second return value from
 7528:                  &scantron_getfile()
 7529: 
 7530:  Returns:
 7531:     $count - number of scanlines to process
 7532: 
 7533: =cut
 7534: 
 7535: sub get_todo_count {
 7536:     my ($scanlines,$scan_data)=@_;
 7537:     my $count=0;
 7538:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7539: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7540: 	if ($line=~/^[\s\cz]*$/) { next; }
 7541: 	$count++;
 7542:     }
 7543:     return $count;
 7544: }
 7545: 
 7546: =pod
 7547: 
 7548: =item scantron_put_line
 7549: 
 7550:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
 7551:     data file.
 7552: 
 7553:  Arguments:
 7554:     $scanlines - hash ref that looks like the first return value from
 7555:                  &scantron_getfile()
 7556:     $scan_data - hash ref that looks like the second return value from
 7557:                  &scantron_getfile()
 7558:     $i         - line number to update
 7559:     $newline   - contents of the updated scanline
 7560:     $skip      - if true make the line for skipping and update the
 7561:                  'skipped' file
 7562: 
 7563: =cut
 7564: 
 7565: sub scantron_put_line {
 7566:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 7567:     if ($skip) {
 7568: 	$scanlines->{'skipped'}[$i]=$newline;
 7569: 	&start_skipping($scan_data,$i);
 7570: 	return;
 7571:     }
 7572:     $scanlines->{'corrected'}[$i]=$newline;
 7573: }
 7574: 
 7575: =pod
 7576: 
 7577: =item scantron_clear_skip
 7578: 
 7579:    Remove a line from the 'skipped' file
 7580: 
 7581:  Arguments:
 7582:     $scanlines - hash ref that looks like the first return value from
 7583:                  &scantron_getfile()
 7584:     $scan_data - hash ref that looks like the second return value from
 7585:                  &scantron_getfile()
 7586:     $i         - line number to update
 7587: 
 7588: =cut
 7589: 
 7590: sub scantron_clear_skip {
 7591:     my ($scanlines,$scan_data,$i)=@_;
 7592:     if (exists($scanlines->{'skipped'}[$i])) {
 7593: 	undef($scanlines->{'skipped'}[$i]);
 7594: 	return 1;
 7595:     }
 7596:     return 0;
 7597: }
 7598: 
 7599: =pod
 7600: 
 7601: =item scantron_filter_not_exam
 7602: 
 7603:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 7604:    filter out resources that are not marked as 'exam' mode
 7605: 
 7606: =cut
 7607: 
 7608: sub scantron_filter_not_exam {
 7609:     my ($curres)=@_;
 7610:     
 7611:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 7612: 	# if the user has asked to not have either hidden
 7613: 	# or 'randomout' controlled resources to be graded
 7614: 	# don't include them
 7615: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 7616: 	    && $curres->randomout) {
 7617: 	    return 0;
 7618: 	}
 7619: 	return 1;
 7620:     }
 7621:     return 0;
 7622: }
 7623: 
 7624: =pod
 7625: 
 7626: =item scantron_validate_sequence
 7627: 
 7628:     Validates the selected sequence, checking for resource that are
 7629:     not set to exam mode.
 7630: 
 7631: =cut
 7632: 
 7633: sub scantron_validate_sequence {
 7634:     my ($r,$currentphase) = @_;
 7635: 
 7636:     my $navmap=Apache::lonnavmaps::navmap->new();
 7637:     unless (ref($navmap)) {
 7638:         $r->print(&navmap_errormsg());
 7639:         return (1,$currentphase);
 7640:     }
 7641:     my (undef,undef,$sequence)=
 7642: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7643: 
 7644:     my $map=$navmap->getResourceByUrl($sequence);
 7645: 
 7646:     $r->print('<input type="hidden" name="validate_sequence_exam"
 7647:                                     value="ignore" />');
 7648:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 7649: 	my @resources=
 7650: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 7651: 	if (@resources) {
 7652: 	    $r->print(
 7653:                 '<p class="LC_warning">'
 7654:                .&mt('Some resources in the sequence currently are not set to'
 7655:                    .' bubblesheet exam mode. Grading these resources currently may not'
 7656:                    .' work correctly.')
 7657:                .'</p>'
 7658:             );
 7659: 	    return (1,$currentphase);
 7660: 	}
 7661:     }
 7662: 
 7663:     return (0,$currentphase+1);
 7664: }
 7665: 
 7666: 
 7667: 
 7668: sub scantron_validate_ID {
 7669:     my ($r,$currentphase) = @_;
 7670:     
 7671:     #get student info
 7672:     my $classlist=&Apache::loncoursedata::get_classlist();
 7673:     my %idmap=&username_to_idmap($classlist);
 7674: 
 7675:     #get scantron line setup
 7676:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7677:     my ($scanlines,$scan_data)=&scantron_getfile();
 7678: 
 7679:     my $nav_error;
 7680:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
 7681:     if ($nav_error) {
 7682:         $r->print(&navmap_errormsg());
 7683:         return(1,$currentphase);
 7684:     }
 7685: 
 7686:     my %found=('ids'=>{},'usernames'=>{});
 7687:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7688: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7689: 	if ($line=~/^[\s\cz]*$/) { next; }
 7690: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7691: 						 $scan_data);
 7692: 	my $id=$$scan_record{'scantron.ID'};
 7693: 	my $found;
 7694: 	foreach my $checkid (keys(%idmap)) {
 7695: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 7696: 	}
 7697: 	if ($found) {
 7698: 	    my $username=$idmap{$found};
 7699: 	    if ($found{'ids'}{$found}) {
 7700: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7701: 					 $line,'duplicateID',$found);
 7702: 		return(1,$currentphase);
 7703: 	    } elsif ($found{'usernames'}{$username}) {
 7704: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7705: 					 $line,'duplicateID',$username);
 7706: 		return(1,$currentphase);
 7707: 	    }
 7708: 	    #FIXME store away line we previously saw the ID on to use above
 7709: 	    $found{'ids'}{$found}++;
 7710: 	    $found{'usernames'}{$username}++;
 7711: 	} else {
 7712: 	    if ($id =~ /^\s*$/) {
 7713: 		my $username=&scan_data($scan_data,"$i.user");
 7714: 		if (defined($username) && $found{'usernames'}{$username}) {
 7715: 		    &scantron_get_correction($r,$i,$scan_record,
 7716: 					     \%scantron_config,
 7717: 					     $line,'duplicateID',$username);
 7718: 		    return(1,$currentphase);
 7719: 		} elsif (!defined($username)) {
 7720: 		    &scantron_get_correction($r,$i,$scan_record,
 7721: 					     \%scantron_config,
 7722: 					     $line,'incorrectID');
 7723: 		    return(1,$currentphase);
 7724: 		}
 7725: 		$found{'usernames'}{$username}++;
 7726: 	    } else {
 7727: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7728: 					 $line,'incorrectID');
 7729: 		return(1,$currentphase);
 7730: 	    }
 7731: 	}
 7732:     }
 7733: 
 7734:     return (0,$currentphase+1);
 7735: }
 7736: 
 7737: 
 7738: sub scantron_get_correction {
 7739:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
 7740:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
 7741: #FIXME in the case of a duplicated ID the previous line, probably need
 7742: #to show both the current line and the previous one and allow skipping
 7743: #the previous one or the current one
 7744: 
 7745:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 7746:         $r->print(
 7747:             '<p class="LC_warning">'
 7748:            .&mt('An error was detected ([_1]) for PaperID [_2]',
 7749:                 "<b>$error</b>",
 7750:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
 7751:            ."</p> \n");
 7752:     } else {
 7753:         $r->print(
 7754:             '<p class="LC_warning">'
 7755:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
 7756:                 "<b>$error</b>", $i, "<pre>$line</pre>")
 7757:            ."</p> \n");
 7758:     }
 7759:     my $message =
 7760:         '<p>'
 7761:        .&mt('The ID on the form is [_1]',
 7762:             "<tt>$$scan_record{'scantron.ID'}</tt>")
 7763:        .'<br />'
 7764:        .&mt('The name on the paper is [_1], [_2]',
 7765:             $$scan_record{'scantron.LastName'},
 7766:             $$scan_record{'scantron.FirstName'})
 7767:        .'</p>';
 7768: 
 7769:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 7770:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 7771:                            # Array populated for doublebubble or
 7772:     my @lines_to_correct;  # missingbubble errors to build javascript
 7773:                            # to validate radio button checking   
 7774: 
 7775:     if ($error =~ /ID$/) {
 7776: 	if ($error eq 'incorrectID') {
 7777:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
 7778: 		      "</p>\n");
 7779: 	} elsif ($error eq 'duplicateID') {
 7780:             $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 7781: 	}
 7782: 	$r->print($message);
 7783: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 7784: 	$r->print("\n<ul><li> ");
 7785: 	#FIXME it would be nice if this sent back the user ID and
 7786: 	#could do partial userID matches
 7787: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 7788: 				       'scantron_username','scantron_domain'));
 7789: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 7790: 	$r->print("\n:\n".
 7791: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 7792: 
 7793: 	$r->print('</li>');
 7794:     } elsif ($error =~ /CODE$/) {
 7795: 	if ($error eq 'incorrectCODE') {
 7796: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 7797: 	} elsif ($error eq 'duplicateCODE') {
 7798: 	    $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");
 7799: 	}
 7800: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
 7801: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
 7802:                  ."</p>\n");
 7803: 	$r->print($message);
 7804: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
 7805: 	$r->print("\n<br /> ");
 7806: 	my $i=0;
 7807: 	if ($error eq 'incorrectCODE' 
 7808: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 7809: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 7810: 	    if ($closest > 0) {
 7811: 		foreach my $testcode (@{$closest}) {
 7812: 		    my $checked='';
 7813: 		    if (!$i) { $checked=' checked="checked"'; }
 7814: 		    $r->print("
 7815:    <label>
 7816:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 7817:        ".&mt("Use the similar CODE [_1] instead.",
 7818: 	    "<b><tt>".$testcode."</tt></b>")."
 7819:     </label>
 7820:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 7821: 		    $r->print("\n<br />");
 7822: 		    $i++;
 7823: 		}
 7824: 	    }
 7825: 	}
 7826: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 7827: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 7828: 	    $r->print("
 7829:     <label>
 7830:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 7831:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
 7832: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 7833:     </label>");
 7834: 	    $r->print("\n<br />");
 7835: 	}
 7836: 
 7837: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
 7838: function change_radio(field) {
 7839:     var slct=document.scantronupload.scantron_CODE_resolution;
 7840:     var i;
 7841:     for (i=0;i<slct.length;i++) {
 7842:         if (slct[i].value==field) { slct[i].checked=true; }
 7843:     }
 7844: }
 7845: ENDSCRIPT
 7846: 	my $href="/adm/pickcode?".
 7847: 	   "form=".&escape("scantronupload").
 7848: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 7849: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 7850: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 7851: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 7852: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 7853: 	    $r->print("
 7854:     <label>
 7855:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 7856:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 7857: 	     "<a target='_blank' href='$href'>","</a>")."
 7858:     </label> 
 7859:     ".&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\')" />'));
 7860: 	    $r->print("\n<br />");
 7861: 	}
 7862: 	$r->print("
 7863:     <label>
 7864:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 7865:        ".&mt("Use [_1] as the CODE.",
 7866: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 7867: 	$r->print("\n<br /><br />");
 7868:     } elsif ($error eq 'doublebubble') {
 7869: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 7870: 
 7871: 	# The form field scantron_questions is acutally a list of line numbers.
 7872: 	# represented by this form so:
 7873: 
 7874: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7875:                                                 $respnumlookup,$startline);
 7876: 
 7877: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7878: 		  $line_list.'" />');
 7879: 	$r->print($message);
 7880: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 7881: 	foreach my $question (@{$arg}) {
 7882: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7883:                                                    $scan_record, $error,
 7884:                                                    $randomorder,$randompick,
 7885:                                                    $respnumlookup,$startline);
 7886:             push(@lines_to_correct,@linenums);
 7887: 	}
 7888:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7889:     } elsif ($error eq 'missingbubble') {
 7890: 	$r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
 7891: 	$r->print($message);
 7892: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 7893: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 7894: 
 7895: 	# The form field scantron_questions is actually a list of line numbers not
 7896: 	# a list of question numbers. Therefore:
 7897: 	#
 7898: 
 7899: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7900:                                                 $respnumlookup,$startline);
 7901: 
 7902: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7903: 		  $line_list.'" />');
 7904: 	foreach my $question (@{$arg}) {
 7905: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7906:                                                    $scan_record, $error,
 7907:                                                    $randomorder,$randompick,
 7908:                                                    $respnumlookup,$startline);
 7909:             push(@lines_to_correct,@linenums);
 7910: 	}
 7911:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7912:     } else {
 7913: 	$r->print("\n<ul>");
 7914:     }
 7915:     $r->print("\n</li></ul>");
 7916: }
 7917: 
 7918: sub verify_bubbles_checked {
 7919:     my (@ansnums) = @_;
 7920:     my $ansnumstr = join('","',@ansnums);
 7921:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 7922:     &js_escape(\$warning);
 7923:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
 7924: function verify_bubble_radio(form) {
 7925:     var ansnumArray = new Array ("$ansnumstr");
 7926:     var need_bubble_count = 0;
 7927:     for (var i=0; i<ansnumArray.length; i++) {
 7928:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 7929:             var bubble_picked = 0; 
 7930:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 7931:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 7932:                     bubble_picked = 1;
 7933:                 }
 7934:             }
 7935:             if (bubble_picked == 0) {
 7936:                 need_bubble_count ++;
 7937:             }
 7938:         }
 7939:     }
 7940:     if (need_bubble_count) {
 7941:         alert("$warning");
 7942:         return;
 7943:     }
 7944:     form.submit(); 
 7945: }
 7946: ENDSCRIPT
 7947:     return $output;
 7948: }
 7949: 
 7950: =pod
 7951: 
 7952: =item  questions_to_line_list
 7953: 
 7954: Converts a list of questions into a string of comma separated
 7955: line numbers in the answer sheet used by the questions.  This is
 7956: used to fill in the scantron_questions form field.
 7957: 
 7958:   Arguments:
 7959:      questions    - Reference to an array of questions.
 7960:      randomorder  - True if randomorder in use.
 7961:      randompick   - True if randompick in use.
 7962:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
 7963:                      for current line to question number used for same question
 7964:                      in "Master Seqence" (as seen by Course Coordinator).
 7965:      startline    - Reference to hash where key is question number (0 is first)
 7966:                     and key is number of first bubble line for current student
 7967:                     or code-based randompick and/or randomorder.
 7968: 
 7969: =cut
 7970: 
 7971: 
 7972: sub questions_to_line_list {
 7973:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
 7974:     my @lines;
 7975: 
 7976:     foreach my $item (@{$questions}) {
 7977:         my $question = $item;
 7978:         my ($first,$count,$last);
 7979:         if ($item =~ /^(\d+)\.(\d+)$/) {
 7980:             $question = $1;
 7981:             my $subquestion = $2;
 7982:             my $responsenum = $question-1;
 7983:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7984:                 $responsenum = $respnumlookup->{$question-1};
 7985:                 if (ref($startline) eq 'HASH') {
 7986:                     $first = $startline->{$question-1} + 1;
 7987:                 }
 7988:             } else {
 7989:                 $first = $first_bubble_line{$responsenum} + 1;
 7990:             }
 7991:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 7992:             my $subcount = 1;
 7993:             while ($subcount<$subquestion) {
 7994:                 $first += $subans[$subcount-1];
 7995:                 $subcount ++;
 7996:             }
 7997:             $count = $subans[$subquestion-1];
 7998:         } else {
 7999:             my $responsenum = $question-1;
 8000:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8001:                 $responsenum = $respnumlookup->{$question-1};
 8002:                 if (ref($startline) eq 'HASH') {
 8003:                     $first = $startline->{$question-1} + 1;
 8004:                 }
 8005:             } else {
 8006:                 $first = $first_bubble_line{$responsenum} + 1;
 8007:             }
 8008: 	    $count   = $bubble_lines_per_response{$responsenum};
 8009:         }
 8010:         $last = $first+$count-1;
 8011:         push(@lines, ($first..$last));
 8012:     }
 8013:     return join(',', @lines);
 8014: }
 8015: 
 8016: =pod 
 8017: 
 8018: =item prompt_for_corrections
 8019: 
 8020: Prompts for a potentially multiline correction to the
 8021: user's bubbling (factors out common code from scantron_get_correction
 8022: for multi and missing bubble cases).
 8023: 
 8024:  Arguments:
 8025:    $r           - Apache request object.
 8026:    $question    - The question number to prompt for.
 8027:    $scan_config - The scantron file configuration hash.
 8028:    $scan_record - Reference to the hash that has the the parsed scanlines.
 8029:    $error       - Type of error
 8030:    $randomorder - True if randomorder in use.
 8031:    $randompick  - True if randompick in use.
 8032:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
 8033:                     for current line to question number used for same question
 8034:                     in "Master Seqence" (as seen by Course Coordinator).
 8035:    $startline   - Reference to hash where key is question number (0 is first)
 8036:                   and value is number of first bubble line for current student
 8037:                   or code-based randompick and/or randomorder.
 8038: 
 8039: 
 8040:  Implicit inputs:
 8041:    %bubble_lines_per_response   - Starting line numbers for each question.
 8042:                                   Numbered from 0 (but question numbers are from
 8043:                                   1.
 8044:    %first_bubble_line           - Starting bubble line for each question.
 8045:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 8046:                                   type problems render as separate sub-questions, 
 8047:                                   in exam mode. This hash contains a 
 8048:                                   comma-separated list of the lines per 
 8049:                                   sub-question.
 8050:    %responsetype_per_response   - essayresponse, formularesponse,
 8051:                                   stringresponse, imageresponse, reactionresponse,
 8052:                                   and organicresponse type problem parts can have
 8053:                                   multiple lines per response if the weight
 8054:                                   assigned exceeds 10.  In this case, only
 8055:                                   one bubble per line is permitted, but more 
 8056:                                   than one line might contain bubbles, e.g.
 8057:                                   bubbling of: line 1 - J, line 2 - J, 
 8058:                                   line 3 - B would assign 22 points.  
 8059: 
 8060: =cut
 8061: 
 8062: sub prompt_for_corrections {
 8063:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
 8064:         $randompick, $respnumlookup, $startline) = @_;
 8065:     my ($current_line,$lines);
 8066:     my @linenums;
 8067:     my $questionnum = $question;
 8068:     my ($first,$responsenum);
 8069:     if ($question =~ /^(\d+)\.(\d+)$/) {
 8070:         $question = $1;
 8071:         my $subquestion = $2;
 8072:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8073:             $responsenum = $respnumlookup->{$question-1};
 8074:             if (ref($startline) eq 'HASH') {
 8075:                 $first = $startline->{$question-1};
 8076:             }
 8077:         } else {
 8078:             $responsenum = $question-1;
 8079:             $first = $first_bubble_line{$responsenum};
 8080:         }
 8081:         $current_line = $first + 1 ;
 8082:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8083:         my $subcount = 1;
 8084:         while ($subcount<$subquestion) {
 8085:             $current_line += $subans[$subcount-1];
 8086:             $subcount ++;
 8087:         }
 8088:         $lines = $subans[$subquestion-1];
 8089:     } else {
 8090:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8091:             $responsenum = $respnumlookup->{$question-1};
 8092:             if (ref($startline) eq 'HASH') { 
 8093:                 $first = $startline->{$question-1};
 8094:             }
 8095:         } else {
 8096:             $responsenum = $question-1;
 8097:             $first = $first_bubble_line{$responsenum};
 8098:         }
 8099:         $current_line = $first + 1;
 8100:         $lines        = $bubble_lines_per_response{$responsenum};
 8101:     }
 8102:     if ($lines > 1) {
 8103:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 8104:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 8105:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 8106:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 8107:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 8108:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 8109:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 8110:             $r->print(
 8111:                 &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)
 8112:                .'<br /><br />'
 8113:                .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
 8114:                .'<br />'
 8115:                .&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.')
 8116:                .'<br />'
 8117:                .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
 8118:                .'<br /><br />'
 8119:             );
 8120:         } else {
 8121:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 8122:         }
 8123:     }
 8124:     for (my $i =0; $i < $lines; $i++) {
 8125:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 8126: 	&scantron_bubble_selector($r,$scan_config,$current_line,
 8127: 	        		  $questionnum,$error,split('', $selected));
 8128:         push(@linenums,$current_line);
 8129: 	$current_line++;
 8130:     }
 8131:     if ($lines > 1) {
 8132: 	$r->print("<hr /><br />");
 8133:     }
 8134:     return @linenums;
 8135: }
 8136: 
 8137: =pod
 8138: 
 8139: =item scantron_bubble_selector
 8140:   
 8141:    Generates the html radiobuttons to correct a single bubble line
 8142:    possibly showing the existing the selected bubbles if known
 8143: 
 8144:  Arguments:
 8145:     $r           - Apache request object
 8146:     $scan_config - hash from &get_scantron_config()
 8147:     $line        - Number of the line being displayed.
 8148:     $questionnum - Question number (may include subquestion)
 8149:     $error       - Type of error.
 8150:     @selected    - Array of bubbles picked on this line.
 8151: 
 8152: =cut
 8153: 
 8154: sub scantron_bubble_selector {
 8155:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 8156:     my $max=$$scan_config{'Qlength'};
 8157: 
 8158:     my $scmode=$$scan_config{'Qon'};
 8159:     if ($scmode eq 'number' || $scmode eq 'letter') { 
 8160:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
 8161:             ($$scan_config{'BubblesPerRow'} > 0)) {
 8162:             $max=$$scan_config{'BubblesPerRow'};
 8163:             if (($scmode eq 'number') && ($max > 10)) {
 8164:                 $max = 10;
 8165:             } elsif (($scmode eq 'letter') && $max > 26) {
 8166:                 $max = 26;
 8167:             }
 8168:         } else {
 8169:             $max = 10;
 8170:         }
 8171:     }
 8172: 
 8173:     my @alphabet=('A'..'Z');
 8174:     $r->print(&Apache::loncommon::start_data_table().
 8175:               &Apache::loncommon::start_data_table_row());
 8176:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 8177:     for (my $i=0;$i<$max+1;$i++) {
 8178: 	$r->print("\n".'<td align="center">');
 8179: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 8180: 	else { $r->print('&nbsp;'); }
 8181: 	$r->print('</td>');
 8182:     }
 8183:     $r->print(&Apache::loncommon::end_data_table_row().
 8184:               &Apache::loncommon::start_data_table_row());
 8185:     for (my $i=0;$i<$max;$i++) {
 8186: 	$r->print("\n".
 8187: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 8188: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 8189:     }
 8190:     my $nobub_checked = ' ';
 8191:     if ($error eq 'missingbubble') {
 8192:         $nobub_checked = ' checked = "checked" ';
 8193:     }
 8194:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 8195: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 8196:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 8197:               $line.'" value="'.$questionnum.'" /></td>');
 8198:     $r->print(&Apache::loncommon::end_data_table_row().
 8199:               &Apache::loncommon::end_data_table());
 8200: }
 8201: 
 8202: =pod
 8203: 
 8204: =item num_matches
 8205: 
 8206:    Counts the number of characters that are the same between the two arguments.
 8207: 
 8208:  Arguments:
 8209:    $orig - CODE from the scanline
 8210:    $code - CODE to match against
 8211: 
 8212:  Returns:
 8213:    $count - integer count of the number of same characters between the
 8214:             two arguments
 8215: 
 8216: =cut
 8217: 
 8218: sub num_matches {
 8219:     my ($orig,$code) = @_;
 8220:     my @code=split(//,$code);
 8221:     my @orig=split(//,$orig);
 8222:     my $same=0;
 8223:     for (my $i=0;$i<scalar(@code);$i++) {
 8224: 	if ($code[$i] eq $orig[$i]) { $same++; }
 8225:     }
 8226:     return $same;
 8227: }
 8228: 
 8229: =pod
 8230: 
 8231: =item scantron_get_closely_matching_CODEs
 8232: 
 8233:    Cycles through all CODEs and finds the set that has the greatest
 8234:    number of same characters as the provided CODE
 8235: 
 8236:  Arguments:
 8237:    $allcodes - hash ref returned by &get_codes()
 8238:    $CODE     - CODE from the current scanline
 8239: 
 8240:  Returns:
 8241:    2 element list
 8242:     - first elements is number of how closely matching the best fit is 
 8243:       (5 means best set has 5 matching characters)
 8244:     - second element is an arrary ref containing the set of valid CODEs
 8245:       that best fit the passed in CODE
 8246: 
 8247: =cut
 8248: 
 8249: sub scantron_get_closely_matching_CODEs {
 8250:     my ($allcodes,$CODE)=@_;
 8251:     my @CODEs;
 8252:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 8253: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 8254:     }
 8255: 
 8256:     return ($#CODEs,$CODEs[-1]);
 8257: }
 8258: 
 8259: =pod
 8260: 
 8261: =item get_codes
 8262: 
 8263:    Builds a hash which has keys of all of the valid CODEs from the selected
 8264:    set of remembered CODEs.
 8265: 
 8266:  Arguments:
 8267:   $old_name - name of the set of remembered CODEs
 8268:   $cdom     - domain of the course
 8269:   $cnum     - internal course name
 8270: 
 8271:  Returns:
 8272:   %allcodes - keys are the valid CODEs, values are all 1
 8273: 
 8274: =cut
 8275: 
 8276: sub get_codes {
 8277:     my ($old_name, $cdom, $cnum) = @_;
 8278:     if (!$old_name) {
 8279: 	$old_name=$env{'form.scantron_CODElist'};
 8280:     }
 8281:     if (!$cdom) {
 8282: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 8283:     }
 8284:     if (!$cnum) {
 8285: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 8286:     }
 8287:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 8288: 				    $cdom,$cnum);
 8289:     my %allcodes;
 8290:     if ($result{"type\0$old_name"} eq 'number') {
 8291: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 8292:     } else {
 8293: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 8294:     }
 8295:     return %allcodes;
 8296: }
 8297: 
 8298: =pod
 8299: 
 8300: =item scantron_validate_CODE
 8301: 
 8302:    Validates all scanlines in the selected file to not have any
 8303:    invalid or underspecified CODEs and that none of the codes are
 8304:    duplicated if this was requested.
 8305: 
 8306: =cut
 8307: 
 8308: sub scantron_validate_CODE {
 8309:     my ($r,$currentphase) = @_;
 8310:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8311:     if ($scantron_config{'CODElocation'} &&
 8312: 	$scantron_config{'CODEstart'} &&
 8313: 	$scantron_config{'CODElength'}) {
 8314: 	if (!defined($env{'form.scantron_CODElist'})) {
 8315: 	    &FIXME_blow_up()
 8316: 	}
 8317:     } else {
 8318: 	return (0,$currentphase+1);
 8319:     }
 8320:     
 8321:     my %usedCODEs;
 8322: 
 8323:     my %allcodes=&get_codes();
 8324: 
 8325:     my $nav_error;
 8326:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
 8327:     if ($nav_error) {
 8328:         $r->print(&navmap_errormsg());
 8329:         return(1,$currentphase);
 8330:     }
 8331: 
 8332:     my ($scanlines,$scan_data)=&scantron_getfile();
 8333:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8334: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8335: 	if ($line=~/^[\s\cz]*$/) { next; }
 8336: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8337: 						 $scan_data);
 8338: 	my $CODE=$$scan_record{'scantron.CODE'};
 8339: 	my $error=0;
 8340: 	if (!&Apache::lonnet::validCODE($CODE)) {
 8341: 	    &scantron_get_correction($r,$i,$scan_record,
 8342: 				     \%scantron_config,
 8343: 				     $line,'incorrectCODE',\%allcodes);
 8344: 	    return(1,$currentphase);
 8345: 	}
 8346: 	if (%allcodes && !exists($allcodes{$CODE}) 
 8347: 	    && !$$scan_record{'scantron.useCODE'}) {
 8348: 	    &scantron_get_correction($r,$i,$scan_record,
 8349: 				     \%scantron_config,
 8350: 				     $line,'incorrectCODE',\%allcodes);
 8351: 	    return(1,$currentphase);
 8352: 	}
 8353: 	if (exists($usedCODEs{$CODE}) 
 8354: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 8355: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 8356: 	    &scantron_get_correction($r,$i,$scan_record,
 8357: 				     \%scantron_config,
 8358: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 8359: 	    return(1,$currentphase);
 8360: 	}
 8361: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 8362:     }
 8363:     return (0,$currentphase+1);
 8364: }
 8365: 
 8366: =pod
 8367: 
 8368: =item scantron_validate_doublebubble
 8369: 
 8370:    Validates all scanlines in the selected file to not have any
 8371:    bubble lines with multiple bubbles marked.
 8372: 
 8373: =cut
 8374: 
 8375: sub scantron_validate_doublebubble {
 8376:     my ($r,$currentphase) = @_;
 8377:     #get student info
 8378:     my $classlist=&Apache::loncoursedata::get_classlist();
 8379:     my %idmap=&username_to_idmap($classlist);
 8380:     my (undef,undef,$sequence)=
 8381:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8382: 
 8383:     #get scantron line setup
 8384:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8385:     my ($scanlines,$scan_data)=&scantron_getfile();
 8386: 
 8387:     my $navmap = Apache::lonnavmaps::navmap->new();
 8388:     unless (ref($navmap)) {
 8389:         $r->print(&navmap_errormsg());
 8390:         return(1,$currentphase);
 8391:     }
 8392:     my $map=$navmap->getResourceByUrl($sequence);
 8393:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8394:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8395:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8396:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8397: 
 8398:     my $nav_error;
 8399:     if (ref($map)) {
 8400:         $randomorder = $map->randomorder();
 8401:         $randompick = $map->randompick();
 8402:         if ($randomorder || $randompick) {
 8403:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8404:             if ($nav_error) {
 8405:                 $r->print(&navmap_errormsg());
 8406:                 return(1,$currentphase);
 8407:             }
 8408:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8409:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8410:         }
 8411:     } else {
 8412:         $r->print(&navmap_errormsg());
 8413:         return(1,$currentphase);
 8414:     }
 8415: 
 8416:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
 8417:     if ($nav_error) {
 8418:         $r->print(&navmap_errormsg());
 8419:         return(1,$currentphase);
 8420:     }
 8421: 
 8422:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8423: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8424: 	if ($line=~/^[\s\cz]*$/) { next; }
 8425: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8426: 						 $scan_data,undef,\%idmap,$randomorder,
 8427:                                                  $randompick,$sequence,\@master_seq,
 8428:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8429:                                                  \%orderedforcode,\%respnumlookup,\%startline);
 8430: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 8431: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 8432: 				 'doublebubble',
 8433: 				 $$scan_record{'scantron.doubleerror'},
 8434:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
 8435:     	return (1,$currentphase);
 8436:     }
 8437:     return (0,$currentphase+1);
 8438: }
 8439: 
 8440: 
 8441: sub scantron_get_maxbubble {
 8442:     my ($nav_error,$scantron_config) = @_;
 8443:     if (defined($env{'form.scantron_maxbubble'}) &&
 8444: 	$env{'form.scantron_maxbubble'}) {
 8445: 	&restore_bubble_lines();
 8446: 	return $env{'form.scantron_maxbubble'};
 8447:     }
 8448: 
 8449:     my (undef, undef, $sequence) =
 8450: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8451: 
 8452:     my $navmap=Apache::lonnavmaps::navmap->new();
 8453:     unless (ref($navmap)) {
 8454:         if (ref($nav_error)) {
 8455:             $$nav_error = 1;
 8456:         }
 8457:         return;
 8458:     }
 8459:     my $map=$navmap->getResourceByUrl($sequence);
 8460:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8461:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
 8462: 
 8463:     &Apache::lonxml::clear_problem_counter();
 8464: 
 8465:     my $uname       = $env{'user.name'};
 8466:     my $udom        = $env{'user.domain'};
 8467:     my $cid         = $env{'request.course.id'};
 8468:     my $total_lines = 0;
 8469:     %bubble_lines_per_response = ();
 8470:     %first_bubble_line         = ();
 8471:     %subdivided_bubble_lines   = ();
 8472:     %responsetype_per_response = ();
 8473:     %masterseq_id_responsenum  = ();
 8474: 
 8475:     my $response_number = 0;
 8476:     my $bubble_line     = 0;
 8477:     foreach my $resource (@resources) {
 8478:         my $resid = $resource->id(); 
 8479:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
 8480:                                                           $udom,undef,$bubbles_per_row);
 8481:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 8482: 	    foreach my $part_id (@{$parts}) {
 8483:                 my $lines;
 8484: 
 8485: 	        # TODO - make this a persistent hash not an array.
 8486: 
 8487:                 # optionresponse, matchresponse and rankresponse type items 
 8488:                 # render as separate sub-questions in exam mode.
 8489:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 8490:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 8491:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 8492:                     my ($numbub,$numshown);
 8493:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 8494:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 8495:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 8496:                         }
 8497:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 8498:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 8499:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 8500:                         }
 8501:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 8502:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 8503:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 8504:                         }
 8505:                     }
 8506:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 8507:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 8508:                     }
 8509:                     my $bubbles_per_row =
 8510:                         &bubblesheet_bubbles_per_row($scantron_config);
 8511:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
 8512:                     if (($numbub % $bubbles_per_row) != 0) {
 8513:                         $inner_bubble_lines++;
 8514:                     }
 8515:                     for (my $i=0; $i<$numshown; $i++) {
 8516:                         $subdivided_bubble_lines{$response_number} .= 
 8517:                             $inner_bubble_lines.',';
 8518:                     }
 8519:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 8520:                     $lines = $numshown * $inner_bubble_lines;
 8521:                 } else {
 8522:                     $lines = $analysis->{"$part_id.bubble_lines"};
 8523:                 }
 8524: 
 8525:                 $first_bubble_line{$response_number} = $bubble_line;
 8526: 	        $bubble_lines_per_response{$response_number} = $lines;
 8527:                 $responsetype_per_response{$response_number} = 
 8528:                     $analysis->{$part_id.'.type'};
 8529:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;  
 8530: 	        $response_number++;
 8531: 
 8532: 	        $bubble_line +=  $lines;
 8533: 	        $total_lines +=  $lines;
 8534: 	    }
 8535:         }
 8536:     }
 8537:     &Apache::lonnet::delenv('scantron.');
 8538: 
 8539:     &save_bubble_lines();
 8540:     $env{'form.scantron_maxbubble'} =
 8541: 	$total_lines;
 8542:     return $env{'form.scantron_maxbubble'};
 8543: }
 8544: 
 8545: sub bubblesheet_bubbles_per_row {
 8546:     my ($scantron_config) = @_;
 8547:     my $bubbles_per_row;
 8548:     if (ref($scantron_config) eq 'HASH') {
 8549:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
 8550:     }
 8551:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
 8552:         $bubbles_per_row = 10;
 8553:     }
 8554:     return $bubbles_per_row;
 8555: }
 8556: 
 8557: sub scantron_validate_missingbubbles {
 8558:     my ($r,$currentphase) = @_;
 8559:     #get student info
 8560:     my $classlist=&Apache::loncoursedata::get_classlist();
 8561:     my %idmap=&username_to_idmap($classlist);
 8562:     my (undef,undef,$sequence)=
 8563:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8564: 
 8565:     #get scantron line setup
 8566:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8567:     my ($scanlines,$scan_data)=&scantron_getfile();
 8568: 
 8569:     my $navmap = Apache::lonnavmaps::navmap->new();
 8570:     unless (ref($navmap)) {
 8571:         $r->print(&navmap_errormsg());
 8572:         return(1,$currentphase);
 8573:     }
 8574: 
 8575:     my $map=$navmap->getResourceByUrl($sequence);
 8576:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8577:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8578:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8579:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8580: 
 8581:     my $nav_error;
 8582:     if (ref($map)) {
 8583:         $randomorder = $map->randomorder();
 8584:         $randompick = $map->randompick();
 8585:         if ($randomorder || $randompick) {
 8586:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8587:             if ($nav_error) {
 8588:                 $r->print(&navmap_errormsg());
 8589:                 return(1,$currentphase);
 8590:             }
 8591:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8592:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8593:         }
 8594:     } else {
 8595:         $r->print(&navmap_errormsg());
 8596:         return(1,$currentphase);
 8597:     }
 8598: 
 8599: 
 8600:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 8601:     if ($nav_error) {
 8602:         $r->print(&navmap_errormsg());
 8603:         return(1,$currentphase);
 8604:     }
 8605: 
 8606:     if (!$max_bubble) { $max_bubble=2**31; }
 8607:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8608: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8609: 	if ($line=~/^[\s\cz]*$/) { next; }
 8610: 	my $scan_record =
 8611:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
 8612: 				     $randomorder,$randompick,$sequence,\@master_seq,
 8613:                                      \%symb_to_resource,\%grader_partids_by_symb,
 8614:                                      \%orderedforcode,\%respnumlookup,\%startline);
 8615: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 8616: 	my @to_correct;
 8617: 	
 8618: 	# Probably here's where the error is...
 8619: 
 8620: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 8621:             my $lastbubble;
 8622:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 8623:                my $question = $1;
 8624:                my $subquestion = $2;
 8625:                my ($first,$responsenum);
 8626:                if ($randomorder || $randompick) {
 8627:                    $responsenum = $respnumlookup{$question-1};
 8628:                    $first = $startline{$question-1};
 8629:                } else {
 8630:                    $responsenum = $question-1; 
 8631:                    $first = $first_bubble_line{$responsenum};
 8632:                }
 8633:                if (!defined($first)) { next; }
 8634:                my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8635:                my $subcount = 1;
 8636:                while ($subcount<$subquestion) {
 8637:                    $first += $subans[$subcount-1];
 8638:                    $subcount ++;
 8639:                }
 8640:                my $count = $subans[$subquestion-1];
 8641:                $lastbubble = $first + $count;
 8642:             } else {
 8643:                my ($first,$responsenum);
 8644:                if ($randomorder || $randompick) {
 8645:                    $responsenum = $respnumlookup{$missing-1};
 8646:                    $first = $startline{$missing-1};
 8647:                } else {
 8648:                    $responsenum = $missing-1;
 8649:                    $first = $first_bubble_line{$responsenum};
 8650:                }
 8651:                if (!defined($first)) { next; }
 8652:                $lastbubble = $first + $bubble_lines_per_response{$responsenum};
 8653:             }
 8654:             if ($lastbubble > $max_bubble) { next; }
 8655: 	    push(@to_correct,$missing);
 8656: 	}
 8657: 	if (@to_correct) {
 8658: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 8659: 				     $line,'missingbubble',\@to_correct,
 8660:                                      $randomorder,$randompick,\%respnumlookup,
 8661:                                      \%startline);
 8662: 	    return (1,$currentphase);
 8663: 	}
 8664: 
 8665:     }
 8666:     return (0,$currentphase+1);
 8667: }
 8668: 
 8669: sub hand_bubble_option {
 8670:     my (undef, undef, $sequence) =
 8671:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8672:     return if ($sequence eq '');
 8673:     my $navmap = Apache::lonnavmaps::navmap->new();
 8674:     unless (ref($navmap)) {
 8675:         return;
 8676:     }
 8677:     my $needs_hand_bubbles;
 8678:     my $map=$navmap->getResourceByUrl($sequence);
 8679:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8680:     foreach my $res (@resources) {
 8681:         if (ref($res)) {
 8682:             if ($res->is_problem()) {
 8683:                 my $partlist = $res->parts();
 8684:                 foreach my $part (@{ $partlist }) {
 8685:                     my @types = $res->responseType($part);
 8686:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
 8687:                         $needs_hand_bubbles = 1;
 8688:                         last;
 8689:                     }
 8690:                 }
 8691:             }
 8692:         }
 8693:     }
 8694:     if ($needs_hand_bubbles) {
 8695:         my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8696:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8697:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
 8698:                &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 />').
 8699:                '<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;'.
 8700:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
 8701:     }
 8702:     return;
 8703: }
 8704: 
 8705: sub scantron_process_students {
 8706:     my ($r,$symb) = @_;
 8707: 
 8708:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8709:     if (!$symb) {
 8710: 	return '';
 8711:     }
 8712:     my $default_form_data=&defaultFormData($symb);
 8713: 
 8714:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8715:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config); 
 8716:     my ($scanlines,$scan_data)=&scantron_getfile();
 8717:     my $classlist=&Apache::loncoursedata::get_classlist();
 8718:     my %idmap=&username_to_idmap($classlist);
 8719:     my $navmap=Apache::lonnavmaps::navmap->new();
 8720:     unless (ref($navmap)) {
 8721:         $r->print(&navmap_errormsg());
 8722:         return '';
 8723:     }
 8724:     my $map=$navmap->getResourceByUrl($sequence);
 8725:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8726:         %grader_randomlists_by_symb);
 8727:     if (ref($map)) {
 8728:         $randomorder = $map->randomorder();
 8729:         $randompick = $map->randompick();
 8730:     } else {
 8731:         $r->print(&navmap_errormsg());
 8732:         return '';
 8733:     }
 8734:     my $nav_error;
 8735:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8736:     if ($randomorder || $randompick) {
 8737:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8738:         if ($nav_error) {
 8739:             $r->print(&navmap_errormsg());
 8740:             return '';
 8741:         }
 8742:     }
 8743:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8744:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 8745: 
 8746:     my ($uname,$udom);
 8747:     my $result= <<SCANTRONFORM;
 8748: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 8749:   <input type="hidden" name="command" value="scantron_configphase" />
 8750:   $default_form_data
 8751: SCANTRONFORM
 8752:     $r->print($result);
 8753: 
 8754:     my @delayqueue;
 8755:     my (%completedstudents,%scandata);
 8756:     
 8757:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 8758:     my $count=&get_todo_count($scanlines,$scan_data);
 8759:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 8760:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
 8761:     $r->print('<br />');
 8762:     my $start=&Time::HiRes::time();
 8763:     my $i=-1;
 8764:     my $started;
 8765: 
 8766:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 8767:     if ($nav_error) {
 8768:         $r->print(&navmap_errormsg());
 8769:         return '';
 8770:     }
 8771: 
 8772:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 8773:     # the user and return.
 8774: 
 8775:     if ($ssi_error) {
 8776: 	$r->print("</form>");
 8777: 	&ssi_print_error($r);
 8778:         &Apache::lonnet::remove_lock($lock);
 8779: 	return '';		# Dunno why the other returns return '' rather than just returning.
 8780:     }
 8781: 
 8782:     my %lettdig = &letter_to_digits();
 8783:     my $numletts = scalar(keys(%lettdig));
 8784:     my %orderedforcode;
 8785: 
 8786:     while ($i<$scanlines->{'count'}) {
 8787:  	($uname,$udom)=('','');
 8788:  	$i++;
 8789:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8790:  	if ($line=~/^[\s\cz]*$/) { next; }
 8791: 	if ($started) {
 8792: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 8793: 	}
 8794: 	$started=1;
 8795:         my %respnumlookup = ();
 8796:         my %startline = ();
 8797:         my $total;
 8798:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8799:                                                  $scan_data,undef,\%idmap,$randomorder,
 8800:                                                  $randompick,$sequence,\@master_seq,
 8801:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8802:                                                  \%orderedforcode,\%respnumlookup,\%startline,
 8803:                                                  \$total);
 8804:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 8805:  					      \%idmap,$i)) {
 8806:   	    &scantron_add_delay(\@delayqueue,$line,
 8807:  				'Unable to find a student that matches',1);
 8808:  	    next;
 8809:   	}
 8810:  	if (exists $completedstudents{$uname}) {
 8811:  	    &scantron_add_delay(\@delayqueue,$line,
 8812:  				'Student '.$uname.' has multiple sheets',2);
 8813:  	    next;
 8814:  	}
 8815:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 8816:         my $user = $uname.':'.$usec;
 8817:   	($uname,$udom)=split(/:/,$uname);
 8818: 
 8819:         my $scancode;
 8820:         if ((exists($scan_record->{'scantron.CODE'})) &&
 8821:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 8822:             $scancode = $scan_record->{'scantron.CODE'};
 8823:         } else {
 8824:             $scancode = '';
 8825:         }
 8826: 
 8827:         my @mapresources = @resources;
 8828:         if ($randomorder || $randompick) {
 8829:             @mapresources = 
 8830:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 8831:                              \%orderedforcode);
 8832:         }
 8833:         my (%partids_by_symb,$res_error);
 8834:         foreach my $resource (@mapresources) {
 8835:             my $ressymb;
 8836:             if (ref($resource)) {
 8837:                 $ressymb = $resource->symb();
 8838:             } else {
 8839:                 $res_error = 1;
 8840:                 last;
 8841:             }
 8842:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8843:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8844:                 my $currcode;
 8845:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
 8846:                     $currcode = $scancode;
 8847:                 }
 8848:                 my ($analysis,$parts) =
 8849:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 8850:                                               $uname,$udom,undef,$bubbles_per_row,
 8851:                                               $currcode);
 8852:                 $partids_by_symb{$ressymb} = $parts;
 8853:             } else {
 8854:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 8855:             }
 8856:         }
 8857: 
 8858:         if ($res_error) {
 8859:             &scantron_add_delay(\@delayqueue,$line,
 8860:                                 'An error occurred while grading student '.$uname,2);
 8861:             next;
 8862:         }
 8863: 
 8864: 	&Apache::lonxml::clear_problem_counter();
 8865:   	&Apache::lonnet::appenv($scan_record);
 8866: 
 8867: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 8868: 	    &scantron_putfile($scanlines,$scan_data);
 8869: 	}
 8870: 	
 8871:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8872:                                    \@mapresources,\%partids_by_symb,
 8873:                                    $bubbles_per_row,$randomorder,$randompick,
 8874:                                    \%respnumlookup,\%startline) 
 8875:             eq 'ssi_error') {
 8876:             $ssi_error = 0; # So end of handler error message does not trigger.
 8877:             $r->print("</form>");
 8878:             &ssi_print_error($r);
 8879:             &Apache::lonnet::remove_lock($lock);
 8880:             return '';      # Why return ''?  Beats me.
 8881:         }
 8882: 
 8883:         if (($scancode) && ($randomorder || $randompick)) {
 8884:             my $parmresult =
 8885:                 &Apache::lonparmset::storeparm_by_symb($symb,
 8886:                                                        '0_examcode',2,$scancode,
 8887:                                                        'string_examcode',$uname,
 8888:                                                        $udom);
 8889:         }
 8890: 	$completedstudents{$uname}={'line'=>$line};
 8891:         if ($env{'form.verifyrecord'}) {
 8892:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8893:             if ($randompick) {
 8894:                 if ($total) {
 8895:                     $lastpos = $total*$scantron_config{'Qlength'};
 8896:                 }
 8897:             }
 8898: 
 8899:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8900:             chomp($studentdata);
 8901:             $studentdata =~ s/\r$//;
 8902:             my $studentrecord = '';
 8903:             my $counter = -1;
 8904:             foreach my $resource (@mapresources) {
 8905:                 my $ressymb = $resource->symb();
 8906:                 ($counter,my $recording) =
 8907:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8908:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 8909:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
 8910:                                              $randompick,\%respnumlookup,\%startline);
 8911:                 $studentrecord .= $recording;
 8912:             }
 8913:             if ($studentrecord ne $studentdata) {
 8914:                 &Apache::lonxml::clear_problem_counter();
 8915:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8916:                                            \@mapresources,\%partids_by_symb,
 8917:                                            $bubbles_per_row,$randomorder,$randompick,
 8918:                                            \%respnumlookup,\%startline) 
 8919:                     eq 'ssi_error') {
 8920:                     $ssi_error = 0; # So end of handler error message does not trigger.
 8921:                     $r->print("</form>");
 8922:                     &ssi_print_error($r);
 8923:                     &Apache::lonnet::remove_lock($lock);
 8924:                     delete($completedstudents{$uname});
 8925:                     return '';
 8926:                 }
 8927:                 $counter = -1;
 8928:                 $studentrecord = '';
 8929:                 foreach my $resource (@mapresources) {
 8930:                     my $ressymb = $resource->symb();
 8931:                     ($counter,my $recording) =
 8932:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8933:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 8934:                                                  \%scantron_config,\%lettdig,$numletts,
 8935:                                                  $randomorder,$randompick,\%respnumlookup,
 8936:                                                  \%startline);
 8937:                     $studentrecord .= $recording;
 8938:                 }
 8939:                 if ($studentrecord ne $studentdata) {
 8940:                     $r->print('<p><span class="LC_warning">');
 8941:                     if ($scancode eq '') {
 8942:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
 8943:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 8944:                     } else {
 8945:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
 8946:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 8947:                     }
 8948:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 8949:                               &Apache::loncommon::start_data_table_header_row()."\n".
 8950:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 8951:                               &Apache::loncommon::end_data_table_header_row()."\n".
 8952:                               &Apache::loncommon::start_data_table_row().
 8953:                               '<td>'.&mt('Bubblesheet').'</td>'.
 8954:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
 8955:                               &Apache::loncommon::end_data_table_row().
 8956:                               &Apache::loncommon::start_data_table_row().
 8957:                               '<td>'.&mt('Stored submissions').'</td>'.
 8958:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
 8959:                               &Apache::loncommon::end_data_table_row().
 8960:                               &Apache::loncommon::end_data_table().'</p>');
 8961:                 } else {
 8962:                     $r->print('<br /><span class="LC_warning">'.
 8963:                              &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 />'.
 8964:                              &mt("As a consequence, this user's submission history records two tries.").
 8965:                                  '</span><br />');
 8966:                 }
 8967:             }
 8968:         }
 8969:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 8970:     } continue {
 8971: 	&Apache::lonxml::clear_problem_counter();
 8972: 	&Apache::lonnet::delenv('scantron.');
 8973:     }
 8974:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8975:     &Apache::lonnet::remove_lock($lock);
 8976: #    my $lasttime = &Time::HiRes::time()-$start;
 8977: #    $r->print("<p>took $lasttime</p>");
 8978: 
 8979:     $r->print("</form>");
 8980:     return '';
 8981: }
 8982: 
 8983: sub graders_resources_pass {
 8984:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
 8985:         $bubbles_per_row) = @_;
 8986:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 8987:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 8988:         foreach my $resource (@{$resources}) {
 8989:             my $ressymb = $resource->symb();
 8990:             my ($analysis,$parts) =
 8991:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 8992:                                           $env{'user.name'},$env{'user.domain'},
 8993:                                           1,$bubbles_per_row);
 8994:             $grader_partids_by_symb->{$ressymb} = $parts;
 8995:             if (ref($analysis) eq 'HASH') {
 8996:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 8997:                     $grader_randomlists_by_symb->{$ressymb} =
 8998:                         $analysis->{'parts_withrandomlist'};
 8999:                 }
 9000:             }
 9001:         }
 9002:     }
 9003:     return;
 9004: }
 9005: 
 9006: =pod
 9007: 
 9008: =item users_order
 9009: 
 9010:   Returns array of resources in current map, ordered based on either CODE,
 9011:   if this is a CODEd exam, or based on student's identity if this is a 
 9012:   "NAMEd" exam.
 9013: 
 9014:   Should be used when randomorder and/or randompick applied when the 
 9015:   corresponding exam was printed, prior to students completing bubblesheets 
 9016:   for the version of the exam the student received.
 9017: 
 9018: =cut
 9019: 
 9020: sub users_order  {
 9021:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
 9022:     my @mapresources;
 9023:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
 9024:         return @mapresources;
 9025:     }
 9026:     if ($scancode) {
 9027:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
 9028:             @mapresources = @{$orderedforcode->{$scancode}};
 9029:         } else {
 9030:             $env{'form.CODE'} = $scancode;
 9031:             my $actual_seq =
 9032:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 9033:                                                                $master_seq,
 9034:                                                                $user,$scancode,1);
 9035:             if (ref($actual_seq) eq 'ARRAY') {
 9036:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
 9037:                 if (ref($orderedforcode) eq 'HASH') {
 9038:                     if (@mapresources > 0) { 
 9039:                         $orderedforcode->{$scancode} = \@mapresources;
 9040:                     }
 9041:                 }
 9042:             }
 9043:             delete($env{'form.CODE'});
 9044:         }
 9045:     } else {
 9046:         my $actual_seq =
 9047:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 9048:                                                            $master_seq,
 9049:                                                            $user,undef,1);
 9050:         if (ref($actual_seq) eq 'ARRAY') {
 9051:             @mapresources = 
 9052:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
 9053:         }
 9054:     }
 9055:     return @mapresources;
 9056: }
 9057: 
 9058: sub grade_student_bubbles {
 9059:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
 9060:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
 9061:     my $uselookup = 0;
 9062:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
 9063:         (ref($startline) eq 'HASH')) {
 9064:         $uselookup = 1;
 9065:     }
 9066: 
 9067:     if (ref($resources) eq 'ARRAY') {
 9068:         my $count = 0;
 9069:         foreach my $resource (@{$resources}) {
 9070:             my $ressymb = $resource->symb();
 9071:             my %form = ('submitted'      => 'scantron',
 9072:                         'grade_target'   => 'grade',
 9073:                         'grade_username' => $uname,
 9074:                         'grade_domain'   => $udom,
 9075:                         'grade_courseid' => $env{'request.course.id'},
 9076:                         'grade_symb'     => $ressymb,
 9077:                         'CODE'           => $scancode
 9078:                        );
 9079:             if ($bubbles_per_row ne '') {
 9080:                 $form{'bubbles_per_row'} = $bubbles_per_row;
 9081:             }
 9082:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
 9083:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
 9084:             }
 9085:             if (ref($parts) eq 'HASH') {
 9086:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 9087:                     foreach my $part (@{$parts->{$ressymb}}) {
 9088:                         if ($uselookup) {
 9089:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
 9090:                         } else {
 9091:                             $form{'scantron_questnum_start.'.$part} =
 9092:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
 9093:                         }
 9094:                         $count++;
 9095:                     }
 9096:                 }
 9097:             }
 9098:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 9099:             return 'ssi_error' if ($ssi_error);
 9100:             last if (&Apache::loncommon::connection_aborted($r));
 9101:         }
 9102:     }
 9103:     return;
 9104: }
 9105: 
 9106: sub scantron_upload_scantron_data {
 9107:     my ($r,$symb)=@_;
 9108:     my $dom = $env{'request.role.domain'};
 9109:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 9110:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 9111:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 9112: 							  'domainid',
 9113: 							  'coursename',$dom);
 9114:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 9115:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
 9116:     my $default_form_data=&defaultFormData($symb);
 9117:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 9118:     &js_escape(\$nofile_alert);
 9119:     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.");
 9120:     &js_escape(\$nocourseid_alert);
 9121:     $r->print(&Apache::lonhtmlcommon::scripttag('
 9122:     function checkUpload(formname) {
 9123: 	if (formname.upfile.value == "") {
 9124: 	    alert("'.$nofile_alert.'");
 9125: 	    return false;
 9126: 	}
 9127:         if (formname.courseid.value == "") {
 9128:             alert("'.$nocourseid_alert.'");
 9129:             return false;
 9130:         }
 9131: 	formname.submit();
 9132:     }
 9133: 
 9134:     function ToSyllabus() {
 9135:         var cdom = '."'$dom'".';
 9136:         var cnum = document.rules.courseid.value;
 9137:         if (cdom == "" || cdom == null) {
 9138:             return;
 9139:         }
 9140:         if (cnum == "" || cnum == null) {
 9141:            return;
 9142:         }
 9143:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 9144:                             "height=350,width=350,scrollbars=yes,menubar=no");
 9145:         return;
 9146:     }
 9147: 
 9148: '));
 9149:     $r->print('
 9150: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
 9151: 
 9152: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 9153: '.$default_form_data.
 9154:   &Apache::lonhtmlcommon::start_pick_box().
 9155:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 9156:   '<input name="courseid" type="text" size="30" />'.$select_link.
 9157:   &Apache::lonhtmlcommon::row_closure().
 9158:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 9159:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 9160:   &Apache::lonhtmlcommon::row_closure().
 9161:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 9162:   '<input name="domainid" type="hidden" />'.$domdesc.
 9163:   &Apache::lonhtmlcommon::row_closure().
 9164:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 9165:   '<input type="file" name="upfile" size="50" />'.
 9166:   &Apache::lonhtmlcommon::row_closure(1).
 9167:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 9168: 
 9169: <input name="command" value="scantronupload_save" type="hidden" />
 9170: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 9171: </form>
 9172: ');
 9173:     return '';
 9174: }
 9175: 
 9176: 
 9177: sub scantron_upload_scantron_data_save {
 9178:     my($r,$symb)=@_;
 9179:     my $doanotherupload=
 9180: 	'<br /><form action="/adm/grades" method="post">'."\n".
 9181: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 9182: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 9183: 	'</form>'."\n";
 9184:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 9185: 	!&Apache::lonnet::allowed('usc',
 9186: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 9187: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 9188: 	unless ($symb) {
 9189: 	    $r->print($doanotherupload);
 9190: 	}
 9191: 	return '';
 9192:     }
 9193:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 9194:     my $uploadedfile;
 9195:     $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
 9196:     if (length($env{'form.upfile'}) < 2) {
 9197:         $r->print(
 9198:             &Apache::lonhtmlcommon::confirm_success(
 9199:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
 9200:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
 9201:     } else {
 9202:         my $result = 
 9203:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
 9204:                                             $env{'form.courseid'},$env{'form.domainid'});
 9205:         if ($result =~ m{^/uploaded/}) {
 9206:             $r->print(
 9207:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
 9208:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
 9209:                         (length($env{'form.upfile'})-1),
 9210:                         '<span class="LC_filename">'.$result.'</span>'));
 9211:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 9212:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 9213:                                                        $env{'form.courseid'},$uploadedfile));
 9214:         } else {
 9215:             $r->print(
 9216:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
 9217:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
 9218:                           $result,
 9219: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 9220: 	}
 9221:     }
 9222:     if ($symb) {
 9223: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
 9224:     } else {
 9225: 	$r->print($doanotherupload);
 9226:     }
 9227:     return '';
 9228: }
 9229: 
 9230: sub validate_uploaded_scantron_file {
 9231:     my ($cdom,$cname,$fname) = @_;
 9232:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 9233:     my @lines;
 9234:     if ($scanlines ne '-1') {
 9235:         @lines=split("\n",$scanlines,-1);
 9236:     }
 9237:     my $output;
 9238:     if (@lines) {
 9239:         my (%counts,$max_match_format);
 9240:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
 9241:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 9242:         my %idmap = &username_to_idmap($classlist);
 9243:         foreach my $key (keys(%idmap)) {
 9244:             my $lckey = lc($key);
 9245:             $idmap{$lckey} = $idmap{$key};
 9246:         }
 9247:         my %unique_formats;
 9248:         my @formatlines = &get_scantronformat_file();
 9249:         foreach my $line (@formatlines) {
 9250:             chomp($line);
 9251:             my @config = split(/:/,$line);
 9252:             my $idstart = $config[5];
 9253:             my $idlength = $config[6];
 9254:             if (($idstart ne '') && ($idlength > 0)) {
 9255:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 9256:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 9257:                 } else {
 9258:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 9259:                 }
 9260:             }
 9261:         }
 9262:         foreach my $key (keys(%unique_formats)) {
 9263:             my ($idstart,$idlength) = split(':',$key);
 9264:             %{$counts{$key}} = (
 9265:                                'found'   => 0,
 9266:                                'total'   => 0,
 9267:                               );
 9268:             foreach my $line (@lines) {
 9269:                 next if ($line =~ /^#/);
 9270:                 next if ($line =~ /^[\s\cz]*$/);
 9271:                 my $id = substr($line,$idstart-1,$idlength);
 9272:                 $id = lc($id);
 9273:                 if (exists($idmap{$id})) {
 9274:                     $counts{$key}{'found'} ++;
 9275:                 }
 9276:                 $counts{$key}{'total'} ++;
 9277:             }
 9278:             if ($counts{$key}{'total'}) {
 9279:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 9280:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 9281:                     $max_match_pct = $percent_match;
 9282:                     $max_match_format = $key;
 9283:                     $found_match_count = $counts{$key}{'found'};
 9284:                     $max_match_count = $counts{$key}{'total'};
 9285:                 }
 9286:             }
 9287:         }
 9288:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 9289:             my $format_descs;
 9290:             my $numwithformat = @{$unique_formats{$max_match_format}};
 9291:             for (my $i=0; $i<$numwithformat; $i++) {
 9292:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 9293:                 if ($i<$numwithformat-2) {
 9294:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 9295:                 } elsif ($i==$numwithformat-2) {
 9296:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 9297:                 } elsif ($i==$numwithformat-1) {
 9298:                     $format_descs .= '"<i>'.$desc.'</i>"';
 9299:                 }
 9300:             }
 9301:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 9302:             $output .= '<br />';
 9303:             if ($found_match_count == $max_match_count) {
 9304:                 # 100% matching entries
 9305:                 $output .= &Apache::lonhtmlcommon::confirm_success(
 9306:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
 9307:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
 9308:                 &mt('Comparison of student IDs in the uploaded file with'.
 9309:                     ' the course roster found matches for [_1] of the [_2] entries'.
 9310:                     ' in the file (for the format defined for [_3]).',
 9311:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
 9312:             } else {
 9313:                 # Not all entries matching? -> Show warning and additional info
 9314:                 $output .=
 9315:                     &Apache::lonhtmlcommon::confirm_success(
 9316:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
 9317:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
 9318:                         &mt('Not all entries could be matched!'),1).'<br />'.
 9319:                     &mt('Comparison of student IDs in the uploaded file with'.
 9320:                         ' the course roster found matches for [_1] of the [_2] entries'.
 9321:                         ' in the file (for the format defined for [_3]).',
 9322:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
 9323:                     '<p class="LC_info">'.
 9324:                     &mt('A low percentage of matches results from one of the following:').
 9325:                     '</p><ul>'.
 9326:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
 9327:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
 9328:                                '<i>'.$cdom.'</i>').'</li>'.
 9329:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 9330:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
 9331:                     '</ul>';
 9332:             }
 9333:         }
 9334:     } else {
 9335:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
 9336:     }
 9337:     return $output;
 9338: }
 9339: 
 9340: sub valid_file {
 9341:     my ($requested_file)=@_;
 9342:     foreach my $filename (sort(&scantron_filenames())) {
 9343: 	if ($requested_file eq $filename) { return 1; }
 9344:     }
 9345:     return 0;
 9346: }
 9347: 
 9348: sub scantron_download_scantron_data {
 9349:     my ($r,$symb)=@_;
 9350:     my $default_form_data=&defaultFormData($symb);
 9351:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9352:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9353:     my $file=$env{'form.scantron_selectfile'};
 9354:     if (! &valid_file($file)) {
 9355: 	$r->print('
 9356: 	<p>
 9357: 	    '.&mt('The requested filename was invalid.').'
 9358:         </p>
 9359: ');
 9360: 	return;
 9361:     }
 9362:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 9363:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 9364:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 9365:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 9366:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 9367:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 9368:     $r->print('
 9369:     <p>
 9370: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
 9371: 	      '<a href="'.$orig.'">','</a>').'
 9372:     </p>
 9373:     <p>
 9374: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 9375: 	      '<a href="'.$corrected.'">','</a>').'
 9376:     </p>
 9377:     <p>
 9378: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 9379: 	      '<a href="'.$skipped.'">','</a>').'
 9380:     </p>
 9381: ');
 9382:     return '';
 9383: }
 9384: 
 9385: sub checkscantron_results {
 9386:     my ($r,$symb) = @_;
 9387:     if (!$symb) {return '';}
 9388:     my $cid = $env{'request.course.id'};
 9389:     my %lettdig = &letter_to_digits();
 9390:     my $numletts = scalar(keys(%lettdig));
 9391:     my $cnum = $env{'course.'.$cid.'.num'};
 9392:     my $cdom = $env{'course.'.$cid.'.domain'};
 9393:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 9394:     my %record;
 9395:     my %scantron_config =
 9396:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 9397:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 9398:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 9399:     my $classlist=&Apache::loncoursedata::get_classlist();
 9400:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 9401:     my $navmap=Apache::lonnavmaps::navmap->new();
 9402:     unless (ref($navmap)) {
 9403:         $r->print(&navmap_errormsg());
 9404:         return '';
 9405:     }
 9406:     my $map=$navmap->getResourceByUrl($sequence);
 9407:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 9408:         %grader_randomlists_by_symb,%orderedforcode);
 9409:     if (ref($map)) { 
 9410:         $randomorder=$map->randomorder();
 9411:         $randompick=$map->randompick();
 9412:     }
 9413:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 9414:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 9415:     if ($nav_error) {
 9416:         $r->print(&navmap_errormsg());
 9417:         return '';
 9418:     }
 9419:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 9420:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 9421:     my ($uname,$udom);
 9422:     my (%scandata,%lastname,%bylast);
 9423:     $r->print('
 9424: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 9425: 
 9426:     my @delayqueue;
 9427:     my %completedstudents;
 9428: 
 9429:     my $count=&get_todo_count($scanlines,$scan_data);
 9430:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 9431:     my ($username,$domain,$started);
 9432:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 9433:     if ($nav_error) {
 9434:         $r->print(&navmap_errormsg());
 9435:         return '';
 9436:     }
 9437: 
 9438:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
 9439:     my $start=&Time::HiRes::time();
 9440:     my $i=-1;
 9441: 
 9442:     while ($i<$scanlines->{'count'}) {
 9443:         ($username,$domain,$uname)=('','','');
 9444:         $i++;
 9445:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 9446:         if ($line=~/^[\s\cz]*$/) { next; }
 9447:         if ($started) {
 9448:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 9449:         }
 9450:         $started=1;
 9451:         my $scan_record=
 9452:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 9453:                                                      $scan_data);
 9454:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
 9455:                                               \%idmap,$i)) {
 9456:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9457:                                 'Unable to find a student that matches',1);
 9458:             next;
 9459:         }
 9460:         if (exists $completedstudents{$uname}) {
 9461:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9462:                                 'Student '.$uname.' has multiple sheets',2);
 9463:             next;
 9464:         }
 9465:         my $pid = $scan_record->{'scantron.ID'};
 9466:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 9467:         push(@{$bylast{$lastname{$pid}}},$pid);
 9468:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 9469:         my $user = $uname.':'.$usec;
 9470:         ($username,$domain)=split(/:/,$uname);
 9471: 
 9472:         my $scancode;
 9473:         if ((exists($scan_record->{'scantron.CODE'})) &&
 9474:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 9475:             $scancode = $scan_record->{'scantron.CODE'};
 9476:         } else {
 9477:             $scancode = '';
 9478:         }
 9479: 
 9480:         my @mapresources = @resources;
 9481:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 9482:         my %respnumlookup=();
 9483:         my %startline=();
 9484:         if ($randomorder || $randompick) {
 9485:             @mapresources =
 9486:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 9487:                              \%orderedforcode);
 9488:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
 9489:                                              $scan_record,\@master_seq,\%symb_to_resource,
 9490:                                              \%grader_partids_by_symb,\%orderedforcode,
 9491:                                              \%respnumlookup,\%startline);
 9492:             if ($randompick && $total) {
 9493:                 $lastpos = $total*$scantron_config{'Qlength'};
 9494:             }
 9495:         }
 9496:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 9497:         chomp($scandata{$pid});
 9498:         $scandata{$pid} =~ s/\r$//;
 9499: 
 9500:         my $counter = -1;
 9501:         foreach my $resource (@mapresources) {
 9502:             my $parts;
 9503:             my $ressymb = $resource->symb();
 9504:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 9505:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 9506:                 my $currcode;
 9507:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
 9508:                     $currcode = $scancode;
 9509:                 }
 9510:                 (my $analysis,$parts) =
 9511:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 9512:                                               $username,$domain,undef,
 9513:                                               $bubbles_per_row,$currcode);
 9514:             } else {
 9515:                 $parts = $grader_partids_by_symb{$ressymb};
 9516:             }
 9517:             ($counter,my $recording) =
 9518:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 9519:                                          $scandata{$pid},$parts,
 9520:                                          \%scantron_config,\%lettdig,$numletts,
 9521:                                          $randomorder,$randompick,
 9522:                                          \%respnumlookup,\%startline);
 9523:             $record{$pid} .= $recording;
 9524:         }
 9525:     }
 9526:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 9527:     $r->print('<br />');
 9528:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 9529:     $passed = 0;
 9530:     $failed = 0;
 9531:     $numstudents = 0;
 9532:     foreach my $last (sort(keys(%bylast))) {
 9533:         if (ref($bylast{$last}) eq 'ARRAY') {
 9534:             foreach my $pid (sort(@{$bylast{$last}})) {
 9535:                 my $showscandata = $scandata{$pid};
 9536:                 my $showrecord = $record{$pid};
 9537:                 $showscandata =~ s/\s/&nbsp;/g;
 9538:                 $showrecord =~ s/\s/&nbsp;/g;
 9539:                 if ($scandata{$pid} eq $record{$pid}) {
 9540:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 9541:                     $okstudents .= '<tr class="'.$css_class.'">'.
 9542: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 9543: '</tr>'."\n".
 9544: '<tr class="'.$css_class.'">'."\n".
 9545: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
 9546:                     $passed ++;
 9547:                 } else {
 9548:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 9549:                     $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".
 9550: '</tr>'."\n".
 9551: '<tr class="'.$css_class.'">'."\n".
 9552: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 9553: '</tr>'."\n";
 9554:                     $failed ++;
 9555:                 }
 9556:                 $numstudents ++;
 9557:             }
 9558:         }
 9559:     }
 9560:     $r->print(
 9561:         '<p>'
 9562:        .&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).',
 9563:             '<b>',
 9564:             $numstudents,
 9565:             '</b>',
 9566:             $env{'form.scantron_maxbubble'})
 9567:        .'</p>'
 9568:     );
 9569:     $r->print('<p>'
 9570:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
 9571:              .'<br />'
 9572:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
 9573:              .'</p>'
 9574:     );
 9575:     if ($passed) {
 9576:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 9577:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9578:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9579:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9580:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9581:                  $okstudents."\n".
 9582:                  &Apache::loncommon::end_data_table().'<br />');
 9583:     }
 9584:     if ($failed) {
 9585:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 9586:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9587:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9588:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9589:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9590:                  $badstudents."\n".
 9591:                  &Apache::loncommon::end_data_table()).'<br />'.
 9592:                  &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.');  
 9593:     }
 9594:     $r->print('</form><br />');
 9595:     return;
 9596: }
 9597: 
 9598: sub verify_scantron_grading {
 9599:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 9600:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
 9601:         $respnumlookup,$startline) = @_;
 9602:     my ($record,%expected,%startpos);
 9603:     return ($counter,$record) if (!ref($resource));
 9604:     return ($counter,$record) if (!$resource->is_problem());
 9605:     my $symb = $resource->symb();
 9606:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 9607:     foreach my $part_id (@{$partids}) {
 9608:         $counter ++;
 9609:         $expected{$part_id} = 0;
 9610:         my $respnum = $counter;
 9611:         if ($randomorder || $randompick) {
 9612:             $respnum = $respnumlookup->{$counter};
 9613:             $startpos{$part_id} = $startline->{$counter} + 1;
 9614:         } else {
 9615:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 9616:         }
 9617:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
 9618:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
 9619:             foreach my $item (@sub_lines) {
 9620:                 $expected{$part_id} += $item;
 9621:             }
 9622:         } else {
 9623:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
 9624:         }
 9625:     }
 9626:     if ($symb) {
 9627:         my %recorded;
 9628:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 9629:         if ($returnhash{'version'}) {
 9630:             my %lasthash=();
 9631:             my $version;
 9632:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 9633:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 9634:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 9635:                 }
 9636:             }
 9637:             foreach my $key (keys(%lasthash)) {
 9638:                 if ($key =~ /\.scantron$/) {
 9639:                     my $value = &unescape($lasthash{$key});
 9640:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 9641:                     if ($value eq '') {
 9642:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 9643:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 9644:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9645:                             }
 9646:                         }
 9647:                     } else {
 9648:                         my @tocheck;
 9649:                         my @items = split(//,$value);
 9650:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 9651:                             ($scantron_config->{'Qon'} eq 'number')) {
 9652:                             if (@items < $expected{$part_id}) {
 9653:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 9654:                                 my @singles = split(//,$fragment);
 9655:                                 foreach my $pos (@singles) {
 9656:                                     if ($pos eq ' ') {
 9657:                                         push(@tocheck,$pos);
 9658:                                     } else {
 9659:                                         my $next = shift(@items);
 9660:                                         push(@tocheck,$next);
 9661:                                     }
 9662:                                 }
 9663:                             } else {
 9664:                                 @tocheck = @items;
 9665:                             }
 9666:                             foreach my $letter (@tocheck) {
 9667:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 9668:                                     if ($letter !~ /^[A-J]$/) {
 9669:                                         $letter = $scantron_config->{'Qoff'};
 9670:                                     }
 9671:                                     $recorded{$part_id} .= $letter;
 9672:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 9673:                                     my $digit;
 9674:                                     if ($letter !~ /^[A-J]$/) {
 9675:                                         $digit = $scantron_config->{'Qoff'};
 9676:                                     } else {
 9677:                                         $digit = $lettdig->{$letter};
 9678:                                     }
 9679:                                     $recorded{$part_id} .= $digit;
 9680:                                 }
 9681:                             }
 9682:                         } else {
 9683:                             @tocheck = @items;
 9684:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 9685:                                 my $curr_sub = shift(@tocheck);
 9686:                                 my $digit;
 9687:                                 if ($curr_sub =~ /^[A-J]$/) {
 9688:                                     $digit = $lettdig->{$curr_sub}-1;
 9689:                                 }
 9690:                                 if ($curr_sub eq 'J') {
 9691:                                     $digit += scalar($numletts);
 9692:                                 }
 9693:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9694:                                     if ($j == $digit) {
 9695:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 9696:                                     } else {
 9697:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9698:                                     }
 9699:                                 }
 9700:                             }
 9701:                         }
 9702:                     }
 9703:                 }
 9704:             }
 9705:         }
 9706:         foreach my $part_id (@{$partids}) {
 9707:             if ($recorded{$part_id} eq '') {
 9708:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 9709:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9710:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9711:                     }
 9712:                 }
 9713:             }
 9714:             $record .= $recorded{$part_id};
 9715:         }
 9716:     }
 9717:     return ($counter,$record);
 9718: }
 9719: 
 9720: sub letter_to_digits {
 9721:     my %lettdig = (
 9722:                     A => 1,
 9723:                     B => 2,
 9724:                     C => 3,
 9725:                     D => 4,
 9726:                     E => 5,
 9727:                     F => 6,
 9728:                     G => 7,
 9729:                     H => 8,
 9730:                     I => 9,
 9731:                     J => 0,
 9732:                   );
 9733:     return %lettdig;
 9734: }
 9735: 
 9736: 
 9737: #-------- end of section for handling grading scantron forms -------
 9738: #
 9739: #-------------------------------------------------------------------
 9740: 
 9741: #-------------------------- Menu interface -------------------------
 9742: #
 9743: #--- Href with symb and command ---
 9744: 
 9745: sub href_symb_cmd {
 9746:     my ($symb,$cmd)=@_;
 9747:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
 9748: }
 9749: 
 9750: sub grading_menu {
 9751:     my ($request,$symb) = @_;
 9752:     if (!$symb) {return '';}
 9753: 
 9754:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 9755:                   'command'=>'individual');
 9756:     
 9757:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9758: 
 9759:     $fields{'command'}='ungraded';
 9760:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9761: 
 9762:     $fields{'command'}='table';
 9763:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9764: 
 9765:     $fields{'command'}='all_for_one';
 9766:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9767: 
 9768:     $fields{'command'}='downloadfilesselect';
 9769:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9770: 
 9771:     $fields{'command'} = 'csvform';
 9772:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9773:     
 9774:     $fields{'command'} = 'processclicker';
 9775:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9776:     
 9777:     $fields{'command'} = 'scantron_selectphase';
 9778:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9779: 
 9780:     $fields{'command'} = 'initialverifyreceipt';
 9781:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9782:     
 9783:     my @menu = ({	categorytitle=>'Hand Grading',
 9784:             items =>[
 9785:                         {	linktext => 'Select individual students to grade',
 9786:                     		url => $url1a,
 9787:                     		permission => 'F',
 9788:                     		icon => 'grade_students.png',
 9789:                     		linktitle => 'Grade current resource for a selection of students.'
 9790:                         }, 
 9791:                         {       linktext => 'Grade ungraded submissions.',
 9792:                                 url => $url1b,
 9793:                                 permission => 'F',
 9794:                                 icon => 'ungrade_sub.png',
 9795:                                 linktitle => 'Grade all submissions that have not been graded yet.'
 9796:                         },
 9797: 
 9798:                         {       linktext => 'Grading table',
 9799:                                 url => $url1c,
 9800:                                 permission => 'F',
 9801:                                 icon => 'grading_table.png',
 9802:                                 linktitle => 'Grade current resource for all students.'
 9803:                         },
 9804:                         {       linktext => 'Grade page/folder for one student',
 9805:                                 url => $url1d,
 9806:                                 permission => 'F',
 9807:                                 icon => 'grade_PageFolder.png',
 9808:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
 9809:                         },
 9810:                         {       linktext => 'Download submissions',
 9811:                                 url => $url1e,
 9812:                                 permission => 'F',
 9813:                                 icon => 'download_sub.png',
 9814:                                 linktitle => 'Download all students submissions.'
 9815:                         }]},
 9816:                          { categorytitle=>'Automated Grading',
 9817:                items =>[
 9818: 
 9819:                 	    {	linktext => 'Upload Scores',
 9820:                     		url => $url2,
 9821:                     		permission => 'F',
 9822:                     		icon => 'uploadscores.png',
 9823:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 9824:                 	    },
 9825:                 	    {	linktext => 'Process Clicker',
 9826:                     		url => $url3,
 9827:                     		permission => 'F',
 9828:                     		icon => 'addClickerInfoFile.png',
 9829:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 9830:                 	    },
 9831:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
 9832:                     		url => $url4,
 9833:                     		permission => 'F',
 9834:                     		icon => 'bubblesheet.png',
 9835:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
 9836:                 	    },
 9837:                             {   linktext => 'Verify Receipt Number',
 9838:                                 url => $url5,
 9839:                                 permission => 'F',
 9840:                                 icon => 'receipt_number.png',
 9841:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
 9842:                             }
 9843: 
 9844:                     ]
 9845:             });
 9846: 
 9847:     # Create the menu
 9848:     my $Str;
 9849:     $Str .= '<form method="post" action="" name="gradingMenu">';
 9850:     $Str .= '<input type="hidden" name="command" value="" />'.
 9851:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9852: 
 9853:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
 9854:     return $Str;    
 9855: }
 9856: 
 9857: 
 9858: sub ungraded {
 9859:     my ($request)=@_;
 9860:     &submit_options($request);
 9861: }
 9862: 
 9863: sub submit_options_sequence {
 9864:     my ($request,$symb) = @_;
 9865:     if (!$symb) {return '';}
 9866:     &commonJSfunctions($request);
 9867:     my $result;
 9868: 
 9869:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9870:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9871:     $result.=&selectfield(0).
 9872:             '<input type="hidden" name="command" value="pickStudentPage" />
 9873:             <div>
 9874:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 9875:             </div>
 9876:         </div>
 9877:   </form>';
 9878:     return $result;
 9879: }
 9880: 
 9881: sub submit_options_table {
 9882:     my ($request,$symb) = @_;
 9883:     if (!$symb) {return '';}
 9884:     &commonJSfunctions($request);
 9885:     my $is_tool = ($symb =~ /ext\.tool$/);
 9886:     my $result;
 9887: 
 9888:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9889:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9890: 
 9891:     $result.=&selectfield(1,$is_tool).
 9892:             '<input type="hidden" name="command" value="viewgrades" />
 9893:             <div>
 9894:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 9895:             </div>
 9896:         </div>
 9897:   </form>';
 9898:     return $result;
 9899: }
 9900: 
 9901: sub submit_options_download {
 9902:     my ($request,$symb) = @_;
 9903:     if (!$symb) {return '';}
 9904: 
 9905:     my $is_tool = ($symb =~ /ext\.tool$/);
 9906:     &commonJSfunctions($request);
 9907: 
 9908:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9909:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9910:     $result.='
 9911: <h2>
 9912:   '.&mt('Select Students for whom to Download Submissions').'
 9913: </h2>'.&selectfield(1,$is_tool).'
 9914:                 <input type="hidden" name="command" value="downloadfileslink" /> 
 9915:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 9916:             </div>
 9917:           </div>
 9918: 
 9919: 
 9920:   </form>';
 9921:     return $result;
 9922: }
 9923: 
 9924: #--- Displays the submissions first page -------
 9925: sub submit_options {
 9926:     my ($request,$symb) = @_;
 9927:     if (!$symb) {return '';}
 9928: 
 9929:     my $is_tool = ($symb =~ /ext\.tool$/);
 9930:     &commonJSfunctions($request);
 9931:     my $result;
 9932: 
 9933:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9934: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9935:     $result.=&selectfield(1,$is_tool).'
 9936:                 <input type="hidden" name="command" value="submission" /> 
 9937: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
 9938:             </div>
 9939:           </div>
 9940: 
 9941: 
 9942:   </form>';
 9943:     return $result;
 9944: }
 9945: 
 9946: sub selectfield {
 9947:    my ($full,$is_tool)=@_;
 9948:    my %options;
 9949:    if ($is_tool) {
 9950:        %options =
 9951:            (&transtatus_options,
 9952:             'select_form_order' => ['yes','incorrect','all']);
 9953:    } else {
 9954:        %options = 
 9955:            (&substatus_options,
 9956:             'select_form_order' => ['yes','queued','graded','incorrect','all']);
 9957:    }
 9958:    my $result='<div class="LC_columnSection">
 9959:   
 9960:     <fieldset>
 9961:       <legend>
 9962:        '.&mt('Sections').'
 9963:       </legend>
 9964:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
 9965:     </fieldset>
 9966:   
 9967:     <fieldset>
 9968:       <legend>
 9969:         '.&mt('Groups').'
 9970:       </legend>
 9971:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 9972:     </fieldset>
 9973:   
 9974:     <fieldset>
 9975:       <legend>
 9976:         '.&mt('Access Status').'
 9977:       </legend>
 9978:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
 9979:     </fieldset>';
 9980:     if ($full) {
 9981:         my $heading = &mt('Submission Status');
 9982:         if ($is_tool) {
 9983:             $heading = &mt('Transaction Status');
 9984:         }
 9985:         $result.='
 9986:     <fieldset>
 9987:       <legend>
 9988:         '.$heading.'
 9989:       </legend>'.
 9990:        &Apache::loncommon::select_form('all','submitonly',\%options).
 9991:    '</fieldset>';
 9992:     }
 9993:     $result.='</div><br />';
 9994:     return $result;
 9995: }
 9996: 
 9997: sub substatus_options {
 9998:     return &Apache::lonlocal::texthash(
 9999:                                       'yes'       => 'with submissions',
10000:                                       'queued'    => 'in grading queue',
10001:                                       'graded'    => 'with ungraded submissions',
10002:                                       'incorrect' => 'with incorrect submissions',
10003:                                       'all'       => 'with any status',
10004:                                       );
10005: }
10006: 
10007: sub transtatus_options {
10008:     return &Apache::lonlocal::texthash(
10009:                                        'yes'       => 'with score transactions',
10010:                                        'incorrect' => 'with less than full credit',
10011:                                        'all'       => 'with any status',
10012:                                       );
10013: }
10014: 
10015: sub reset_perm {
10016:     undef(%perm);
10017: }
10018: 
10019: sub init_perm {
10020:     &reset_perm();
10021:     foreach my $test_perm ('vgr','mgr','opa') {
10022: 
10023: 	my $scope = $env{'request.course.id'};
10024: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
10025: 
10026: 	    $scope .= '/'.$env{'request.course.sec'};
10027: 	    if ( $perm{$test_perm}=
10028: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
10029: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
10030: 	    } else {
10031: 		delete($perm{$test_perm});
10032: 	    }
10033: 	}
10034:     }
10035: }
10036: 
10037: sub init_old_essays {
10038:     my ($symb,$apath,$adom,$aname) = @_;
10039:     if ($symb ne '') {
10040:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
10041:         if (keys(%essays) > 0) {
10042:             $old_essays{$symb} = \%essays;
10043:         }
10044:     }
10045:     return;
10046: }
10047: 
10048: sub reset_old_essays {
10049:     undef(%old_essays);
10050: }
10051: 
10052: sub gather_clicker_ids {
10053:     my %clicker_ids;
10054: 
10055:     my $classlist = &Apache::loncoursedata::get_classlist();
10056: 
10057:     # Set up a couple variables.
10058:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
10059:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
10060:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
10061: 
10062:     foreach my $student (keys(%$classlist)) {
10063:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
10064:         my $username = $classlist->{$student}->[$username_idx];
10065:         my $domain   = $classlist->{$student}->[$domain_idx];
10066:         my $clickers =
10067: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
10068:         foreach my $id (split(/\,/,$clickers)) {
10069:             $id=~s/^[\#0]+//;
10070:             $id=~s/[\-\:]//g;
10071:             if (exists($clicker_ids{$id})) {
10072: 		$clicker_ids{$id}.=','.$username.':'.$domain;
10073:             } else {
10074: 		$clicker_ids{$id}=$username.':'.$domain;
10075:             }
10076:         }
10077:     }
10078:     return %clicker_ids;
10079: }
10080: 
10081: sub gather_adv_clicker_ids {
10082:     my %clicker_ids;
10083:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
10084:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
10085:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
10086:     foreach my $element (sort(keys(%coursepersonnel))) {
10087:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
10088:             my ($puname,$pudom)=split(/\:/,$person);
10089:             my $clickers =
10090: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
10091:             foreach my $id (split(/\,/,$clickers)) {
10092: 		$id=~s/^[\#0]+//;
10093:                 $id=~s/[\-\:]//g;
10094: 		if (exists($clicker_ids{$id})) {
10095: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
10096: 		} else {
10097: 		    $clicker_ids{$id}=$puname.':'.$pudom;
10098: 		}
10099:             }
10100:         }
10101:     }
10102:     return %clicker_ids;
10103: }
10104: 
10105: sub clicker_grading_parameters {
10106:     return ('gradingmechanism' => 'scalar',
10107:             'upfiletype' => 'scalar',
10108:             'specificid' => 'scalar',
10109:             'pcorrect' => 'scalar',
10110:             'pincorrect' => 'scalar');
10111: }
10112: 
10113: sub process_clicker {
10114:     my ($r,$symb)=@_;
10115:     if (!$symb) {return '';}
10116:     my $result=&checkforfile_js();
10117:     $result.=&Apache::loncommon::start_data_table().
10118:              &Apache::loncommon::start_data_table_header_row().
10119:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
10120:              &Apache::loncommon::end_data_table_header_row().
10121:              &Apache::loncommon::start_data_table_row()."<td>\n";
10122: # Attempt to restore parameters from last session, set defaults if not present
10123:     my %Saveable_Parameters=&clicker_grading_parameters();
10124:     &Apache::loncommon::restore_course_settings('grades_clicker',
10125:                                                  \%Saveable_Parameters);
10126:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
10127:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
10128:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
10129:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
10130: 
10131:     my %checked;
10132:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
10133:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
10134:           $checked{$gradingmechanism}=' checked="checked"';
10135:        }
10136:     }
10137: 
10138:     my $upload=&mt("Evaluate File");
10139:     my $type=&mt("Type");
10140:     my $attendance=&mt("Award points just for participation");
10141:     my $personnel=&mt("Correctness determined from response by course personnel");
10142:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
10143:     my $given=&mt("Correctness determined from given list of answers").' '.
10144:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
10145:     my $pcorrect=&mt("Percentage points for correct solution");
10146:     my $pincorrect=&mt("Percentage points for incorrect solution");
10147:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
10148: 						   {'iclicker' => 'i>clicker',
10149:                                                     'interwrite' => 'interwrite PRS',
10150:                                                     'turning' => 'Turning Technologies'});
10151:     $symb = &Apache::lonenc::check_encrypt($symb);
10152:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
10153: function sanitycheck() {
10154: // Accept only integer percentages
10155:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
10156:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
10157: // Find out grading choice
10158:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
10159:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
10160:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
10161:       }
10162:    }
10163: // By default, new choice equals user selection
10164:    newgradingchoice=gradingchoice;
10165: // Not good to give more points for false answers than correct ones
10166:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
10167:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
10168:    }
10169: // If new choice is attendance only, and old choice was correctness-based, restore defaults
10170:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
10171:       document.forms.gradesupload.pcorrect.value=100;
10172:       document.forms.gradesupload.pincorrect.value=100;
10173:    }
10174: // If the values are different, cannot be attendance only
10175:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
10176:        (gradingchoice=='attendance')) {
10177:        newgradingchoice='personnel';
10178:    }
10179: // Change grading choice to new one
10180:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
10181:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
10182:          document.forms.gradesupload.gradingmechanism[i].checked=true;
10183:       } else {
10184:          document.forms.gradesupload.gradingmechanism[i].checked=false;
10185:       }
10186:    }
10187: // Remember the old state
10188:    document.forms.gradesupload.waschecked.value=newgradingchoice;
10189: }
10190: ENDUPFORM
10191:     $result.= <<ENDUPFORM;
10192: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
10193: <input type="hidden" name="symb" value="$symb" />
10194: <input type="hidden" name="command" value="processclickerfile" />
10195: <input type="file" name="upfile" size="50" />
10196: <br /><label>$type: $selectform</label>
10197: ENDUPFORM
10198:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
10199:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
10200:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
10201: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
10202: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
10203: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
10204: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
10205: <br />&nbsp;&nbsp;&nbsp;
10206: <input type="text" name="givenanswer" size="50" />
10207: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
10208: ENDGRADINGFORM
10209:          $result.='</td>'.&Apache::loncommon::end_data_table_row().
10210:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
10211:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
10212: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
10213: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
10214: </form>'
10215: ENDPERCFORM
10216:     $result.='</td>'.
10217:              &Apache::loncommon::end_data_table_row().
10218:              &Apache::loncommon::end_data_table();
10219:     return $result;
10220: }
10221: 
10222: sub process_clicker_file {
10223:     my ($r,$symb)=@_;
10224:     if (!$symb) {return '';}
10225: 
10226:     my %Saveable_Parameters=&clicker_grading_parameters();
10227:     &Apache::loncommon::store_course_settings('grades_clicker',
10228:                                               \%Saveable_Parameters);
10229:     my $result='';
10230:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
10231: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
10232: 	return $result;
10233:     }
10234:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
10235:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
10236:         return $result;
10237:     }
10238:     my $foundgiven=0;
10239:     if ($env{'form.gradingmechanism'} eq 'given') {
10240:         $env{'form.givenanswer'}=~s/^\s*//gs;
10241:         $env{'form.givenanswer'}=~s/\s*$//gs;
10242:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
10243:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
10244:         my @answers=split(/\,/,$env{'form.givenanswer'});
10245:         $foundgiven=$#answers+1;
10246:     }
10247:     my %clicker_ids=&gather_clicker_ids();
10248:     my %correct_ids;
10249:     if ($env{'form.gradingmechanism'} eq 'personnel') {
10250: 	%correct_ids=&gather_adv_clicker_ids();
10251:     }
10252:     if ($env{'form.gradingmechanism'} eq 'specific') {
10253: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
10254: 	   $correct_id=~tr/a-z/A-Z/;
10255: 	   $correct_id=~s/\s//gs;
10256: 	   $correct_id=~s/^[\#0]+//;
10257:            $correct_id=~s/[\-\:]//g;
10258:            if ($correct_id) {
10259: 	      $correct_ids{$correct_id}='specified';
10260:            }
10261:         }
10262:     }
10263:     if ($env{'form.gradingmechanism'} eq 'attendance') {
10264: 	$result.=&mt('Score based on attendance only');
10265:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
10266:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
10267:     } else {
10268: 	my $number=0;
10269: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
10270: 	foreach my $id (sort(keys(%correct_ids))) {
10271: 	    $result.='<br /><tt>'.$id.'</tt> - ';
10272: 	    if ($correct_ids{$id} eq 'specified') {
10273: 		$result.=&mt('specified');
10274: 	    } else {
10275: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
10276: 		$result.=&Apache::loncommon::plainname($uname,$udom);
10277: 	    }
10278: 	    $number++;
10279: 	}
10280:         $result.="</p>\n";
10281:         if ($number==0) {
10282:             $result .=
10283:                  &Apache::lonhtmlcommon::confirm_success(
10284:                      &mt('No IDs found to determine correct answer'),1);
10285:             return $result;
10286:         }
10287:     }
10288:     if (length($env{'form.upfile'}) < 2) {
10289:         $result .=
10290:             &Apache::lonhtmlcommon::confirm_success(
10291:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
10292:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
10293:         return $result;
10294:     }
10295: 
10296: # Were able to get all the info needed, now analyze the file
10297: 
10298:     $result.=&Apache::loncommon::studentbrowser_javascript();
10299:     $symb = &Apache::lonenc::check_encrypt($symb);
10300:     $result.=&Apache::loncommon::start_data_table().
10301:              &Apache::loncommon::start_data_table_header_row().
10302:              '<th>'.&mt('Evaluate clicker file').'</th>'.
10303:              &Apache::loncommon::end_data_table_header_row().
10304:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
10305: <td>
10306: <form method="post" action="/adm/grades" name="clickeranalysis">
10307: <input type="hidden" name="symb" value="$symb" />
10308: <input type="hidden" name="command" value="assignclickergrades" />
10309: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
10310: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
10311: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
10312: ENDHEADER
10313:     if ($env{'form.gradingmechanism'} eq 'given') {
10314:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
10315:     } 
10316:     my %responses;
10317:     my @questiontitles;
10318:     my $errormsg='';
10319:     my $number=0;
10320:     if ($env{'form.upfiletype'} eq 'iclicker') {
10321: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
10322:     }
10323:     if ($env{'form.upfiletype'} eq 'interwrite') {
10324:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
10325:     }
10326:     if ($env{'form.upfiletype'} eq 'turning') {
10327:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
10328:     }
10329:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
10330:              '<input type="hidden" name="number" value="'.$number.'" />'.
10331:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
10332:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
10333:              '<br />';
10334:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
10335:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
10336:        return $result;
10337:     } 
10338: # Remember Question Titles
10339: # FIXME: Possibly need delimiter other than ":"
10340:     for (my $i=0;$i<$number;$i++) {
10341:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
10342:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
10343:     }
10344:     my $correct_count=0;
10345:     my $student_count=0;
10346:     my $unknown_count=0;
10347: # Match answers with usernames
10348: # FIXME: Possibly need delimiter other than ":"
10349:     foreach my $id (keys(%responses)) {
10350:        if ($correct_ids{$id}) {
10351:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
10352:           $correct_count++;
10353:        } elsif ($clicker_ids{$id}) {
10354:           if ($clicker_ids{$id}=~/\,/) {
10355: # More than one user with the same clicker!
10356:              $result.="</td>".&Apache::loncommon::end_data_table_row().
10357:                            &Apache::loncommon::start_data_table_row()."<td>".
10358:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
10359:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10360:                            "<select name='multi".$id."'>";
10361:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
10362:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
10363:              }
10364:              $result.='</select>';
10365:              $unknown_count++;
10366:           } else {
10367: # Good: found one and only one user with the right clicker
10368:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
10369:              $student_count++;
10370:           }
10371:        } else {
10372:           $result.="</td>".&Apache::loncommon::end_data_table_row().
10373:                            &Apache::loncommon::start_data_table_row()."<td>".
10374:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
10375:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10376:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
10377:                    "\n".&mt("Domain").": ".
10378:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
10379:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
10380:           $unknown_count++;
10381:        }
10382:     }
10383:     $result.='<hr />'.
10384:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
10385:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
10386:        if ($correct_count==0) {
10387:           $errormsg.="Found no correct answers for grading!";
10388:        } elsif ($correct_count>1) {
10389:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
10390:        }
10391:     }
10392:     if ($number<1) {
10393:        $errormsg.="Found no questions.";
10394:     }
10395:     if ($errormsg) {
10396:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
10397:     } else {
10398:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
10399:     }
10400:     $result.='</form></td>'.
10401:              &Apache::loncommon::end_data_table_row().
10402:              &Apache::loncommon::end_data_table();
10403:     return $result;
10404: }
10405: 
10406: sub iclicker_eval {
10407:     my ($questiontitles,$responses)=@_;
10408:     my $number=0;
10409:     my $errormsg='';
10410:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10411:         my %components=&Apache::loncommon::record_sep($line);
10412:         my @entries=map {$components{$_}} (sort(keys(%components)));
10413: 	if ($entries[0] eq 'Question') {
10414: 	    for (my $i=3;$i<$#entries;$i+=6) {
10415: 		$$questiontitles[$number]=$entries[$i];
10416: 		$number++;
10417: 	    }
10418: 	}
10419: 	if ($entries[0]=~/^\#/) {
10420: 	    my $id=$entries[0];
10421: 	    my @idresponses;
10422: 	    $id=~s/^[\#0]+//;
10423: 	    for (my $i=0;$i<$number;$i++) {
10424: 		my $idx=3+$i*6;
10425:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
10426: 		push(@idresponses,$entries[$idx]);
10427: 	    }
10428: 	    $$responses{$id}=join(',',@idresponses);
10429: 	}
10430:     }
10431:     return ($errormsg,$number);
10432: }
10433: 
10434: sub interwrite_eval {
10435:     my ($questiontitles,$responses)=@_;
10436:     my $number=0;
10437:     my $errormsg='';
10438:     my $skipline=1;
10439:     my $questionnumber=0;
10440:     my %idresponses=();
10441:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10442:         my %components=&Apache::loncommon::record_sep($line);
10443:         my @entries=map {$components{$_}} (sort(keys(%components)));
10444:         if ($entries[1] eq 'Time') { $skipline=0; next; }
10445:         if ($entries[1] eq 'Response') { $skipline=1; }
10446:         next if $skipline;
10447:         if ($entries[0]!=$questionnumber) {
10448:            $questionnumber=$entries[0];
10449:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
10450:            $number++;
10451:         }
10452:         my $id=$entries[4];
10453:         $id=~s/^[\#0]+//;
10454:         $id=~s/^v\d*\://i;
10455:         $id=~s/[\-\:]//g;
10456:         $idresponses{$id}[$number]=$entries[6];
10457:     }
10458:     foreach my $id (keys(%idresponses)) {
10459:        $$responses{$id}=join(',',@{$idresponses{$id}});
10460:        $$responses{$id}=~s/^\s*\,//;
10461:     }
10462:     return ($errormsg,$number);
10463: }
10464: 
10465: sub turning_eval {
10466:     my ($questiontitles,$responses)=@_;
10467:     my $number=0;
10468:     my $errormsg='';
10469:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10470:         my %components=&Apache::loncommon::record_sep($line);
10471:         my @entries=map {$components{$_}} (sort(keys(%components)));
10472:         if ($#entries>$number) { $number=$#entries; }
10473:         my $id=$entries[0];
10474:         my @idresponses;
10475:         $id=~s/^[\#0]+//;
10476:         unless ($id) { next; }
10477:         for (my $idx=1;$idx<=$#entries;$idx++) {
10478:             $entries[$idx]=~s/\,/\;/g;
10479:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
10480:             push(@idresponses,$entries[$idx]);
10481:         }
10482:         $$responses{$id}=join(',',@idresponses);
10483:     }
10484:     for (my $i=1; $i<=$number; $i++) {
10485:         $$questiontitles[$i]=&mt('Question [_1]',$i);
10486:     }
10487:     return ($errormsg,$number);
10488: }
10489: 
10490: 
10491: sub assign_clicker_grades {
10492:     my ($r,$symb)=@_;
10493:     if (!$symb) {return '';}
10494: # See which part we are saving to
10495:     my $res_error;
10496:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
10497:     if ($res_error) {
10498:         return &navmap_errormsg();
10499:     }
10500: # FIXME: This should probably look for the first handgradeable part
10501:     my $part=$$partlist[0];
10502: # Start screen output
10503:     my $result=&Apache::loncommon::start_data_table().
10504:              &Apache::loncommon::start_data_table_header_row().
10505:              '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
10506:              &Apache::loncommon::end_data_table_header_row().
10507:              &Apache::loncommon::start_data_table_row().'<td>';
10508: # Get correct result
10509: # FIXME: Possibly need delimiter other than ":"
10510:     my @correct=();
10511:     my $gradingmechanism=$env{'form.gradingmechanism'};
10512:     my $number=$env{'form.number'};
10513:     if ($gradingmechanism ne 'attendance') {
10514:        foreach my $key (keys(%env)) {
10515:           if ($key=~/^form\.correct\:/) {
10516:              my @input=split(/\,/,$env{$key});
10517:              for (my $i=0;$i<=$#input;$i++) {
10518:                  if (($correct[$i]) && ($input[$i]) &&
10519:                      ($correct[$i] ne $input[$i])) {
10520:                     $result.='<br /><span class="LC_warning">'.
10521:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
10522:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
10523:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
10524:                     $correct[$i]=$input[$i];
10525:                  }
10526:              }
10527:           }
10528:        }
10529:        for (my $i=0;$i<$number;$i++) {
10530:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
10531:              $result.='<br /><span class="LC_error">'.
10532:                       &mt('No correct result given for question "[_1]"!',
10533:                           $env{'form.question:'.$i}).'</span>';
10534:           }
10535:        }
10536:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
10537:     }
10538: # Start grading
10539:     my $pcorrect=$env{'form.pcorrect'};
10540:     my $pincorrect=$env{'form.pincorrect'};
10541:     my $storecount=0;
10542:     my %users=();
10543:     foreach my $key (keys(%env)) {
10544:        my $user='';
10545:        if ($key=~/^form\.student\:(.*)$/) {
10546:           $user=$1;
10547:        }
10548:        if ($key=~/^form\.unknown\:(.*)$/) {
10549:           my $id=$1;
10550:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
10551:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
10552:           } elsif ($env{'form.multi'.$id}) {
10553:              $user=$env{'form.multi'.$id};
10554:           }
10555:        }
10556:        if ($user) {
10557:           if ($users{$user}) {
10558:              $result.='<br /><span class="LC_warning">'.
10559:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
10560:                       '</span><br />';
10561:           }
10562:           $users{$user}=1; 
10563:           my @answer=split(/\,/,$env{$key});
10564:           my $sum=0;
10565:           my $realnumber=$number;
10566:           for (my $i=0;$i<$number;$i++) {
10567:              if  ($correct[$i] eq '-') {
10568:                 $realnumber--;
10569:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/))  {
10570:                 if ($gradingmechanism eq 'attendance') {
10571:                    $sum+=$pcorrect;
10572:                 } elsif ($correct[$i] eq '*') {
10573:                    $sum+=$pcorrect;
10574:                 } else {
10575: # We actually grade if correct or not
10576:                    my $increment=$pincorrect;
10577: # Special case: numerical answer "0"
10578:                    if ($correct[$i] eq '0') {
10579:                       if ($answer[$i]=~/^[0\.]+$/) {
10580:                          $increment=$pcorrect;
10581:                       }
10582: # General numerical answer, both evaluate to something non-zero
10583:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
10584:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
10585:                          $increment=$pcorrect;
10586:                       }
10587: # Must be just alphanumeric
10588:                    } elsif ($answer[$i] eq $correct[$i]) {
10589:                       $increment=$pcorrect;
10590:                    }
10591:                    $sum+=$increment;
10592:                 }
10593:              }
10594:           }
10595:           my $ave=$sum/(100*$realnumber);
10596: # Store
10597:           my ($username,$domain)=split(/\:/,$user);
10598:           my %grades=();
10599:           $grades{"resource.$part.solved"}='correct_by_override';
10600:           $grades{"resource.$part.awarded"}=$ave;
10601:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
10602:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
10603:                                                  $env{'request.course.id'},
10604:                                                  $domain,$username);
10605:           if ($returncode ne 'ok') {
10606:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
10607:           } else {
10608:              $storecount++;
10609:           }
10610:        }
10611:     }
10612: # We are done
10613:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
10614:              '</td>'.
10615:              &Apache::loncommon::end_data_table_row().
10616:              &Apache::loncommon::end_data_table();
10617:     return $result;
10618: }
10619: 
10620: sub navmap_errormsg {
10621:     return '<div class="LC_error">'.
10622:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
10623:            &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>').
10624:            '</div>';
10625: }
10626: 
10627: sub startpage {
10628:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js) = @_;
10629:     if ($nomenu) {
10630:         $r->print(&Apache::loncommon::start_page("Student's Version",$js,{'only_body' => '1'}));
10631:     } else {
10632:         unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
10633:         $r->print(&Apache::loncommon::start_page('Grading',$js,
10634:                                                  {'bread_crumbs' => $crumbs}));
10635:         &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
10636:     }
10637:     unless ($nodisplayflag) {
10638:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
10639:     }
10640: }
10641: 
10642: sub select_problem {
10643:     my ($r)=@_;
10644:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
10645:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1,undef,undef,undef,undef,1));
10646:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
10647:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
10648: }
10649: 
10650: sub handler {
10651:     my $request=$_[0];
10652:     &reset_caches();
10653:     if ($request->header_only) {
10654:         &Apache::loncommon::content_type($request,'text/html');
10655:         $request->send_http_header;
10656:         return OK;
10657:     }
10658:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
10659: 
10660: # see what command we need to execute
10661: 
10662:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
10663:     my $command=$commands[0];
10664: 
10665:     &init_perm();
10666:     if (!$env{'request.course.id'}) {
10667:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
10668:                 ($command =~ /^scantronupload/)) {
10669:             # Not in a course.
10670:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
10671:             return HTTP_NOT_ACCEPTABLE;
10672:         }
10673:     } elsif (!%perm) {
10674:         $request->internal_redirect('/adm/quickgrades');
10675:         return OK;
10676:     }
10677:     &Apache::loncommon::content_type($request,'text/html');
10678:     $request->send_http_header;
10679: 
10680:     if ($#commands > 0) {
10681: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
10682:     }
10683: 
10684: # see what the symb is
10685: 
10686:     my $symb=$env{'form.symb'};
10687:     unless ($symb) {
10688:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
10689:        $symb=&Apache::lonnet::symbread($url);
10690:     }
10691:     &Apache::lonenc::check_decrypt(\$symb);
10692: 
10693:     $ssi_error = 0;
10694:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
10695: #
10696: # Not called from a resource, but inside a course
10697: #    
10698:         &startpage($request,undef,[],1,1);
10699:         &select_problem($request);
10700:     } else {
10701: 	if ($command eq 'submission' && $perm{'vgr'}) {
10702:             my ($stuvcurrent,$stuvdisp,$versionform,$js);
10703:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
10704:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
10705:                     &choose_task_version_form($symb,$env{'form.student'},
10706:                                               $env{'form.userdom'});
10707:             }
10708:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
10709:             if ($versionform) {
10710:                 $request->print($versionform);
10711:             }
10712:             $request->print('<br clear="all" />');
10713: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
10714:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
10715:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
10716:                 &choose_task_version_form($symb,$env{'form.student'},
10717:                                           $env{'form.userdom'},
10718:                                           $env{'form.inhibitmenu'});
10719:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
10720:             if ($versionform) {
10721:                 $request->print($versionform);
10722:             }
10723:             $request->print('<br clear="all" />');
10724:             $request->print(&show_previous_task_version($request,$symb));
10725: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
10726:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10727:                                        {href=>'',text=>'Select student'}],1,1);
10728: 	    &pickStudentPage($request,$symb);
10729: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
10730:             &startpage($request,$symb,
10731:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10732:                                        {href=>'',text=>'Select student'},
10733:                                        {href=>'',text=>'Grade student'}],1,1);
10734: 	    &displayPage($request,$symb);
10735: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
10736:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10737:                                        {href=>'',text=>'Select student'},
10738:                                        {href=>'',text=>'Grade student'},
10739:                                        {href=>'',text=>'Store grades'}],1,1);
10740: 	    &updateGradeByPage($request,$symb);
10741: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
10742:             &startpage($request,$symb,[{href=>'',text=>'...'},
10743:                                        {href=>'',text=>'Modify grades'}]);
10744: 	    &processGroup($request,$symb);
10745: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
10746:             &startpage($request,$symb);
10747: 	    $request->print(&grading_menu($request,$symb));
10748: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
10749:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
10750: 	    $request->print(&submit_options($request,$symb));
10751:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
10752:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
10753:             $request->print(&listStudents($request,$symb,'graded'));
10754:         } elsif ($command eq 'table' && $perm{'vgr'}) {
10755:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
10756:             $request->print(&submit_options_table($request,$symb));
10757:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
10758:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
10759:             $request->print(&submit_options_sequence($request,$symb));
10760: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
10761:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
10762: 	    $request->print(&viewgrades($request,$symb));
10763: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
10764:             &startpage($request,$symb,[{href=>'',text=>'...'},
10765:                                        {href=>'',text=>'Store grades'}]);
10766: 	    $request->print(&processHandGrade($request,$symb));
10767: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
10768:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
10769:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
10770:                                                                              text=>"Modify grades"},
10771:                                        {href=>'', text=>"Store grades"}]);
10772: 	    $request->print(&editgrades($request,$symb));
10773:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
10774:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
10775:             $request->print(&initialverifyreceipt($request,$symb));
10776: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
10777:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
10778:                                        {href=>'',text=>'Verification Result'}]);
10779: 	    $request->print(&verifyreceipt($request,$symb));
10780:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
10781:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
10782:             $request->print(&process_clicker($request,$symb));
10783:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
10784:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
10785:                                        {href=>'', text=>'Process clicker file'}]);
10786:             $request->print(&process_clicker_file($request,$symb));
10787:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
10788:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
10789:                                        {href=>'', text=>'Process clicker file'},
10790:                                        {href=>'', text=>'Store grades'}]);
10791:             $request->print(&assign_clicker_grades($request,$symb));
10792: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
10793:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10794: 	    $request->print(&upcsvScores_form($request,$symb));
10795: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
10796:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10797: 	    $request->print(&csvupload($request,$symb));
10798: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
10799:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10800: 	    $request->print(&csvuploadmap($request,$symb));
10801: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
10802: 	    if ($env{'form.associate'} ne 'Reverse Association') {
10803:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10804: 		$request->print(&csvuploadoptions($request,$symb));
10805: 	    } else {
10806: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
10807: 		    $env{'form.upfile_associate'} = 'reverse';
10808: 		} else {
10809: 		    $env{'form.upfile_associate'} = 'forward';
10810: 		}
10811:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10812: 		$request->print(&csvuploadmap($request,$symb));
10813: 	    }
10814: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
10815:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10816: 	    $request->print(&csvuploadassign($request,$symb));
10817: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
10818:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10819: 	    $request->print(&scantron_selectphase($request,undef,$symb));
10820:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
10821:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10822:  	    $request->print(&scantron_do_warning($request,$symb));
10823: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
10824:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10825: 	    $request->print(&scantron_validate_file($request,$symb));
10826: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
10827:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10828: 	    $request->print(&scantron_process_students($request,$symb));
10829:  	} elsif ($command eq 'scantronupload' && 
10830:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10831: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10832:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10833:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
10834:  	} elsif ($command eq 'scantronupload_save' &&
10835:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10836: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10837:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10838:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
10839:  	} elsif ($command eq 'scantron_download' &&
10840: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
10841:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10842:  	    $request->print(&scantron_download_scantron_data($request,$symb));
10843:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
10844:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10845:             $request->print(&checkscantron_results($request,$symb));
10846:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
10847:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
10848:             $request->print(&submit_options_download($request,$symb));
10849:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
10850:             &startpage($request,$symb,
10851:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
10852:     {href=>'', text=>'Download submitted files'}]);
10853:             &submit_download_link($request,$symb);
10854: 	} elsif ($command) {
10855:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
10856: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
10857: 	}
10858:     }
10859:     if ($ssi_error) {
10860: 	&ssi_print_error($request);
10861:     }
10862:     if ($env{'form.inhibitmenu'}) {
10863:         $request->print(&Apache::loncommon::end_page());
10864:     } else {
10865:         &Apache::lonquickgrades::endGradeScreen($request);
10866:     }
10867:     &reset_caches();
10868:     return OK;
10869: }
10870: 
10871: 1;
10872: 
10873: __END__;
10874: 
10875: 
10876: =head1 NAME
10877: 
10878: Apache::grades
10879: 
10880: =head1 SYNOPSIS
10881: 
10882: Handles the viewing of grades.
10883: 
10884: This is part of the LearningOnline Network with CAPA project
10885: described at http://www.lon-capa.org.
10886: 
10887: =head1 OVERVIEW
10888: 
10889: Do an ssi with retries:
10890: While I'd love to factor out this with the version in lonprintout,
10891: 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
10892: I'm not quite ready to invent (e.g. an ssi_with_retry object).
10893: 
10894: At least the logic that drives this has been pulled out into loncommon.
10895: 
10896: 
10897: 
10898: ssi_with_retries - Does the server side include of a resource.
10899:                      if the ssi call returns an error we'll retry it up to
10900:                      the number of times requested by the caller.
10901:                      If we still have a problem, no text is appended to the
10902:                      output and we set some global variables.
10903:                      to indicate to the caller an SSI error occurred.  
10904:                      All of this is supposed to deal with the issues described
10905:                      in LON-CAPA BZ 5631 see:
10906:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
10907:                      by informing the user that this happened.
10908: 
10909: Parameters:
10910:   resource   - The resource to include.  This is passed directly, without
10911:                interpretation to lonnet::ssi.
10912:   form       - The form hash parameters that guide the interpretation of the resource
10913:                
10914:   retries    - Number of retries allowed before giving up completely.
10915: Returns:
10916:   On success, returns the rendered resource identified by the resource parameter.
10917: Side Effects:
10918:   The following global variables can be set:
10919:    ssi_error                - If an unrecoverable error occurred this becomes true.
10920:                               It is up to the caller to initialize this to false
10921:                               if desired.
10922:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
10923:                               of the resource that could not be rendered by the ssi
10924:                               call.
10925:    ssi_error_message   - The error string fetched from the ssi response
10926:                               in the event of an error.
10927: 
10928: 
10929: =head1 HANDLER SUBROUTINE
10930: 
10931: ssi_with_retries()
10932: 
10933: =head1 SUBROUTINES
10934: 
10935: =over
10936: 
10937: =head1 Routines to display previous version of a Task for a specific student
10938: 
10939: Tasks are graded pass/fail. Students who have yet to pass a particular Task
10940: can receive another opportunity. Access to tasks is slot-based. If a slot
10941: requires a proctor to check-in the student, a new version of the Task will
10942: be created when the student is checked in to the new opportunity.
10943: 
10944: If a particular student has tried two or more versions of a particular task,
10945: the submission screen provides a user with vgr privileges (e.g., a Course
10946: Coordinator) the ability to display a previous version worked on by the
10947: student.  By default, the current version is displayed. If a previous version
10948: has been selected for display, submission data are only shown that pertain
10949: to that particular version, and the interface to submit grades is not shown.
10950: 
10951: =over 4
10952: 
10953: =item show_previous_task_version()
10954: 
10955: Displays a specified version of a student's Task, as the student sees it.
10956: 
10957: Inputs: 2
10958:         request - request object
10959:         symb    - unique symb for current instance of resource
10960: 
10961: Output: None.
10962: 
10963: Side Effects: calls &show_problem() to print version of Task, with
10964:               version contained in form item: $env{'form.previousversion'}
10965: 
10966: =item choose_task_version_form()
10967: 
10968: Displays a web form used to select which version of a student's view of a
10969: Task should be displayed.  Either launches a pop-up window, or replaces
10970: content in existing pop-up, or replaces page in main window.
10971: 
10972: Inputs: 4
10973:         symb    - unique symb for current instance of resource
10974:         uname   - username of student
10975:         udom    - domain of student
10976:         nomenu  - 1 if display is in a pop-up window, and hence no menu
10977:                   breadcrumbs etc., are displayed
10978: 
10979: Output: 4
10980:         current   - student's current version
10981:         displayed - student's version being displayed
10982:         result    - scalar containing HTML for web form used to switch to
10983:                     a different version (or a link to close window, if pop-up).
10984:         js        - javascript for processing selection in versions web form
10985: 
10986: Side Effects: None.
10987: 
10988: =item previous_display_javascript()
10989: 
10990: Inputs: 2
10991:         nomenu  - 1 if display is in a pop-up window, and hence no menu
10992:                   breadcrumbs etc., are displayed.
10993:         current - student's current version number.
10994: 
10995: Output: 1
10996:         js      - javascript for processing selection in versions web form.
10997: 
10998: Side Effects: None.
10999: 
11000: =back
11001: 
11002: =head1 Routines to process bubblesheet data.
11003: 
11004: =over 4
11005: 
11006: =item scantron_get_correction() : 
11007: 
11008:    Builds the interface screen to interact with the operator to fix a
11009:    specific error condition in a specific scanline
11010: 
11011:  Arguments:
11012:     $r           - Apache request object
11013:     $i           - number of the current scanline
11014:     $scan_record - hash ref as returned from &scantron_parse_scanline()
11015:     $scan_config - hash ref as returned from &get_scantron_config()
11016:     $line        - full contents of the current scanline
11017:     $error       - error condition, valid values are
11018:                    'incorrectCODE', 'duplicateCODE',
11019:                    'doublebubble', 'missingbubble',
11020:                    'duplicateID', 'incorrectID'
11021:     $arg         - extra information needed
11022:        For errors:
11023:          - duplicateID   - paper number that this studentID was seen before on
11024:          - duplicateCODE - array ref of the paper numbers this CODE was
11025:                            seen on before
11026:          - incorrectCODE - current incorrect CODE 
11027:          - doublebubble  - array ref of the bubble lines that have double
11028:                            bubble errors
11029:          - missingbubble - array ref of the bubble lines that have missing
11030:                            bubble errors
11031: 
11032:    $randomorder - True if exam folder has randomorder set
11033:    $randompick  - True if exam folder has randompick set
11034:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
11035:                      for current line to question number used for same question
11036:                      in "Master Seqence" (as seen by Course Coordinator).
11037:    $startline   - Reference to hash where key is question number (0 is first)
11038:                   and value is number of first bubble line for current student
11039:                   or code-based randompick and/or randomorder.
11040: 
11041: 
11042: 
11043: =item  scantron_get_maxbubble() : 
11044: 
11045:    Arguments:
11046:        $nav_error  - Reference to scalar which is a flag to indicate a
11047:                       failure to retrieve a navmap object.
11048:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
11049:        calling routine should trap the error condition and display the warning
11050:        found in &navmap_errormsg().
11051: 
11052:        $scantron_config - Reference to bubblesheet format configuration hash.
11053: 
11054:    Returns the maximum number of bubble lines that are expected to
11055:    occur. Does this by walking the selected sequence rendering the
11056:    resource and then checking &Apache::lonxml::get_problem_counter()
11057:    for what the current value of the problem counter is.
11058: 
11059:    Caches the results to $env{'form.scantron_maxbubble'},
11060:    $env{'form.scantron.bubble_lines.n'}, 
11061:    $env{'form.scantron.first_bubble_line.n'} and
11062:    $env{"form.scantron.sub_bubblelines.n"}
11063:    which are the total number of bubble lines, the number of bubble
11064:    lines for response n and number of the first bubble line for response n,
11065:    and a comma separated list of numbers of bubble lines for sub-questions
11066:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
11067: 
11068: 
11069: =item  scantron_validate_missingbubbles() : 
11070: 
11071:    Validates all scanlines in the selected file to not have any
11072:     answers that don't have bubbles that have not been verified
11073:     to be bubble free.
11074: 
11075: =item  scantron_process_students() : 
11076: 
11077:    Routine that does the actual grading of the bubblesheet information.
11078: 
11079:    The parsed scanline hash is added to %env 
11080: 
11081:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
11082:    foreach resource , with the form data of
11083: 
11084: 	'submitted'     =>'scantron' 
11085: 	'grade_target'  =>'grade',
11086: 	'grade_username'=> username of student
11087: 	'grade_domain'  => domain of student
11088: 	'grade_courseid'=> of course
11089: 	'grade_symb'    => symb of resource to grade
11090: 
11091:     This triggers a grading pass. The problem grading code takes care
11092:     of converting the bubbled letter information (now in %env) into a
11093:     valid submission.
11094: 
11095: =item  scantron_upload_scantron_data() :
11096: 
11097:     Creates the screen for adding a new bubblesheet data file to a course.
11098: 
11099: =item  scantron_upload_scantron_data_save() : 
11100: 
11101:    Adds a provided bubble information data file to the course if user
11102:    has the correct privileges to do so. 
11103: 
11104: =item  valid_file() :
11105: 
11106:    Validates that the requested bubble data file exists in the course.
11107: 
11108: =item  scantron_download_scantron_data() : 
11109: 
11110:    Shows a list of the three internal files (original, corrected,
11111:    skipped) for a specific bubblesheet data file that exists in the
11112:    course.
11113: 
11114: =item  scantron_validate_ID() : 
11115: 
11116:    Validates all scanlines in the selected file to not have any
11117:    invalid or underspecified student/employee IDs
11118: 
11119: =item navmap_errormsg() :
11120: 
11121:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
11122:    Should be called whenever the request to instantiate a navmap object fails.
11123: 
11124: =back
11125: 
11126: =back
11127: 
11128: =cut

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