File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.752: download - view: text, annotated - select for diffs
Mon Oct 8 19:11:01 2018 UTC (5 years, 8 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Explicitly declare use of Apache::lontexconvert().

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.752 2018/10/08 19:11:01 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: 
   30: 
   31: package Apache::grades;
   32: use strict;
   33: use Apache::style;
   34: use Apache::lonxml;
   35: use Apache::lonnet;
   36: use Apache::loncommon;
   37: use Apache::lonhtmlcommon;
   38: use Apache::lonnavmaps;
   39: use Apache::lonhomework;
   40: use Apache::lonpickcode;
   41: use Apache::loncoursedata;
   42: use Apache::lonmsg();
   43: use Apache::Constants qw(:common :http);
   44: use Apache::lonlocal;
   45: use Apache::lonenc;
   46: use Apache::lonstathelpers;
   47: use Apache::lonquickgrades;
   48: use Apache::bridgetask();
   49: use Apache::lontexconvert();
   50: use String::Similarity;
   51: use LONCAPA;
   52: 
   53: use POSIX qw(floor);
   54: 
   55: 
   56: 
   57: my %perm=();
   58: my %old_essays=();
   59: 
   60: #  These variables are used to recover from ssi errors
   61: 
   62: my $ssi_retries = 5;
   63: my $ssi_error;
   64: my $ssi_error_resource;
   65: my $ssi_error_message;
   66: 
   67: 
   68: sub ssi_with_retries {
   69:     my ($resource, $retries, %form) = @_;
   70:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
   71:     if ($response->is_error) {
   72: 	$ssi_error          = 1;
   73: 	$ssi_error_resource = $resource;
   74: 	$ssi_error_message  = $response->code . " " . $response->message;
   75:     }
   76: 
   77:     return $content;
   78: 
   79: }
   80: #
   81: #  Prodcuces an ssi retry failure error message to the user:
   82: #
   83: 
   84: sub ssi_print_error {
   85:     my ($r) = @_;
   86:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
   87:     $r->print('
   88: <br />
   89: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
   90: <p>
   91: '.&mt('Unable to retrieve a resource from a server:').'<br />
   92: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
   93: '.&mt('Error:').' '.$ssi_error_message.'
   94: </p>
   95: <p>'.
   96: &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 />'.
   97: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
   98: '</p>');
   99:     return;
  100: }
  101: 
  102: #
  103: # --- Retrieve the parts from the metadata file.---
  104: # Returns an array of everything that the resources stores away
  105: #
  106: 
  107: sub getpartlist {
  108:     my ($symb,$errorref) = @_;
  109: 
  110:     my $navmap   = Apache::lonnavmaps::navmap->new();
  111:     unless (ref($navmap)) {
  112:         if (ref($errorref)) { 
  113:             $$errorref = 'navmap';
  114:             return;
  115:         }
  116:     }
  117:     my $res      = $navmap->getBySymb($symb);
  118:     my $partlist = $res->parts();
  119:     my $url      = $res->src();
  120:     my $toolsymb;
  121:     if ($url =~ /ext\.tool$/) {
  122:         $toolsymb = $symb;
  123:     }
  124:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys',$toolsymb));
  125: 
  126:     my @stores;
  127:     foreach my $part (@{ $partlist }) {
  128: 	foreach my $key (@metakeys) {
  129: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
  130: 	}
  131:     }
  132:     return @stores;
  133: }
  134: 
  135: #--- Format fullname, username:domain if different for display
  136: #--- Use anywhere where the student names are listed
  137: sub nameUserString {
  138:     my ($type,$fullname,$uname,$udom) = @_;
  139:     if ($type eq 'header') {
  140: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
  141:     } else {
  142: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
  143: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
  144:     }
  145: }
  146: 
  147: #--- Get the partlist and the response type for a given problem. ---
  148: #--- Indicate if a response type is coded handgraded or not. ---
  149: #--- Sets response_error pointer to "1" if navmaps object broken ---
  150: sub response_type {
  151:     my ($symb,$response_error) = @_;
  152: 
  153:     my $navmap = Apache::lonnavmaps::navmap->new();
  154:     unless (ref($navmap)) {
  155:         if (ref($response_error)) {
  156:             $$response_error = 1;
  157:         }
  158:         return;
  159:     }
  160:     my $res = $navmap->getBySymb($symb);
  161:     unless (ref($res)) {
  162:         $$response_error = 1;
  163:         return;
  164:     }
  165:     my $partlist = $res->parts();
  166:     my %vPart = 
  167: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
  168:     my (%response_types,%handgrade);
  169:     foreach my $part (@{ $partlist }) {
  170: 	next if (%vPart && !exists($vPart{$part}));
  171: 
  172: 	my @types = $res->responseType($part);
  173: 	my @ids = $res->responseIds($part);
  174: 	for (my $i=0; $i < scalar(@ids); $i++) {
  175: 	    $response_types{$part}{$ids[$i]} = $types[$i];
  176: 	    $handgrade{$part.'_'.$ids[$i]} = 
  177: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
  178: 				     '.handgrade',$symb);
  179: 	}
  180:     }
  181:     return ($partlist,\%handgrade,\%response_types);
  182: }
  183: 
  184: sub flatten_responseType {
  185:     my ($responseType) = @_;
  186:     my @part_response_id =
  187: 	map { 
  188: 	    my $part = $_;
  189: 	    map {
  190: 		[$part,$_]
  191: 		} sort(keys(%{ $responseType->{$part} }));
  192: 	} sort(keys(%$responseType));
  193:     return @part_response_id;
  194: }
  195: 
  196: sub get_display_part {
  197:     my ($partID,$symb)=@_;
  198:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
  199:     if (defined($display) and $display ne '') {
  200:         $display.= ' (<span class="LC_internal_info">'
  201:                   .&mt('Part ID: [_1]',$partID).'</span>)';
  202:     } else {
  203: 	$display=$partID;
  204:     }
  205:     return $display;
  206: }
  207: 
  208: sub reset_caches {
  209:     &reset_analyze_cache();
  210:     &reset_perm();
  211:     &reset_old_essays();
  212: }
  213: 
  214: {
  215:     my %analyze_cache;
  216:     my %analyze_cache_formkeys;
  217: 
  218:     sub reset_analyze_cache {
  219: 	undef(%analyze_cache);
  220:         undef(%analyze_cache_formkeys);
  221:     }
  222: 
  223:     sub get_analyze {
  224: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
  225: 	my $key = "$symb\0$uname\0$udom";
  226:         if ($type eq 'randomizetry') {
  227:             if ($trial ne '') {
  228:                 $key .= "\0".$trial;
  229:             }
  230:         }
  231: 	if (exists($analyze_cache{$key})) {
  232:             my $getupdate = 0;
  233:             if (ref($add_to_hash) eq 'HASH') {
  234:                 foreach my $item (keys(%{$add_to_hash})) {
  235:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
  236:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
  237:                             $getupdate = 1;
  238:                             last;
  239:                         }
  240:                     } else {
  241:                         $getupdate = 1;
  242:                     }
  243:                 }
  244:             }
  245:             if (!$getupdate) {
  246:                 return $analyze_cache{$key};
  247:             }
  248:         }
  249: 
  250: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  251: 	$url=&Apache::lonnet::clutter($url);
  252:         my %form = ('grade_target'      => 'analyze',
  253:                     'grade_domain'      => $udom,
  254:                     'grade_symb'        => $symb,
  255:                     'grade_courseid'    =>  $env{'request.course.id'},
  256:                     'grade_username'    => $uname,
  257:                     'grade_noincrement' => $no_increment);
  258:         if ($bubbles_per_row ne '') {
  259:             $form{'bubbles_per_row'} = $bubbles_per_row;
  260:         }
  261:         if ($type eq 'randomizetry') {
  262:             $form{'grade_questiontype'} = $type;
  263:             if ($rndseed ne '') {
  264:                 $form{'grade_rndseed'} = $rndseed;
  265:             }
  266:         }
  267:         if (ref($add_to_hash)) {
  268:             %form = (%form,%{$add_to_hash});
  269:         }
  270: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
  271: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  272: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  273:         if (ref($add_to_hash) eq 'HASH') {
  274:             $analyze_cache_formkeys{$key} = $add_to_hash;
  275:         } else {
  276:             $analyze_cache_formkeys{$key} = {};
  277:         }
  278: 	return $analyze_cache{$key} = \%analyze;
  279:     }
  280: 
  281:     sub get_order {
  282: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
  283: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
  284: 	return $analyze->{"$partid.$respid.shown"};
  285:     }
  286: 
  287:     sub get_radiobutton_correct_foil {
  288: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
  289: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
  290:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
  291:         if (ref($foils) eq 'ARRAY') {
  292: 	    foreach my $foil (@{$foils}) {
  293: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  294: 		    return $foil;
  295: 	        }
  296: 	    }
  297: 	}
  298:     }
  299: 
  300:     sub scantron_partids_tograde {
  301:         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row,$scancode) = @_;
  302:         my (%analysis,@parts);
  303:         if (ref($resource)) {
  304:             my $symb = $resource->symb();
  305:             my $add_to_form;
  306:             if ($check_for_randomlist) {
  307:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
  308:             }
  309:             if ($scancode) {
  310:                 if (ref($add_to_form) eq 'HASH') {
  311:                     $add_to_form->{'code_for_randomlist'} = $scancode;
  312:                 } else {
  313:                     $add_to_form = { 'code_for_randomlist' => $scancode,};
  314:                 }
  315:             }
  316:             my $analyze = 
  317:                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
  318:                              undef,undef,undef,$bubbles_per_row);
  319:             if (ref($analyze) eq 'HASH') {
  320:                 %analysis = %{$analyze};
  321:             }
  322:             if (ref($analysis{'parts'}) eq 'ARRAY') {
  323:                 foreach my $part (@{$analysis{'parts'}}) {
  324:                     my ($id,$respid) = split(/\./,$part);
  325:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
  326:                         push(@parts,$part);
  327:                     }
  328:                 }
  329:             }
  330:         }
  331:         return (\%analysis,\@parts);
  332:     }
  333: 
  334: }
  335: 
  336: #--- Clean response type for display
  337: #--- Currently filters option/rank/radiobutton/match/essay/Task
  338: #        response types only.
  339: sub cleanRecord {
  340:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  341: 	$uname,$udom,$type,$trial,$rndseed) = @_;
  342:     my $grayFont = '<span class="LC_internal_info">';
  343:     if ($response =~ /^(option|rank)$/) {
  344: 	my %answer=&Apache::lonnet::str2hash($answer);
  345:         my @answer = %answer;
  346:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
  347: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  348: 	my ($toprow,$bottomrow);
  349: 	foreach my $foil (@$order) {
  350: 	    if ($grading{$foil} == 1) {
  351: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  352: 	    } else {
  353: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  354: 	    }
  355: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  356: 	}
  357: 	return '<blockquote><table border="1">'.
  358: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  359: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  360: 	    $bottomrow.'</tr></table></blockquote>';
  361:     } elsif ($response eq 'match') {
  362: 	my %answer=&Apache::lonnet::str2hash($answer);
  363:         my @answer = %answer;
  364:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
  365: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  366: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  367: 	my ($toprow,$middlerow,$bottomrow);
  368: 	foreach my $foil (@$order) {
  369: 	    my $item=shift(@items);
  370: 	    if ($grading{$foil} == 1) {
  371: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  372: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  373: 	    } else {
  374: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  375: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  376: 	    }
  377: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  378: 	}
  379: 	return '<blockquote><table border="1">'.
  380: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  381: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  382: 	    $middlerow.'</tr>'.
  383: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  384: 	    $bottomrow.'</tr></table></blockquote>';
  385:     } elsif ($response eq 'radiobutton') {
  386: 	my %answer=&Apache::lonnet::str2hash($answer);
  387:         my @answer = %answer;
  388:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
  389: 	my ($toprow,$bottomrow);
  390: 	my $correct = 
  391: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
  392: 	foreach my $foil (@$order) {
  393: 	    if (exists($answer{$foil})) {
  394: 		if ($foil eq $correct) {
  395: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  396: 		} else {
  397: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  398: 		}
  399: 	    } else {
  400: 		$toprow.='<td>'.&mt('false').'</td>';
  401: 	    }
  402: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  403: 	}
  404: 	return '<blockquote><table border="1">'.
  405: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  406: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  407: 	    $bottomrow.'</tr></table></blockquote>';
  408:     } elsif ($response eq 'essay') {
  409: 	if (! exists ($env{'form.'.$symb})) {
  410: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  411: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  412: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  413: 
  414: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  415: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  416: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  417: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  418: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  419: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  420: 	}
  421:         $answer = &Apache::lontexconvert::msgtexconverted($answer);
  422: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  423: 
  424:     } elsif ( $response eq 'organic') {
  425:         my $result=&mt('Smile representation: [_1]',
  426:                            '"<tt>'.&HTML::Entities::encode($answer, '"<>&').'</tt>"');
  427: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  428: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  429: 	return $result;
  430:     } elsif ( $response eq 'Task') {
  431: 	if ( $answer eq 'SUBMITTED') {
  432: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  433: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  434: 	    return $result;
  435: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  436: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  437: 			       keys(%{$record}));
  438: 	    return join('<br />',($version,@matches));
  439: 			       
  440: 			       
  441: 	} else {
  442: 	    my $result =
  443: 		'<p>'
  444: 		.&mt('Overall result: [_1]',
  445: 		     $record->{$version."resource.$respid.$partid.status"})
  446: 		.'</p>';
  447: 	    
  448: 	    $result .= '<ul>';
  449: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  450: 			     keys(%{$record}));
  451: 	    foreach my $grade (sort(@grade)) {
  452: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  453: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  454: 				     $dim, $record->{$grade}).
  455: 			  '</li>';
  456: 	    }
  457: 	    $result.='</ul>';
  458: 	    return $result;
  459: 	}
  460:     } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
  461:         # Respect multiple input fields, see Bug #5409
  462: 	$answer = 
  463: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  464: 							      $answer);
  465: 	return $answer;
  466:     }
  467:     return &HTML::Entities::encode($answer, '"<>&');
  468: }
  469: 
  470: #-- A couple of common js functions
  471: sub commonJSfunctions {
  472:     my $request = shift;
  473:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
  474:     function radioSelection(radioButton) {
  475: 	var selection=null;
  476: 	if (radioButton.length > 1) {
  477: 	    for (var i=0; i<radioButton.length; i++) {
  478: 		if (radioButton[i].checked) {
  479: 		    return radioButton[i].value;
  480: 		}
  481: 	    }
  482: 	} else {
  483: 	    if (radioButton.checked) return radioButton.value;
  484: 	}
  485: 	return selection;
  486:     }
  487: 
  488:     function pullDownSelection(selectOne) {
  489: 	var selection="";
  490: 	if (selectOne.length > 1) {
  491: 	    for (var i=0; i<selectOne.length; i++) {
  492: 		if (selectOne[i].selected) {
  493: 		    return selectOne[i].value;
  494: 		}
  495: 	    }
  496: 	} else {
  497:             // only one value it must be the selected one
  498: 	    return selectOne.value;
  499: 	}
  500:     }
  501: COMMONJSFUNCTIONS
  502: }
  503: 
  504: #--- Dumps the class list with usernames,list of sections,
  505: #--- section, ids and fullnames for each user.
  506: sub getclasslist {
  507:     my ($getsec,$filterbyaccstatus,$getgroup,$symb,$submitonly,$filterbysubmstatus) = @_;
  508:     my @getsec;
  509:     my @getgroup;
  510:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  511:     if (!ref($getsec)) {
  512: 	if ($getsec ne '' && $getsec ne 'all') {
  513: 	    @getsec=($getsec);
  514: 	}
  515:     } else {
  516: 	@getsec=@{$getsec};
  517:     }
  518:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  519:     if (!ref($getgroup)) {
  520: 	if ($getgroup ne '' && $getgroup ne 'all') {
  521: 	    @getgroup=($getgroup);
  522: 	}
  523:     } else {
  524: 	@getgroup=@{$getgroup};
  525:     }
  526:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  527: 
  528:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  529:     # Bail out if we were unable to get the classlist
  530:     return if (! defined($classlist));
  531:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  532:     #
  533:     my %sections;
  534:     my %fullnames;
  535:     my ($cdom,$cnum,$partlist);
  536:     if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
  537:         $cdom = $env{"course.$env{'request.course.id'}.domain"};
  538:         $cnum = $env{"course.$env{'request.course.id'}.num"};
  539:         my $res_error;
  540:         ($partlist,my $handgrade,my $responseType) = &response_type($symb,\$res_error);
  541:     }
  542:     foreach my $student (keys(%$classlist)) {
  543:         my $end      = 
  544:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  545:         my $start    = 
  546:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  547:         my $id       = 
  548:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  549:         my $section  = 
  550:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  551:         my $fullname = 
  552:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  553:         my $status   = 
  554:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  555:         my $group   = 
  556:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  557: 	# filter students according to status selected
  558: 	if ($filterbyaccstatus && (!($stu_status =~ /Any/))) {
  559: 	    if (!($stu_status =~ $status)) {
  560: 		delete($classlist->{$student});
  561: 		next;
  562: 	    }
  563: 	}
  564: 	# filter students according to groups selected
  565: 	my @stu_groups = split(/,/,$group);
  566: 	if (@getgroup) {
  567: 	    my $exclude = 1;
  568: 	    foreach my $grp (@getgroup) {
  569: 	        foreach my $stu_group (@stu_groups) {
  570: 	            if ($stu_group eq $grp) {
  571: 	                $exclude = 0;
  572:     	            } 
  573: 	        }
  574:     	        if (($grp eq 'none') && !$group) {
  575:         	    $exclude = 0;
  576:         	}
  577: 	    }
  578: 	    if ($exclude) {
  579: 	        delete($classlist->{$student});
  580: 		next;
  581: 	    }
  582: 	}
  583:         if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
  584:             my $udom =
  585:                 $classlist->{$student}->[&Apache::loncoursedata::CL_SDOM()];
  586:             my $uname =
  587:                 $classlist->{$student}->[&Apache::loncoursedata::CL_SNAME()];
  588:             if (($symb ne '') && ($udom ne '') && ($uname ne '')) {
  589:                 if ($submitonly eq 'queued') {
  590:                     my %queue_status =
  591:                         &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
  592:                                                                 $udom,$uname);
  593:                     if (!defined($queue_status{'gradingqueue'})) {
  594:                         delete($classlist->{$student});
  595:                         next;
  596:                     }
  597:                 } else {
  598:                     my (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
  599:                     my $submitted = 0;
  600:                     my $graded = 0;
  601:                     my $incorrect = 0;
  602:                     foreach (keys(%status)) {
  603:                         $submitted = 1 if ($status{$_} ne 'nothing');
  604:                         $graded = 1 if ($status{$_} =~ /^ungraded/);
  605:                         $incorrect = 1 if ($status{$_} =~ /^incorrect/);
  606: 
  607:                         my ($foo,$partid,$foo1) = split(/\./,$_);
  608:                         if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
  609:                             $submitted = 0;
  610:                         }
  611:                     }
  612:                     if (!$submitted && ($submitonly eq 'yes' ||
  613:                                         $submitonly eq 'incorrect' ||
  614:                                         $submitonly eq 'graded')) {
  615:                         delete($classlist->{$student});
  616:                         next;
  617:                     } elsif (!$graded && ($submitonly eq 'graded')) {
  618:                         delete($classlist->{$student});
  619:                         next;
  620:                     } elsif (!$incorrect && $submitonly eq 'incorrect') {
  621:                         delete($classlist->{$student});
  622:                         next;
  623:                     }
  624:                 }
  625:             }
  626:         }
  627: 	$section = ($section ne '' ? $section : 'none');
  628: 	if (&canview($section)) {
  629: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  630: 		$sections{$section}++;
  631: 		if ($classlist->{$student}) {
  632: 		    $fullnames{$student}=$fullname;
  633: 		}
  634: 	    } else {
  635: 		delete($classlist->{$student});
  636: 	    }
  637: 	} else {
  638: 	    delete($classlist->{$student});
  639: 	}
  640:     }
  641:     my @sections = sort(keys(%sections));
  642:     return ($classlist,\@sections,\%fullnames);
  643: }
  644: 
  645: sub canmodify {
  646:     my ($sec)=@_;
  647:     if ($perm{'mgr'}) {
  648: 	if (!defined($perm{'mgr_section'})) {
  649: 	    # can modify whole class
  650: 	    return 1;
  651: 	} else {
  652: 	    if ($sec eq $perm{'mgr_section'}) {
  653: 		#can modify the requested section
  654: 		return 1;
  655: 	    } else {
  656: 		# can't modify the request section
  657: 		return 0;
  658: 	    }
  659: 	}
  660:     }
  661:     #can't modify
  662:     return 0;
  663: }
  664: 
  665: sub canview {
  666:     my ($sec)=@_;
  667:     if ($perm{'vgr'}) {
  668: 	if (!defined($perm{'vgr_section'})) {
  669: 	    # can modify whole class
  670: 	    return 1;
  671: 	} else {
  672: 	    if ($sec eq $perm{'vgr_section'}) {
  673: 		#can modify the requested section
  674: 		return 1;
  675: 	    } else {
  676: 		# can't modify the request section
  677: 		return 0;
  678: 	    }
  679: 	}
  680:     }
  681:     #can't modify
  682:     return 0;
  683: }
  684: 
  685: #--- Retrieve the grade status of a student for all the parts
  686: sub student_gradeStatus {
  687:     my ($symb,$udom,$uname,$partlist) = @_;
  688:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  689:     my %partstatus = ();
  690:     foreach (@$partlist) {
  691: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  692: 	$status              = 'nothing' if ($status eq '');
  693: 	$partstatus{$_}      = $status;
  694: 	my $subkey           = "resource.$_.submitted_by";
  695: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  696:     }
  697:     return %partstatus;
  698: }
  699: 
  700: # hidden form and javascript that calls the form
  701: # Use by verifyscript and viewgrades
  702: # Shows a student's view of problem and submission
  703: sub jscriptNform {
  704:     my ($symb) = @_;
  705:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  706:     my $jscript= &Apache::lonhtmlcommon::scripttag(
  707: 	'    function viewOneStudent(user,domain) {'."\n".
  708: 	'	document.onestudent.student.value = user;'."\n".
  709: 	'	document.onestudent.userdom.value = domain;'."\n".
  710: 	'	document.onestudent.submit();'."\n".
  711: 	'    }'."\n".
  712: 	"\n");
  713:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  714: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  715: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  716: 	'<input type="hidden" name="command" value="submission" />'."\n".
  717: 	'<input type="hidden" name="student" value="" />'."\n".
  718: 	'<input type="hidden" name="userdom" value="" />'."\n".
  719: 	'</form>'."\n";
  720:     return $jscript;
  721: }
  722: 
  723: 
  724: 
  725: # Given the score (as a number [0-1] and the weight) what is the final
  726: # point value? This function will round to the nearest tenth, third,
  727: # or quarter if one of those is within the tolerance of .00001.
  728: sub compute_points {
  729:     my ($score, $weight) = @_;
  730:     
  731:     my $tolerance = .00001;
  732:     my $points = $score * $weight;
  733: 
  734:     # Check for nearness to 1/x.
  735:     my $check_for_nearness = sub {
  736:         my ($factor) = @_;
  737:         my $num = ($points * $factor) + $tolerance;
  738:         my $floored_num = floor($num);
  739:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  740:             return $floored_num / $factor;
  741:         }
  742:         return $points;
  743:     };
  744: 
  745:     $points = $check_for_nearness->(10);
  746:     $points = $check_for_nearness->(3);
  747:     $points = $check_for_nearness->(4);
  748:     
  749:     return $points;
  750: }
  751: 
  752: #------------------ End of general use routines --------------------
  753: 
  754: #
  755: # Find most similar essay
  756: #
  757: 
  758: sub most_similar {
  759:     my ($uname,$udom,$symb,$uessay)=@_;
  760: 
  761:     unless ($symb) { return ''; }
  762: 
  763:     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
  764: 
  765: # ignore spaces and punctuation
  766: 
  767:     $uessay=~s/\W+/ /gs;
  768: 
  769: # ignore empty submissions (occuring when only files are sent)
  770: 
  771:     unless ($uessay=~/\w+/s) { return ''; }
  772: 
  773: # these will be returned. Do not care if not at least 50 percent similar
  774:     my $limit=0.6;
  775:     my $sname='';
  776:     my $sdom='';
  777:     my $scrsid='';
  778:     my $sessay='';
  779: # go through all essays ...
  780:     foreach my $tkey (keys(%{$old_essays{$symb}})) {
  781: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  782: # ... except the same student
  783:         next if (($tname eq $uname) && ($tdom eq $udom));
  784: 	my $tessay=$old_essays{$symb}{$tkey};
  785: 	$tessay=~s/\W+/ /gs;
  786: # String similarity gives up if not even limit
  787: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  788: # Found one
  789: 	if ($tsimilar>$limit) {
  790: 	    $limit=$tsimilar;
  791: 	    $sname=$tname;
  792: 	    $sdom=$tdom;
  793: 	    $scrsid=$tcrsid;
  794: 	    $sessay=$old_essays{$symb}{$tkey};
  795: 	}
  796:     }
  797:     if ($limit>0.6) {
  798:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  799:     } else {
  800:        return ('','','','',0);
  801:     }
  802: }
  803: 
  804: #-------------------------------------------------------------------
  805: 
  806: #------------------------------------ Receipt Verification Routines
  807: #
  808: 
  809: sub initialverifyreceipt {
  810:    my ($request,$symb) = @_;
  811:    &commonJSfunctions($request);
  812:    return '<form name="gradingMenu" action=""><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
  813:         &Apache::lonnet::recprefix($env{'request.course.id'}).
  814:         '-<input type="text" name="receipt" size="4" />'.
  815:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  816:         '<input type="hidden" name="command" value="verify" />'.
  817:         "</form>\n";
  818: }
  819: 
  820: #--- Check whether a receipt number is valid.---
  821: sub verifyreceipt {
  822:     my ($request,$symb)  = @_;
  823: 
  824:     my $courseid = $env{'request.course.id'};
  825:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  826: 	$env{'form.receipt'};
  827:     $receipt     =~ s/[^\-\d]//g;
  828: 
  829:     my $title.=
  830: 	'<h3><span class="LC_info">'.
  831: 	&mt('Verifying Receipt Number [_1]',$receipt).
  832: 	'</span></h3>'."\n";
  833: 
  834:     my ($string,$contents,$matches) = ('','',0);
  835:     my (undef,undef,$fullname) = &getclasslist('all','0');
  836:     
  837:     my $receiptparts=0;
  838:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  839: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  840:     my $parts=['0'];
  841:     if ($receiptparts) {
  842:         my $res_error; 
  843:         ($parts)=&response_type($symb,\$res_error);
  844:         if ($res_error) {
  845:             return &navmap_errormsg();
  846:         } 
  847:     }
  848:     
  849:     my $header = 
  850: 	&Apache::loncommon::start_data_table().
  851: 	&Apache::loncommon::start_data_table_header_row().
  852: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  853: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  854: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  855:     if ($receiptparts) {
  856: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  857:     }
  858:     $header.=
  859: 	&Apache::loncommon::end_data_table_header_row();
  860: 
  861:     foreach (sort 
  862: 	     {
  863: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  864: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  865: 		 }
  866: 		 return $a cmp $b;
  867: 	     } (keys(%$fullname))) {
  868: 	my ($uname,$udom)=split(/\:/);
  869: 	foreach my $part (@$parts) {
  870: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  871: 		$contents.=
  872: 		    &Apache::loncommon::start_data_table_row().
  873: 		    '<td>&nbsp;'."\n".
  874: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  875: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  876: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  877: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  878: 		if ($receiptparts) {
  879: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  880: 		}
  881: 		$contents.= 
  882: 		    &Apache::loncommon::end_data_table_row()."\n";
  883: 		
  884: 		$matches++;
  885: 	    }
  886: 	}
  887:     }
  888:     if ($matches == 0) {
  889:         $string = $title
  890:                  .'<p class="LC_warning">'
  891:                  .&mt('No match found for the above receipt number.')
  892:                  .'</p>';
  893:     } else {
  894: 	$string = &jscriptNform($symb).$title.
  895: 	    '<p>'.
  896: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
  897: 	    '</p>'.
  898: 	    $header.
  899: 	    $contents.
  900: 	    &Apache::loncommon::end_data_table()."\n";
  901:     }
  902:     return $string;
  903: }
  904: 
  905: #--- This is called by a number of programs.
  906: #--- Called from the Grading Menu - View/Grade an individual student
  907: #--- Also called directly when one clicks on the subm button 
  908: #    on the problem page.
  909: sub listStudents {
  910:     my ($request,$symb,$submitonly) = @_;
  911: 
  912:     my $is_tool   = ($symb =~ /ext\.tool$/);
  913:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  914:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  915:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  916:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  917:     unless ($submitonly) {
  918:        $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  919:     }
  920: 
  921:     my $result='';
  922:     my $res_error;
  923:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
  924: 
  925:     my %js_lt = &Apache::lonlocal::texthash (
  926: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
  927: 		'single'   => 'Please select the student before clicking on the Next button.',
  928: 	     );
  929:     &js_escape(\%js_lt);
  930:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
  931:     function checkSelect(checkBox) {
  932: 	var ctr=0;
  933: 	var sense="";
  934: 	if (checkBox.length > 1) {
  935: 	    for (var i=0; i<checkBox.length; i++) {
  936: 		if (checkBox[i].checked) {
  937: 		    ctr++;
  938: 		}
  939: 	    }
  940: 	    sense = '$js_lt{'multiple'}';
  941: 	} else {
  942: 	    if (checkBox.checked) {
  943: 		ctr = 1;
  944: 	    }
  945: 	    sense = '$js_lt{'single'}';
  946: 	}
  947: 	if (ctr == 0) {
  948: 	    alert(sense);
  949: 	    return false;
  950: 	}
  951: 	document.gradesub.submit();
  952:     }
  953: 
  954:     function reLoadList(formname) {
  955: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  956: 	formname.command.value = 'submission';
  957: 	formname.submit();
  958:     }
  959: LISTJAVASCRIPT
  960: 
  961:     &commonJSfunctions($request);
  962:     $request->print($result);
  963: 
  964:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  965: 	"\n";
  966: 	
  967:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
  968:     unless ($is_tool) {
  969:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
  970:                       .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
  971:                       .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
  972:                       .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
  973:                       .&Apache::lonhtmlcommon::row_closure();
  974:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
  975:                       .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
  976:                       .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
  977:                       .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
  978:                       .&Apache::lonhtmlcommon::row_closure();
  979:     }
  980: 
  981:     my $submission_options;
  982:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  983:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  984:     $env{'form.Status'} = $saveStatus;
  985:     my %optiontext;
  986:     if ($is_tool) {
  987:         %optiontext = &Apache::lonlocal::texthash (
  988:                           lastonly => 'last transaction',
  989:                           last     => 'last transaction with details',
  990:                           datesub  => 'all transactions',
  991:                           all      => 'all transactions with details',
  992:                       );
  993:     } else {
  994:         %optiontext = &Apache::lonlocal::texthash (
  995:                           lastonly => 'last submission',
  996:                           last     => 'last submission with details',
  997:                           datesub  => 'all submissions',
  998:                           all      => 'all submissions with details',
  999:                       );
 1000:     }
 1001:     $submission_options.=
 1002:         '<span class="LC_nobreak">'.
 1003:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
 1004:         $optiontext{'lastonly'}.' </label></span>'."\n".
 1005:         '<span class="LC_nobreak">'.
 1006:         '<label><input type="radio" name="lastSub" value="last" /> '.
 1007:         $optiontext{'last'}.' </label></span>'."\n".
 1008:         '<span class="LC_nobreak">'.
 1009:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
 1010:         $optiontext{'datesub'}.'</label></span>'."\n".
 1011:         '<span class="LC_nobreak">'.
 1012:         '<label><input type="radio" name="lastSub" value="all" /> '.
 1013:         $optiontext{'all'}.'</label></span>';
 1014:     my $viewtitle;
 1015:     if ($is_tool) {
 1016:         $viewtitle = &mt('View Transactions');
 1017:     } else {
 1018:         $viewtitle = &mt('View Submissions');
 1019:     }
 1020:     $gradeTable .= &Apache::lonhtmlcommon::row_title($viewtitle)
 1021:                   .$submission_options
 1022:                   .&Apache::lonhtmlcommon::row_closure();
 1023: 
 1024:     my $closure;
 1025:     if (($is_tool) && (exists($env{'form.Status'}))) {
 1026:         $closure = 1;
 1027:     }
 1028:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
 1029:                   .'<select name="increment">'
 1030:                   .'<option value="1">'.&mt('Whole Points').'</option>'
 1031:                   .'<option value=".5">'.&mt('Half Points').'</option>'
 1032:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
 1033:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
 1034:                   .'</select>'
 1035:                   .&Apache::lonhtmlcommon::row_closure($closure);
 1036: 
 1037:     $gradeTable .= 
 1038:         &build_section_inputs().
 1039: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
 1040: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1041: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
 1042: 
 1043:     if (exists($env{'form.Status'})) {
 1044: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
 1045:     } else {
 1046:         if ($is_tool) {
 1047:             $closure = 1;
 1048:         }
 1049:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
 1050:                       .&Apache::lonhtmlcommon::StatusOptions(
 1051:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
 1052:                       .&Apache::lonhtmlcommon::row_closure($closure);
 1053:     }
 1054: 
 1055:     unless ($is_tool) {
 1056:         $closure = 1;
 1057:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
 1058:                       .'<input type="checkbox" name="checkPlag" checked="checked" />'
 1059:                       .&Apache::lonhtmlcommon::row_closure($closure);
 1060:     }
 1061:     $gradeTable .= &Apache::lonhtmlcommon::end_pick_box();
 1062:     my $regrademsg;
 1063:     if ($is_tool) {
 1064:         $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.");
 1065:     } else {
 1066:         $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.");
 1067:     }
 1068:     $gradeTable .= '<p>'
 1069:                   .$regrademsg."\n"
 1070:                   .'<input type="hidden" name="command" value="processGroup" />'
 1071:                   .'</p>';
 1072: 
 1073: # checkall buttons
 1074:     $gradeTable.=&check_script('gradesub', 'stuinfo');
 1075:     $gradeTable.='<input type="button" '."\n".
 1076:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
 1077:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
 1078:     $gradeTable.=&check_buttons();
 1079:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
 1080:     $gradeTable.= &Apache::loncommon::start_data_table().
 1081: 	&Apache::loncommon::start_data_table_header_row();
 1082:     my $loop = 0;
 1083:     while ($loop < 2) {
 1084: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
 1085: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
 1086: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1087: 	    foreach my $part (sort(@$partlist)) {
 1088: 		my $display_part=
 1089: 		    &get_display_part((split(/_/,$part))[0],$symb);
 1090: 		$gradeTable.=
 1091: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
 1092: 	    }
 1093: 	} elsif ($submitonly eq 'queued') {
 1094: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
 1095: 	}
 1096: 	$loop++;
 1097: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
 1098:     }
 1099:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
 1100: 
 1101:     my $ctr = 0;
 1102:     foreach my $student (sort 
 1103: 			 {
 1104: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 1105: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 1106: 			     }
 1107: 			     return $a cmp $b;
 1108: 			 }
 1109: 			 (keys(%$fullname))) {
 1110: 	my ($uname,$udom) = split(/:/,$student);
 1111: 
 1112: 	my %status = ();
 1113: 
 1114: 	if ($submitonly eq 'queued') {
 1115: 	    my %queue_status = 
 1116: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 1117: 							$udom,$uname);
 1118: 	    next if (!defined($queue_status{'gradingqueue'}));
 1119: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
 1120: 	}
 1121: 
 1122: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1123: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
 1124: 	    my $submitted = 0;
 1125: 	    my $graded = 0;
 1126: 	    my $incorrect = 0;
 1127: 	    foreach (keys(%status)) {
 1128: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1129: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1130: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1131: 		
 1132: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1133: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1134: 		    $submitted = 0;
 1135: 		    my ($part)=split(/\./,$partid);
 1136: 		    $gradeTable.='<input type="hidden" name="'.
 1137: 			$student.':'.$part.':submitted_by" value="'.
 1138: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1139: 		}
 1140: 	    }
 1141: 	    
 1142: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1143: 				     $submitonly eq 'incorrect' ||
 1144: 				     $submitonly eq 'graded'));
 1145: 	    next if (!$graded && ($submitonly eq 'graded'));
 1146: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1147: 	}
 1148: 
 1149: 	$ctr++;
 1150: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1151:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1152: 	if ( $perm{'vgr'} eq 'F' ) {
 1153: 	    if ($ctr%2 ==1) {
 1154: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1155: 	    }
 1156: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1157:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1158:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1159: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1160: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1161: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1162: 
 1163: 	    if ($submitonly ne 'all') {
 1164: 		foreach (sort(keys(%status))) {
 1165: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1166: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1167: 		}
 1168: 	    }
 1169: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1170: 	    if ($ctr%2 ==0) {
 1171: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1172: 	    }
 1173: 	}
 1174:     }
 1175:     if ($ctr%2 ==1) {
 1176: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1177: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1178: 		foreach (@$partlist) {
 1179: 		    $gradeTable.='<td>&nbsp;</td>';
 1180: 		}
 1181: 	    } elsif ($submitonly eq 'queued') {
 1182: 		$gradeTable.='<td>&nbsp;</td>';
 1183: 	    }
 1184: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1185:     }
 1186: 
 1187:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1188:         '<input type="button" '.
 1189:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
 1190:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1191:     if ($ctr == 0) {
 1192: 	my $num_students=(scalar(keys(%$fullname)));
 1193: 	if ($num_students eq 0) {
 1194: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1195: 	} else {
 1196: 	    my $submissions='submissions';
 1197: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1198: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1199: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1200: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1201: 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
 1202: 		    $num_students).
 1203: 		'</span><br />';
 1204: 	}
 1205:     } elsif ($ctr == 1) {
 1206: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1207:     }
 1208:     $request->print($gradeTable);
 1209:     return '';
 1210: }
 1211: 
 1212: #---- Called from the listStudents routine
 1213: 
 1214: sub check_script {
 1215:     my ($form, $type)=@_;
 1216:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
 1217:     function checkall() {
 1218:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1219:             ele = document.forms.'.$form.'.elements[i];
 1220:             if (ele.name == "'.$type.'") {
 1221:             document.forms.'.$form.'.elements[i].checked=true;
 1222:                                        }
 1223:         }
 1224:     }
 1225: 
 1226:     function checksec() {
 1227:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1228:             ele = document.forms.'.$form.'.elements[i];
 1229:            string = document.forms.'.$form.'.chksec.value;
 1230:            if
 1231:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1232:               document.forms.'.$form.'.elements[i].checked=true;
 1233:             }
 1234:         }
 1235:     }
 1236: 
 1237: 
 1238:     function uncheckall() {
 1239:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1240:             ele = document.forms.'.$form.'.elements[i];
 1241:             if (ele.name == "'.$type.'") {
 1242:             document.forms.'.$form.'.elements[i].checked=false;
 1243:                                        }
 1244:         }
 1245:     }
 1246: 
 1247: '."\n");
 1248:     return $chkallscript;
 1249: }
 1250: 
 1251: sub check_buttons {
 1252:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1253:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1254:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1255:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1256:     return $buttons;
 1257: }
 1258: 
 1259: #     Displays the submissions for one student or a group of students
 1260: sub processGroup {
 1261:     my ($request,$symb)  = @_;
 1262:     my $ctr        = 0;
 1263:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1264:     my $total      = scalar(@stuchecked)-1;
 1265: 
 1266:     foreach my $student (@stuchecked) {
 1267: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1268: 	$env{'form.student'}        = $uname;
 1269: 	$env{'form.userdom'}        = $udom;
 1270: 	$env{'form.fullname'}       = $fullname;
 1271: 	&submission($request,$ctr,$total,$symb);
 1272: 	$ctr++;
 1273:     }
 1274:     return '';
 1275: }
 1276: 
 1277: #------------------------------------------------------------------------------------
 1278: #
 1279: #-------------------------- Next few routines handles grading by student, essentially
 1280: #                           handles essay response type problem/part
 1281: #
 1282: #--- Javascript to handle the submission page functionality ---
 1283: sub sub_page_js {
 1284:     my $request = shift;
 1285:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1286:     &js_escape(\$alertmsg);
 1287:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1288:     function updateRadio(formname,id,weight) {
 1289: 	var gradeBox = formname["GD_BOX"+id];
 1290: 	var radioButton = formname["RADVAL"+id];
 1291: 	var oldpts = formname["oldpts"+id].value;
 1292: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1293: 	gradeBox.value = pts;
 1294: 	var resetbox = false;
 1295: 	if (isNaN(pts) || pts < 0) {
 1296: 	    alert("$alertmsg"+pts);
 1297: 	    for (var i=0; i<radioButton.length; i++) {
 1298: 		if (radioButton[i].checked) {
 1299: 		    gradeBox.value = i;
 1300: 		    resetbox = true;
 1301: 		}
 1302: 	    }
 1303: 	    if (!resetbox) {
 1304: 		formtextbox.value = "";
 1305: 	    }
 1306: 	    return;
 1307: 	}
 1308: 
 1309: 	if (pts > weight) {
 1310: 	    var resp = confirm("You entered a value ("+pts+
 1311: 			       ") greater than the weight for the part. Accept?");
 1312: 	    if (resp == false) {
 1313: 		gradeBox.value = oldpts;
 1314: 		return;
 1315: 	    }
 1316: 	}
 1317: 
 1318: 	for (var i=0; i<radioButton.length; i++) {
 1319: 	    radioButton[i].checked=false;
 1320: 	    if (pts == i && pts != "") {
 1321: 		radioButton[i].checked=true;
 1322: 	    }
 1323: 	}
 1324: 	updateSelect(formname,id);
 1325: 	formname["stores"+id].value = "0";
 1326:     }
 1327: 
 1328:     function writeBox(formname,id,pts) {
 1329: 	var gradeBox = formname["GD_BOX"+id];
 1330: 	if (checkSolved(formname,id) == 'update') {
 1331: 	    gradeBox.value = pts;
 1332: 	} else {
 1333: 	    var oldpts = formname["oldpts"+id].value;
 1334: 	    gradeBox.value = oldpts;
 1335: 	    var radioButton = formname["RADVAL"+id];
 1336: 	    for (var i=0; i<radioButton.length; i++) {
 1337: 		radioButton[i].checked=false;
 1338: 		if (i == oldpts) {
 1339: 		    radioButton[i].checked=true;
 1340: 		}
 1341: 	    }
 1342: 	}
 1343: 	formname["stores"+id].value = "0";
 1344: 	updateSelect(formname,id);
 1345: 	return;
 1346:     }
 1347: 
 1348:     function clearRadBox(formname,id) {
 1349: 	if (checkSolved(formname,id) == 'noupdate') {
 1350: 	    updateSelect(formname,id);
 1351: 	    return;
 1352: 	}
 1353: 	gradeSelect = formname["GD_SEL"+id];
 1354: 	for (var i=0; i<gradeSelect.length; i++) {
 1355: 	    if (gradeSelect[i].selected) {
 1356: 		var selectx=i;
 1357: 	    }
 1358: 	}
 1359: 	var stores = formname["stores"+id];
 1360: 	if (selectx == stores.value) { return };
 1361: 	var gradeBox = formname["GD_BOX"+id];
 1362: 	gradeBox.value = "";
 1363: 	var radioButton = formname["RADVAL"+id];
 1364: 	for (var i=0; i<radioButton.length; i++) {
 1365: 	    radioButton[i].checked=false;
 1366: 	}
 1367: 	stores.value = selectx;
 1368:     }
 1369: 
 1370:     function checkSolved(formname,id) {
 1371: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1372: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1373: 	    if (!reply) {return "noupdate";}
 1374: 	    formname.overRideScore.value = 'yes';
 1375: 	}
 1376: 	return "update";
 1377:     }
 1378: 
 1379:     function updateSelect(formname,id) {
 1380: 	formname["GD_SEL"+id][0].selected = true;
 1381: 	return;
 1382:     }
 1383: 
 1384: //=========== Check that a point is assigned for all the parts  ============
 1385:     function checksubmit(formname,val,total,parttot) {
 1386: 	formname.gradeOpt.value = val;
 1387: 	if (val == "Save & Next") {
 1388: 	    for (i=0;i<=total;i++) {
 1389: 		for (j=0;j<parttot;j++) {
 1390: 		    var partid = formname["partid"+i+"_"+j].value;
 1391: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1392: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1393: 			if (points == "") {
 1394: 			    var name = formname["name"+i].value;
 1395: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1396: 			    var resp = confirm("You did not assign a score for "+studentID+
 1397: 					       ", part "+partid+". Continue?");
 1398: 			    if (resp == false) {
 1399: 				formname["GD_BOX"+i+"_"+partid].focus();
 1400: 				return false;
 1401: 			    }
 1402: 			}
 1403: 		    }
 1404: 		}
 1405: 	    }
 1406: 	}
 1407: 	formname.submit();
 1408:     }
 1409: 
 1410: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1411:     function checkSubmitPage(formname,total) {
 1412: 	noscore = new Array(100);
 1413: 	var ptr = 0;
 1414: 	for (i=1;i<total;i++) {
 1415: 	    var partid = formname["q_"+i].value;
 1416: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1417: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1418: 		var status = formname["solved"+i+"_"+partid].value;
 1419: 		if (points == "" && status != "correct_by_student") {
 1420: 		    noscore[ptr] = i;
 1421: 		    ptr++;
 1422: 		}
 1423: 	    }
 1424: 	}
 1425: 	if (ptr != 0) {
 1426: 	    var sense = ptr == 1 ? ": " : "s: ";
 1427: 	    var prolist = "";
 1428: 	    if (ptr == 1) {
 1429: 		prolist = noscore[0];
 1430: 	    } else {
 1431: 		var i = 0;
 1432: 		while (i < ptr-1) {
 1433: 		    prolist += noscore[i]+", ";
 1434: 		    i++;
 1435: 		}
 1436: 		prolist += "and "+noscore[i];
 1437: 	    }
 1438: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1439: 	    if (resp == false) {
 1440: 		return false;
 1441: 	    }
 1442: 	}
 1443: 
 1444: 	formname.submit();
 1445:     }
 1446: SUBJAVASCRIPT
 1447: }
 1448: 
 1449: #--- javascript for essay type problem --
 1450: sub sub_page_kw_js {
 1451:     my $request = shift;
 1452:     my $iconpath = $request->dir_config('lonIconsURL');
 1453:     &commonJSfunctions($request);
 1454: 
 1455:     my $inner_js_msg_central= (<<INNERJS);
 1456: <script type="text/javascript">
 1457:     function checkInput() {
 1458:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1459:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1460:       var usrctr = document.msgcenter.usrctr.value;
 1461:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1462:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1463: 
 1464:       var msgchk = "";
 1465:       if (document.msgcenter.subchk.checked) {
 1466:          msgchk = "msgsub,";
 1467:       }
 1468:       var includemsg = 0;
 1469:       for (var i=1; i<=nmsg; i++) {
 1470:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1471:           var frmmsg = document.msgcenter["msg"+i];
 1472:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1473:           var showflg = opener.document.SCORE["shownOnce"+i];
 1474:           showflg.value = "1";
 1475:           var chkbox = document.msgcenter["msgn"+i];
 1476:           if (chkbox.checked) {
 1477:              msgchk += "savemsg"+i+",";
 1478:              includemsg = 1;
 1479:           }
 1480:       }
 1481:       if (document.msgcenter.newmsgchk.checked) {
 1482:          msgchk += "newmsg"+usrctr;
 1483:          includemsg = 1;
 1484:       }
 1485:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1486:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1487:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1488:       includemsg.value = msgchk;
 1489: 
 1490:       self.close()
 1491: 
 1492:     }
 1493: </script>
 1494: INNERJS
 1495: 
 1496:     my $inner_js_highlight_central= (<<INNERJS);
 1497: <script type="text/javascript">
 1498:     function updateChoice(flag) {
 1499:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1500:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1501:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1502:       opener.document.SCORE.refresh.value = "on";
 1503:       if (opener.document.SCORE.keywords.value!=""){
 1504:          opener.document.SCORE.submit();
 1505:       }
 1506:       self.close()
 1507:     }
 1508: </script>
 1509: INNERJS
 1510: 
 1511:     my $start_page_msg_central = 
 1512:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1513: 				       {'js_ready'  => 1,
 1514: 					'only_body' => 1,
 1515: 					'bgcolor'   =>'#FFFFFF',});
 1516:     my $end_page_msg_central = 
 1517: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1518: 
 1519: 
 1520:     my $start_page_highlight_central = 
 1521:         &Apache::loncommon::start_page('Highlight Central',
 1522: 				       $inner_js_highlight_central,
 1523: 				       {'js_ready'  => 1,
 1524: 					'only_body' => 1,
 1525: 					'bgcolor'   =>'#FFFFFF',});
 1526:     my $end_page_highlight_central = 
 1527: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1528: 
 1529:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1530:     $docopen=~s/^document\.//;
 1531:     my %js_lt = &Apache::lonlocal::texthash(
 1532:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
 1533:                 plse => 'Please select a word or group of words from document and then click this link.',
 1534:                 adds => 'Add selection to keyword list? Edit if desired.',
 1535:                 col1 => 'red',
 1536:                 col2 => 'green',
 1537:                 col3 => 'blue',
 1538:                 siz1 => 'normal',
 1539:                 siz2 => '+1',
 1540:                 siz3 => '+2',
 1541:                 sty1 => 'normal',
 1542:                 sty2 => 'italic',
 1543:                 sty3 => 'bold',
 1544:              );
 1545:     my %html_js_lt = &Apache::lonlocal::texthash(
 1546:                 comp => 'Compose Message for: ',
 1547:                 incl => 'Include',
 1548:                 type => 'Type',
 1549:                 subj => 'Subject',
 1550:                 mesa => 'Message',
 1551:                 new  => 'New',
 1552:                 save => 'Save',
 1553:                 canc => 'Cancel',
 1554:                 kehi => 'Keyword Highlight Options',
 1555:                 txtc => 'Text Color',
 1556:                 font => 'Font Size',
 1557:                 fnst => 'Font Style',
 1558:              );
 1559:     &js_escape(\%js_lt);
 1560:     &html_escape(\%html_js_lt);
 1561:     &js_escape(\%html_js_lt);
 1562:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1563: 
 1564: //===================== Show list of keywords ====================
 1565:   function keywords(formname) {
 1566:     var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
 1567:     if (nret==null) return;
 1568:     formname.keywords.value = nret;
 1569: 
 1570:     if (formname.keywords.value != "") {
 1571: 	formname.refresh.value = "on";
 1572: 	formname.submit();
 1573:     }
 1574:     return;
 1575:   }
 1576: 
 1577: //===================== Script to view submitted by ==================
 1578:   function viewSubmitter(submitter) {
 1579:     document.SCORE.refresh.value = "on";
 1580:     document.SCORE.NCT.value = "1";
 1581:     document.SCORE.unamedom0.value = submitter;
 1582:     document.SCORE.submit();
 1583:     return;
 1584:   }
 1585: 
 1586: //===================== Script to add keyword(s) ==================
 1587:   function getSel() {
 1588:     if (document.getSelection) txt = document.getSelection();
 1589:     else if (document.selection) txt = document.selection.createRange().text;
 1590:     else return;
 1591:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1592:     if (cleantxt=="") {
 1593: 	alert("$js_lt{'plse'}");
 1594: 	return;
 1595:     }
 1596:     var nret = prompt("$js_lt{'adds'}",cleantxt);
 1597:     if (nret==null) return;
 1598:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1599:     if (document.SCORE.keywords.value != "") {
 1600: 	document.SCORE.refresh.value = "on";
 1601: 	document.SCORE.submit();
 1602:     }
 1603:     return;
 1604:   }
 1605: 
 1606: //====================== Script for composing message ==============
 1607:    // preload images
 1608:    img1 = new Image();
 1609:    img1.src = "$iconpath/mailbkgrd.gif";
 1610:    img2 = new Image();
 1611:    img2.src = "$iconpath/mailto.gif";
 1612: 
 1613:   function msgCenter(msgform,usrctr,fullname) {
 1614:     var Nmsg  = msgform.savemsgN.value;
 1615:     savedMsgHeader(Nmsg,usrctr,fullname);
 1616:     var subject = msgform.msgsub.value;
 1617:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1618:     re = /msgsub/;
 1619:     var shwsel = "";
 1620:     if (re.test(msgchk)) { shwsel = "checked" }
 1621:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1622:     displaySubject(checkEntities(subject),shwsel);
 1623:     for (var i=1; i<=Nmsg; i++) {
 1624: 	var testmsg = "savemsg"+i+",";
 1625: 	re = new RegExp(testmsg,"g");
 1626: 	shwsel = "";
 1627: 	if (re.test(msgchk)) { shwsel = "checked" }
 1628: 	var message = document.SCORE["savemsg"+i].value;
 1629: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1630: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1631: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1632:     }
 1633:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1634:     shwsel = "";
 1635:     re = /newmsg/;
 1636:     if (re.test(msgchk)) { shwsel = "checked" }
 1637:     newMsg(newmsg,shwsel);
 1638:     msgTail(); 
 1639:     return;
 1640:   }
 1641: 
 1642:   function checkEntities(strx) {
 1643:     if (strx.length == 0) return strx;
 1644:     var orgStr = ["&", "<", ">", '"']; 
 1645:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1646:     var counter = 0;
 1647:     while (counter < 4) {
 1648: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1649: 	counter++;
 1650:     }
 1651:     return strx;
 1652:   }
 1653: 
 1654:   function strReplace(strx, orgStr, newStr) {
 1655:     return strx.split(orgStr).join(newStr);
 1656:   }
 1657: 
 1658:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1659:     var height = 70*Nmsg+250;
 1660:     if (height > 600) {
 1661: 	height = 600;
 1662:     }
 1663:     var xpos = (screen.width-600)/2;
 1664:     xpos = (xpos < 0) ? '0' : xpos;
 1665:     var ypos = (screen.height-height)/2-30;
 1666:     ypos = (ypos < 0) ? '0' : ypos;
 1667: 
 1668:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
 1669:     pWin.focus();
 1670:     pDoc = pWin.document;
 1671:     pDoc.$docopen;
 1672:     pDoc.write('$start_page_msg_central');
 1673: 
 1674:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1675:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1676:     pDoc.write("<h1>&nbsp;$html_js_lt{'comp'}\"+fullname+\"<\\/h1>");
 1677: 
 1678:     pDoc.write('<table style="border:1px solid black;"><tr>');
 1679:     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>");
 1680: }
 1681:     function displaySubject(msg,shwsel) {
 1682:     pDoc = pWin.document;
 1683:     pDoc.write("<tr>");
 1684:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1685:     pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
 1686:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1687: }
 1688: 
 1689:   function displaySavedMsg(ctr,msg,shwsel) {
 1690:     pDoc = pWin.document;
 1691:     pDoc.write("<tr>");
 1692:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1693:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1694:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1695: }
 1696: 
 1697:   function newMsg(newmsg,shwsel) {
 1698:     pDoc = pWin.document;
 1699:     pDoc.write("<tr>");
 1700:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1701:     pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
 1702:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1703: }
 1704: 
 1705:   function msgTail() {
 1706:     pDoc = pWin.document;
 1707:     //pDoc.write("<\\/table>");
 1708:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1709:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1710:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
 1711:     pDoc.write("<\\/form>");
 1712:     pDoc.write('$end_page_msg_central');
 1713:     pDoc.close();
 1714: }
 1715: 
 1716: //====================== Script for keyword highlight options ==============
 1717:   function kwhighlight() {
 1718:     var kwclr    = document.SCORE.kwclr.value;
 1719:     var kwsize   = document.SCORE.kwsize.value;
 1720:     var kwstyle  = document.SCORE.kwstyle.value;
 1721:     var redsel = "";
 1722:     var grnsel = "";
 1723:     var blusel = "";
 1724:     var txtcol1 = "$js_lt{'col1'}";
 1725:     var txtcol2 = "$js_lt{'col2'}";
 1726:     var txtcol3 = "$js_lt{'col3'}";
 1727:     var txtsiz1 = "$js_lt{'siz1'}";
 1728:     var txtsiz2 = "$js_lt{'siz2'}";
 1729:     var txtsiz3 = "$js_lt{'siz3'}";
 1730:     var txtsty1 = "$js_lt{'sty1'}";
 1731:     var txtsty2 = "$js_lt{'sty2'}";
 1732:     var txtsty3 = "$js_lt{'sty3'}";
 1733:     if (kwclr=="red")   {var redsel="checked='checked'"};
 1734:     if (kwclr=="green") {var grnsel="checked='checked'"};
 1735:     if (kwclr=="blue")  {var blusel="checked='checked'"};
 1736:     var sznsel = "";
 1737:     var sz1sel = "";
 1738:     var sz2sel = "";
 1739:     if (kwsize=="0")  {var sznsel="checked='checked'"};
 1740:     if (kwsize=="+1") {var sz1sel="checked='checked'"};
 1741:     if (kwsize=="+2") {var sz2sel="checked='checked'"};
 1742:     var synsel = "";
 1743:     var syisel = "";
 1744:     var sybsel = "";
 1745:     if (kwstyle=="")    {var synsel="checked='checked'"};
 1746:     if (kwstyle=="<i>") {var syisel="checked='checked'"};
 1747:     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
 1748:     highlightCentral();
 1749:     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
 1750:     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
 1751:     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
 1752:     highlightend();
 1753:     return;
 1754:   }
 1755: 
 1756:   function highlightCentral() {
 1757: //    if (window.hwdWin) window.hwdWin.close();
 1758:     var xpos = (screen.width-400)/2;
 1759:     xpos = (xpos < 0) ? '0' : xpos;
 1760:     var ypos = (screen.height-330)/2-30;
 1761:     ypos = (ypos < 0) ? '0' : ypos;
 1762: 
 1763:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1764:     hwdWin.focus();
 1765:     var hDoc = hwdWin.document;
 1766:     hDoc.$docopen;
 1767:     hDoc.write('$start_page_highlight_central');
 1768:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1769:     hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
 1770: 
 1771:     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
 1772:     hDoc.write("<th>$html_js_lt{'txtc'}<\\/th><th>$html_js_lt{'font'}<\\/th><th>$html_js_lt{'fnst'}<\\/th><\\/tr>");
 1773:   }
 1774: 
 1775:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1776:     var hDoc = hwdWin.document;
 1777:     hDoc.write("<tr>");
 1778:     hDoc.write("<td align=\\"left\\">");
 1779:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
 1780:     hDoc.write("<td align=\\"left\\">");
 1781:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
 1782:     hDoc.write("<td align=\\"left\\">");
 1783:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
 1784:     hDoc.write("<\\/tr>");
 1785:   }
 1786: 
 1787:   function highlightend() { 
 1788:     var hDoc = hwdWin.document;
 1789:     hDoc.write("<\\/table><br \\/>");
 1790:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
 1791:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
 1792:     hDoc.write("<\\/form>");
 1793:     hDoc.write('$end_page_highlight_central');
 1794:     hDoc.close();
 1795:   }
 1796: 
 1797: SUBJAVASCRIPT
 1798: }
 1799: 
 1800: sub get_increment {
 1801:     my $increment = $env{'form.increment'};
 1802:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1803:         $increment != .1) {
 1804:         $increment = 1;
 1805:     }
 1806:     return $increment;
 1807: }
 1808: 
 1809: sub gradeBox_start {
 1810:     return (
 1811:         &Apache::loncommon::start_data_table()
 1812:        .&Apache::loncommon::start_data_table_header_row()
 1813:        .'<th>'.&mt('Part').'</th>'
 1814:        .'<th>'.&mt('Points').'</th>'
 1815:        .'<th>&nbsp;</th>'
 1816:        .'<th>'.&mt('Assign Grade').'</th>'
 1817:        .'<th>'.&mt('Weight').'</th>'
 1818:        .'<th>'.&mt('Grade Status').'</th>'
 1819:        .&Apache::loncommon::end_data_table_header_row()
 1820:     );
 1821: }
 1822: 
 1823: sub gradeBox_end {
 1824:     return (
 1825:         &Apache::loncommon::end_data_table()
 1826:     );
 1827: }
 1828: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1829: sub gradeBox {
 1830:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1831:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1832: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1833:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1834:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1835:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1836:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1837:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1838: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1839:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1840:     my $display_part= &get_display_part($partid,$symb);
 1841:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1842: 				       [$partid]);
 1843:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1844:     if ($last_resets{$partid}) {
 1845:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1846:     }
 1847:     my $result=&Apache::loncommon::start_data_table_row();
 1848:     my $ctr = 0;
 1849:     my $thisweight = 0;
 1850:     my $increment = &get_increment();
 1851: 
 1852:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1853:     while ($thisweight<=$wgt) {
 1854: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1855:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1856: 	    $thisweight.')" value="'.$thisweight.'" '.
 1857: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1858: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1859:         $thisweight += $increment;
 1860: 	$ctr++;
 1861:     }
 1862:     $radio.='</tr></table>';
 1863: 
 1864:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1865: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1866: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1867: 	$wgt.')" /></td>'."\n";
 1868:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1869: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1870: 	' </td>'."\n";
 1871:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1872: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1873:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1874: 	$line.='<option></option>'.
 1875: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1876:     } else {
 1877: 	$line.='<option selected="selected"></option>'.
 1878: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1879:     }
 1880:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1881: 
 1882: 
 1883:     $result .= 
 1884: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 1885:     $result.=&Apache::loncommon::end_data_table_row();
 1886:     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
 1887:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1888: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1889: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1890: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1891:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1892:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1893:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1894:         $aggtries.'" />'."\n";
 1895:     my $res_error;
 1896:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 1897:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
 1898:     if ($res_error) {
 1899:         return &navmap_errormsg();
 1900:     }
 1901:     return $result;
 1902: }
 1903: 
 1904: sub handback_box {
 1905:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
 1906:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
 1907:     my (@respids);
 1908:     my @part_response_id = &flatten_responseType($responseType);
 1909:     foreach my $part_response_id (@part_response_id) {
 1910:     	my ($part,$resp) = @{ $part_response_id };
 1911:         if ($part eq $partid) {
 1912:             push(@respids,$resp);
 1913:         }
 1914:     }
 1915:     my $result;
 1916:     foreach my $respid (@respids) {
 1917: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1918: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1919: 	next if (!@$files);
 1920: 	my $file_counter = 0;
 1921: 	foreach my $file (@$files) {
 1922: 	    if ($file =~ /\/portfolio\//) {
 1923:                 $file_counter++;
 1924:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1925:     	        my ($name,$version,$ext) = &Apache::lonnet::file_name_version_ext($file_disp);
 1926:     	        $file_disp = "$name.$ext";
 1927:     	        $file = $file_path.$file_disp;
 1928:     	        $result.=&mt('Return commented version of [_1] to student.',
 1929:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1930:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1931:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
 1932: 	    }
 1933: 	}
 1934:         if ($file_counter) {
 1935:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
 1936:                        '<span class="LC_info">'.
 1937:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
 1938:         }
 1939:     }
 1940:     return $result;    
 1941: }
 1942: 
 1943: sub show_problem {
 1944:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1945:     my $rendered;
 1946:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1947:     &Apache::lonxml::remember_problem_counter();
 1948:     if ($mode eq 'both' or $mode eq 'text') {
 1949: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1950: 						       $env{'request.course.id'},
 1951: 						       undef,\%form);
 1952:     }
 1953:     if ($removeform) {
 1954: 	$rendered=~s|<form(.*?)>||g;
 1955: 	$rendered=~s|</form>||g;
 1956: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1957:     }
 1958:     my $companswer;
 1959:     if ($mode eq 'both' or $mode eq 'answer') {
 1960: 	&Apache::lonxml::restore_problem_counter();
 1961: 	$companswer=
 1962: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1963: 						    $env{'request.course.id'},
 1964: 						    %form);
 1965:     }
 1966:     if ($removeform) {
 1967: 	$companswer=~s|<form(.*?)>||g;
 1968: 	$companswer=~s|</form>||g;
 1969: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1970:     }
 1971:     my $renderheading = &mt('View of the problem');
 1972:     my $answerheading = &mt('Correct answer');
 1973:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 1974:         my $stu_fullname = $env{'form.fullname'};
 1975:         if ($stu_fullname eq '') {
 1976:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
 1977:         }
 1978:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
 1979:         if ($forwhom ne '') {
 1980:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
 1981:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
 1982:         }
 1983:     }
 1984:     $rendered=
 1985:         '<div class="LC_Box">'
 1986:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
 1987:        .$rendered
 1988:        .'</div>';
 1989:     $companswer=
 1990:         '<div class="LC_Box">'
 1991:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
 1992:        .$companswer
 1993:        .'</div>';
 1994:     my $result;
 1995:     if ($mode eq 'both') {
 1996:         $result=$rendered.$companswer;
 1997:     } elsif ($mode eq 'text') {
 1998:         $result=$rendered;
 1999:     } elsif ($mode eq 'answer') {
 2000:         $result=$companswer;
 2001:     }
 2002:     return $result;
 2003: }
 2004: 
 2005: sub files_exist {
 2006:     my ($r, $symb) = @_;
 2007:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 2008:     foreach my $student (@students) {
 2009:         my ($uname,$udom,$fullname) = split(/:/,$student);
 2010:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 2011: 					      $udom,$uname);
 2012:         my ($string,$timestamp)= &get_last_submission(\%record);
 2013:         foreach my $submission (@$string) {
 2014:             my ($partid,$respid) =
 2015: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2016:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 2017: 					   \%record);
 2018:             return 1 if (@$files);
 2019:         }
 2020:     }
 2021:     return 0;
 2022: }
 2023: 
 2024: sub download_all_link {
 2025:     my ($r,$symb) = @_;
 2026:     unless (&files_exist($r, $symb)) {
 2027:        $r->print(&mt('There are currently no submitted documents.'));
 2028:        return;
 2029:     }
 2030:     my $all_students = 
 2031: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 2032: 
 2033:     my $parts =
 2034: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 2035: 
 2036:     my $identifier = &Apache::loncommon::get_cgi_id();
 2037:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 2038:                              'cgi.'.$identifier.'.symb' => $symb,
 2039:                              'cgi.'.$identifier.'.parts' => $parts,});
 2040:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 2041: 	      &mt('Download All Submitted Documents').'</a>');
 2042:     return;
 2043: }
 2044: 
 2045: sub submit_download_link {
 2046:     my ($request,$symb) = @_;
 2047:     if (!$symb) { return ''; }
 2048: #FIXME: Figure out which type of problem this is and provide appropriate download
 2049:     my $res_error;
 2050:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
 2051:     if (ref($res_error)) {
 2052:         if ($$res_error) {
 2053:             $request->print(&mt('An error occurred retrieving response types'));
 2054:             return;
 2055:         }
 2056:     }
 2057:     my ($numupload,$numessay) = (0,0);
 2058:     if (ref($responseType) eq 'HASH') {
 2059:         foreach my $part (sort(keys(%$responseType))) {
 2060:             foreach my $id (sort(keys(%{ $responseType->{$part} }))) {
 2061:                 my $responsetype = $responseType->{$part}->{$id};
 2062:                 if ($responsetype eq 'essay') {
 2063:                     my $uploadedfiletypes =
 2064:                         &Apache::lonnet::EXT("resource.$part".'_'."$id.uploadedfiletypes",$symb);
 2065:                     if ($uploadedfiletypes) {
 2066:                         $numupload++;
 2067:                     } else {
 2068:                         $numessay++;
 2069:                     }
 2070:                 }
 2071:             }
 2072:         }
 2073:     }
 2074:     if (($numupload) || ($numessay)) {
 2075:         my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
 2076:         my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 2077:         my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
 2078:         (undef,undef,my $fullname) = &getclasslist($getsec,1,$getgroup,$symb,$submitonly,1);
 2079:         if (ref($fullname) eq 'HASH') {
 2080:             my @students = map { $_.':'.$fullname->{$_} } (keys(%{$fullname}));
 2081:             if (@students) {
 2082:                 @{$env{'form.stuinfo'}} = @students;
 2083:                 if ($numupload) {
 2084:                     &download_all_link($request,$symb);
 2085:                 }
 2086: # FIXME Need to provide a mechanism to download essays, i.e., if $numessay > 0
 2087: # Needs to omit user's identity if resource instance is for an anonymous survey.
 2088:             } else {
 2089:                 $request->print(&mt('No students match the criteria you selected'));
 2090:             }
 2091:         } else {
 2092:             $request->print(&mt('Could not retrieve student information'));
 2093:         }
 2094:     } else {
 2095:         $request->print(&mt('No essayresponse items found'));
 2096:     }
 2097:     return;
 2098: }
 2099: 
 2100: sub build_section_inputs {
 2101:     my $section_inputs;
 2102:     if ($env{'form.section'} eq '') {
 2103:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 2104:     } else {
 2105:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 2106:         foreach my $section (@sections) {
 2107:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 2108:         }
 2109:     }
 2110:     return $section_inputs;
 2111: }
 2112: 
 2113: # --------------------------- show submissions of a student, option to grade 
 2114: sub submission {
 2115:     my ($request,$counter,$total,$symb) = @_;
 2116:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 2117:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 2118:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2119:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 2120: 
 2121:     my $probtitle=&Apache::lonnet::gettitle($symb); 
 2122:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 2123:     my $is_tool = ($symb =~ /ext\.tool$/);
 2124: 
 2125:     if (!&canview($usec)) {
 2126:         $request->print(
 2127:             '<span class="LC_warning">'.
 2128:             &mt('Unable to view requested student.').
 2129:             ' '.&mt('([_1] in section [_2] in course id [_3])',
 2130:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
 2131:             '</span>');
 2132: 	return;
 2133:     }
 2134: 
 2135:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 2136:     unless ($is_tool) { 
 2137:         if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 2138:         if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 2139:     }
 2140:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 2141:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 2142: 	'" src="'.$request->dir_config('lonIconsURL').
 2143: 	'/check.gif" height="16" border="0" />';
 2144: 
 2145:     # header info
 2146:     if ($counter == 0) {
 2147: 	&sub_page_js($request);
 2148: 	&sub_page_kw_js($request);
 2149: 
 2150: 	# option to display problem, only once else it cause problems 
 2151:         # with the form later since the problem has a form.
 2152: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 2153: 	    my $mode;
 2154: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 2155: 		$mode='both';
 2156: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 2157: 		$mode='text';
 2158: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 2159: 		$mode='answer';
 2160: 	    }
 2161: 	    &Apache::lonxml::clear_problem_counter();
 2162: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 2163: 	}
 2164: 
 2165: 	# kwclr is the only variable that is guaranteed not to be blank 
 2166:         # if this subroutine has been called once.
 2167: 	my %keyhash = ();
 2168: #	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 2169:         if (1) {
 2170: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 2171: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 2172: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 2173: 
 2174: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2175: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 2176: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 2177: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 2178: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 2179: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 2180: 		$keyhash{$symb.'_subject'} : $probtitle;
 2181: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 2182: 	}
 2183: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 2184: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 2185: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 2186: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 2187: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 2188: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 2189: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 2190: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 2191: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 2192: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 2193: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 2194: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 2195: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 2196: 			&build_section_inputs().
 2197: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 2198: 			'<input type="hidden" name="NCT"'.
 2199: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 2200: #	if ($env{'form.handgrade'} eq 'yes') {
 2201:         if (1) {
 2202: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 2203: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 2204: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 2205: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 2206: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2207: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2208: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2209: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 2210: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 2211: 	    }
 2212: 	}
 2213: 	
 2214: 	my ($cts,$prnmsg) = (1,'');
 2215: 	while ($cts <= $env{'form.savemsgN'}) {
 2216: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2217: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2218: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2219: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2220: 		'" />'."\n".
 2221: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2222: 	    $cts++;
 2223: 	}
 2224: 	$request->print($prnmsg);
 2225: 
 2226: #	if ($env{'form.handgrade'} eq 'yes') {
 2227:         unless ($is_tool) {
 2228: 
 2229:             my %lt = &Apache::lonlocal::texthash(
 2230:                           keyh => 'Keyword Highlighting for Essays',
 2231:                           keyw => 'Keyword Options',
 2232:                           list => 'List',
 2233:                           past => 'Paste Selection to List',
 2234:                           high => 'Highlight Attribute',
 2235:                      );    
 2236: #
 2237: # Print out the keyword options line
 2238: #
 2239: 	    $request->print(
 2240:                 '<div class="LC_columnSection">'
 2241:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
 2242:                .&Apache::lonhtmlcommon::funclist_from_array(
 2243:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
 2244:                      '<a href="#" onmousedown="javascript:getSel(); return false"
 2245:  class="page">'.$lt{'past'}.'</a>',
 2246:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
 2247:                     {legend => $lt{'keyw'}})
 2248:                .'</fieldset></div>'
 2249:             );
 2250: 
 2251: #
 2252: # Load the other essays for similarity check
 2253: #
 2254:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2255: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2256: 	    $apath=&escape($apath);
 2257: 	    $apath=~s/\W/\_/gs;
 2258:             &init_old_essays($symb,$apath,$adom,$aname);
 2259:         }
 2260:     }
 2261: 
 2262: # This is where output for one specific student would start
 2263:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2264:     $request->print(
 2265:         "\n\n"
 2266:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2267:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2268:        ."\n"
 2269:     );
 2270: 
 2271:     # Show additional functions if allowed
 2272:     if ($perm{'vgr'}) {
 2273:         $request->print(
 2274:             &Apache::loncommon::track_student_link(
 2275:                 'View recent activity',
 2276:                 $uname,$udom,'check')
 2277:            .' '
 2278:         );
 2279:     }
 2280:     if ($perm{'opa'}) {
 2281:         $request->print(
 2282:             &Apache::loncommon::pprmlink(
 2283:                 &mt('Set/Change parameters'),
 2284:                 $uname,$udom,$symb,'check'));
 2285:     }
 2286: 
 2287:     # Show Problem
 2288:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2289: 	my $mode;
 2290: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2291: 	    $mode='both';
 2292: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2293: 	    $mode='text';
 2294: 	} elsif ($env{'form.vAns'} eq 'all') {
 2295: 	    $mode='answer';
 2296: 	}
 2297: 	&Apache::lonxml::clear_problem_counter();
 2298: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2299:     }
 2300: 
 2301:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2302:     my $res_error;
 2303:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2304:     if ($res_error) {
 2305:         $request->print(&navmap_errormsg());
 2306:         return;
 2307:     }
 2308: 
 2309:     # Display student info
 2310:     $request->print(($counter == 0 ? '' : '<br />'));
 2311: 
 2312:     my $boxtitle = &mt('Submissions');
 2313:     if ($is_tool) {
 2314:         $boxtitle = &mt('Transactions')
 2315:     }
 2316:     my $result='<div class="LC_Box">'
 2317:               .'<h3 class="LC_hcell">'.$boxtitle.'</h3>';
 2318:     $result.='<input type="hidden" name="name'.$counter.
 2319:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2320: #    if ($env{'form.handgrade'} eq 'no') {
 2321:     unless ($is_tool) {
 2322:         $result.='<p class="LC_info">'
 2323:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2324:                 ."</p>\n";
 2325:     }
 2326: 
 2327:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2328:     my $fullname;
 2329:     my $col_fullnames = [];
 2330: #    if ($env{'form.handgrade'} eq 'yes') {
 2331:     unless ($is_tool) {
 2332: 	(my $sub_result,$fullname,$col_fullnames)=
 2333: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2334: 				 $counter);
 2335: 	$result.=$sub_result;
 2336:     }
 2337:     $request->print($result."\n");
 2338:     
 2339:     # print student answer/submission
 2340:     # Options are (1) Handgraded submission only
 2341:     #             (2) Last submission, includes submission that is not handgraded 
 2342:     #                  (for multi-response type part)
 2343:     #             (3) Last submission plus the parts info
 2344:     #             (4) The whole record for this student
 2345:     
 2346:     my ($string,$timestamp)= &get_last_submission(\%record,$is_tool);
 2347: 	
 2348:     my $lastsubonly;
 2349: 
 2350:     if ($$timestamp eq '') {
 2351:         $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2352:     } elsif ($is_tool) {
 2353:         $lastsubonly =
 2354:             '<div class="LC_grade_submissions_body">'
 2355:            .'<b>'.&mt('Date Grade Passed Back:').'</b> '.$$timestamp."</div>\n";
 2356:     } else {
 2357:         $lastsubonly =
 2358:             '<div class="LC_grade_submissions_body">'
 2359:            .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
 2360: 
 2361: 	my %seenparts;
 2362: 	my @part_response_id = &flatten_responseType($responseType);
 2363: 	foreach my $part (@part_response_id) {
 2364: 	    next if ($env{'form.lastSub'} eq 'hdgrade' 
 2365: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2366: 
 2367: 	    my ($partid,$respid) = @{ $part };
 2368: 	    my $display_part=&get_display_part($partid,$symb);
 2369: 	    if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2370: 		if (exists($seenparts{$partid})) { next; }
 2371: 		$seenparts{$partid}=1;
 2372:                 $request->print(
 2373:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2374:                     ' <b>'.&mt('Collaborative submission by: [_1]',
 2375:                                '<a href="javascript:viewSubmitter(\''.
 2376:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
 2377:                                '\');" target="_self">'.
 2378:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
 2379:                     '<br />');
 2380: 		next;
 2381: 		}
 2382: 	    my $responsetype = $responseType->{$partid}->{$respid};
 2383: 	    if (!exists($record{"resource.$partid.$respid.submission"})) {
 2384:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2385:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2386:                     ' <span class="LC_internal_info">'.
 2387:                     '('.&mt('Response ID: [_1]',$respid).')'.
 2388:                     '</span>&nbsp; &nbsp;'.
 2389: 	       	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2390: 		next;
 2391: 	    }
 2392: 	    foreach my $submission (@$string) {
 2393: 		my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2394: 		if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2395: 		my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
 2396: 		# Similarity check
 2397:                 my $similar='';
 2398:                 my ($type,$trial,$rndseed);
 2399:                 if ($hide eq 'rand') {
 2400:                     $type = 'randomizetry';
 2401:                     $trial = $record{"resource.$partid.tries"};
 2402:                     $rndseed = $record{"resource.$partid.rndseed"};
 2403:                 }
 2404: 	        if ($env{'form.checkPlag'}) {
 2405:     		    my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2406: 		        &most_similar($uname,$udom,$symb,$subval);
 2407: 		    if ($osim) {
 2408: 			$osim=int($osim*100.0);
 2409: 			my %old_course_desc = 
 2410: 			    &Apache::lonnet::coursedescription($ocrsid,
 2411: 							{'one_time' => 1});
 2412: 
 2413:                         if ($hide eq 'anon') {
 2414:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2415:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2416:                         } else {
 2417: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
 2418: 				&mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2419: 				    $osim,
 2420: 				    &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2421: 				        $old_course_desc{'description'},
 2422: 				        $old_course_desc{'num'},
 2423: 				        $old_course_desc{'domain'}).
 2424: 				    '</span></h3><blockquote><i>'.
 2425: 				    &keywords_highlight($oessay).
 2426: 				    '</i></blockquote><hr />';
 2427:                         }
 2428: 	            }
 2429: 		}
 2430: 		my $order=&get_order($partid,$respid,$symb,$uname,$udom,
 2431:                                      undef,$type,$trial,$rndseed);
 2432:                 if ($env{'form.lastSub'} eq 'lastonly' || $env{'form.lastSub'} eq 'datesub' || $env{'form.lastSub'} =~ /^(last|all)$/ || ($env{'form.lastSub'} eq 'hdgrade' && 
 2433: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2434: 		    my $display_part=&get_display_part($partid,$symb);
 2435:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
 2436:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2437:                         ' <span class="LC_internal_info">'.
 2438:                         '('.&mt('Response ID: [_1]',$respid).')'.
 2439:                         '</span>&nbsp; &nbsp;';
 2440: 		    my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2441:                         
 2442: 		    if (@$files) {
 2443:                         if ($hide eq 'anon') {
 2444:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2445:                         } else {
 2446:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
 2447:                                         .'<br /><span class="LC_warning">';
 2448:                             if(@$files == 1) {
 2449:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
 2450:                             } else {
 2451:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
 2452:                             }
 2453:                             $lastsubonly .= '</span>';                         
 2454:                             foreach my $file (@$files) {
 2455:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2456:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
 2457:                             }
 2458:                         }
 2459: 			$lastsubonly.='<br />';
 2460:                     }
 2461:                     if ($hide eq 'anon') {
 2462:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
 2463:                     } else {
 2464:              	        $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
 2465:                         if ($draft) {
 2466:                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
 2467:                         }
 2468:                         $subval =
 2469: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
 2470: 					 $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
 2471:                         if ($responsetype eq 'essay') {
 2472:                             $subval =~ s{\n}{<br />}g;
 2473:                         }
 2474:                         $lastsubonly.=$subval."\n";
 2475:                     }
 2476: 	            if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2477: 		    $lastsubonly.='</div>';
 2478: 		}
 2479:             }
 2480: 	}
 2481: 	$lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2482:     }
 2483:     $request->print($lastsubonly);
 2484:     if ($env{'form.lastSub'} eq 'datesub') {
 2485:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2486: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2487:   
 2488:     } 
 2489:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2490:         my $identifier = (&canmodify($usec)? $counter : '');
 2491:         $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2492: 								 $env{'request.course.id'},
 2493: 								 $last,'.submission',
 2494: 								 'Apache::grades::keywords_highlight',
 2495:                                                                  $usec,$identifier));
 2496:     }
 2497:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2498: 	.$udom.'" />'."\n");
 2499:     # return if view submission with no grading option
 2500:     if (!&canmodify($usec)) {
 2501: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
 2502: 	return;
 2503:     } else {
 2504: 	$request->print('</div>'."\n");
 2505:     }
 2506: 
 2507:     # essay grading message center
 2508: #    if ($env{'form.handgrade'} eq 'yes') {
 2509:     if (1) {
 2510: 	my $result='<div class="LC_grade_message_center">';
 2511:     
 2512: 	$result.='<div class="LC_grade_message_center_header">'.
 2513: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2514: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2515: 	my $msgfor = $givenn.' '.$lastname;
 2516: 	if (scalar(@$col_fullnames) > 0) {
 2517: 	    my $lastone = pop(@$col_fullnames);
 2518: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2519: 	}
 2520: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2521: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2522: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2523: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2524: 	    ',\''.$msgfor.'\');" target="_self">'.
 2525: 	    &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
 2526: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2527: 	    ' <img src="'.$request->dir_config('lonIconsURL').
 2528: 	    '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
 2529: 	    '<br />&nbsp;('.
 2530: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2531: 	$result.='</div></div>';
 2532: 	$request->print($result);
 2533:     }
 2534: 
 2535:     my %seen = ();
 2536:     my @partlist;
 2537:     my @gradePartRespid;
 2538:     my @part_response_id;
 2539:     if ($is_tool) {
 2540:         @part_response_id = ([0,'']);
 2541:     } else {
 2542:         @part_response_id = &flatten_responseType($responseType);
 2543:     }
 2544:     $request->print(
 2545:         '<div class="LC_Box">'
 2546:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2547:     );
 2548:     $request->print(&gradeBox_start());
 2549:     foreach my $part_response_id (@part_response_id) {
 2550:     	my ($partid,$respid) = @{ $part_response_id };
 2551: 	my $part_resp = join('_',@{ $part_response_id });
 2552: 	next if ($seen{$partid} > 0);
 2553: 	$seen{$partid}++;
 2554: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2555: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2556: 	push(@partlist,$partid);
 2557: 	push(@gradePartRespid,$partid.'.'.$respid);
 2558: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2559:     }
 2560:     $request->print(&gradeBox_end()); # </div>
 2561:     $request->print('</div>');
 2562: 
 2563:     $request->print('<div class="LC_grade_info_links">');
 2564:     $request->print('</div>');
 2565: 
 2566:     $result='<input type="hidden" name="partlist'.$counter.
 2567: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2568:     $result.='<input type="hidden" name="gradePartRespid'.
 2569: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2570:     my $ctr = 0;
 2571:     while ($ctr < scalar(@partlist)) {
 2572: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2573: 	    $partlist[$ctr].'" />'."\n";
 2574: 	$ctr++;
 2575:     }
 2576:     $request->print($result.''."\n");
 2577: 
 2578: # Done with printing info for one student
 2579: 
 2580:     $request->print('</div>');#LC_grade_show_user
 2581: 
 2582: 
 2583:     # print end of form
 2584:     if ($counter == $total) {
 2585:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2586: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2587: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2588: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2589: 	my $ntstu ='<select name="NTSTU">'.
 2590: 	    '<option>1</option><option>2</option>'.
 2591: 	    '<option>3</option><option>5</option>'.
 2592: 	    '<option>7</option><option>10</option></select>'."\n";
 2593: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2594: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2595:         $endform.=&mt('[_1]student(s)',$ntstu);
 2596: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2597: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2598: 	    '<input type="button" value="'.&mt('Next').'" '.
 2599: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2600:         $endform.='<span class="LC_warning">'.
 2601:                   &mt('(Next and Previous (student) do not save the scores.)').
 2602:                   '</span>'."\n" ;
 2603:         $endform.="<input type='hidden' value='".&get_increment().
 2604:             "' name='increment' />";
 2605: 	$endform.='</td></tr></table></form>';
 2606: 	$request->print($endform);
 2607:     }
 2608:     return '';
 2609: }
 2610: 
 2611: sub check_collaborators {
 2612:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2613:     my ($result,@col_fullnames);
 2614:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2615:     foreach my $part (keys(%$handgrade)) {
 2616: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2617: 					'.maxcollaborators',
 2618: 					$symb,$udom,$uname);
 2619: 	next if ($ncol <= 0);
 2620: 	$part =~ s/\_/\./g;
 2621: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2622: 	my (@good_collaborators, @bad_collaborators);
 2623: 	foreach my $possible_collaborator
 2624: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2625: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2626: 	    next if ($possible_collaborator eq '');
 2627: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
 2628: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2629: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2630: 	    # Doing this grep allows 'fuzzy' specification
 2631: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2632: 			       keys(%$classlist));
 2633: 	    if (! scalar(@matches)) {
 2634: 		push(@bad_collaborators, $possible_collaborator);
 2635: 	    } else {
 2636: 		push(@good_collaborators, @matches);
 2637: 	    }
 2638: 	}
 2639: 	if (scalar(@good_collaborators) != 0) {
 2640: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
 2641: 	    foreach my $name (@good_collaborators) {
 2642: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2643: 		push(@col_fullnames, $givenn.' '.$lastname);
 2644: 		$result.='<li>'.$fullname->{$name}.'</li>';
 2645: 	    }
 2646: 	    $result.='</ol><br />'."\n";
 2647: 	    my ($part)=split(/\./,$part);
 2648: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2649: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2650: 		"\n";
 2651: 	}
 2652: 	if (scalar(@bad_collaborators) > 0) {
 2653: 	    $result.='<div class="LC_warning">';
 2654: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2655: 	    $result .= '</div>';
 2656: 	}         
 2657: 	if (scalar(@bad_collaborators > $ncol)) {
 2658: 	    $result .= '<div class="LC_warning">';
 2659: 	    $result .= &mt('This student has submitted too many '.
 2660: 		'collaborators.  Maximum is [_1].',$ncol);
 2661: 	    $result .= '</div>';
 2662: 	}
 2663:     }
 2664:     return ($result,$fullname,\@col_fullnames);
 2665: }
 2666: 
 2667: #--- Retrieve the last submission for all the parts
 2668: sub get_last_submission {
 2669:     my ($returnhash,$is_tool)=@_;
 2670:     my (@string,$timestamp,%lasthidden);
 2671:     if ($$returnhash{'version'}) {
 2672: 	my %lasthash=();
 2673: 	my ($version);
 2674: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2675: 	    foreach my $key (sort(split(/\:/,
 2676: 					$$returnhash{$version.':keys'}))) {
 2677: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2678: 		$timestamp = 
 2679: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2680: 	    }
 2681: 	}
 2682:         my (%typeparts,%randombytry);
 2683:         my $showsurv = 
 2684:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2685:         foreach my $key (sort(keys(%lasthash))) {
 2686:             if ($key =~ /\.type$/) {
 2687:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2688:                     ($lasthash{$key} eq 'anonsurveycred') ||
 2689:                     ($lasthash{$key} eq 'randomizetry')) {
 2690:                     my ($ign,@parts) = split(/\./,$key);
 2691:                     pop(@parts);
 2692:                     my $id = join('.',@parts);
 2693:                     if ($lasthash{$key} eq 'randomizetry') {
 2694:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
 2695:                     } else {
 2696:                         unless ($showsurv) {
 2697:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2698:                         }
 2699:                     }
 2700:                     delete($lasthash{$key});
 2701:                 }
 2702:             }
 2703:         }
 2704:         my @hidden = keys(%typeparts);
 2705:         my @randomize = keys(%randombytry);
 2706: 	foreach my $key (keys(%lasthash)) {
 2707: 	    next if ($key !~ /\.submission$/);
 2708:             my $hide;
 2709:             if (@hidden) {
 2710:                 foreach my $id (@hidden) {
 2711:                     if ($key =~ /^\Q$id\E/) {
 2712:                         $hide = 'anon';
 2713:                         last;
 2714:                     }
 2715:                 }
 2716:             }
 2717:             unless ($hide) {
 2718:                 if (@randomize) {
 2719:                     foreach my $id (@randomize) {
 2720:                         if ($key =~ /^\Q$id\E/) {
 2721:                             $hide = 'rand';
 2722:                             last;
 2723:                         }
 2724:                     }
 2725:                 }
 2726:             }
 2727: 	    my ($partid,$foo) = split(/submission$/,$key);
 2728: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
 2729:             push(@string, join(':', $key, $hide, $draft, (
 2730:                 ref($lasthash{$key}) eq 'ARRAY' ?
 2731:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
 2732: 	}
 2733:     }
 2734:     if (!@string) {
 2735:         my $msg;
 2736:         if ($is_tool) {
 2737:             $msg = &mt('No grade passed back.');
 2738:         } else {
 2739:             $msg = &mt('Nothing submitted - no attempts.');
 2740:         }
 2741: 	$string[0] =
 2742: 	    '<span class="LC_warning">'.$msg.'</span>';
 2743:     }
 2744:     return (\@string,\$timestamp);
 2745: }
 2746: 
 2747: #--- High light keywords, with style choosen by user.
 2748: sub keywords_highlight {
 2749:     my $string    = shift;
 2750:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2751:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2752:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2753:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2754:     foreach my $keyword (@keylist) {
 2755: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2756:     }
 2757:     return $string;
 2758: }
 2759: 
 2760: # For Tasks provide a mechanism to display previous version for one specific student
 2761: 
 2762: sub show_previous_task_version {
 2763:     my ($request,$symb) = @_;
 2764:     if ($symb eq '') {
 2765:         $request->print(
 2766:             '<span class="LC_error">'.
 2767:             &mt('Unable to handle ambiguous references.').
 2768:             '</span>');
 2769:         return '';
 2770:     }
 2771:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
 2772:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2773:     if (!&canview($usec)) {
 2774:         $request->print(
 2775:             '<span class="LC_warning">'.
 2776:             &mt('Unable to view previous version for requested student.').
 2777:             ' '.&mt('([_1] in section [_2] in course id [_3])',
 2778:                     $uname.':'.$udom,$usec,$env{'request.course.id'}).
 2779:             '</span>');
 2780:         return;
 2781:     }
 2782:     my $mode = 'both';
 2783:     my $isTask = ($symb =~/\.task$/);
 2784:     if ($isTask) {
 2785:         if ($env{'form.previousversion'} =~ /^\d+$/) {
 2786:             if ($env{'form.fullname'} eq '') {
 2787:                 $env{'form.fullname'} =
 2788:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
 2789:             }
 2790:             my $probtitle=&Apache::lonnet::gettitle($symb);
 2791:             $request->print("\n\n".
 2792:                             '<div class="LC_grade_show_user">'.
 2793:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 2794:                             '</h2>'."\n");
 2795:             &Apache::lonxml::clear_problem_counter();
 2796:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
 2797:                             {'previousversion' => $env{'form.previousversion'} }));
 2798:             $request->print("\n</div>");
 2799:         }
 2800:     }
 2801:     return;
 2802: }
 2803: 
 2804: sub choose_task_version_form {
 2805:     my ($symb,$uname,$udom,$nomenu) = @_;
 2806:     my $isTask = ($symb =~/\.task$/);
 2807:     my ($current,$version,$result,$js,$displayed,$rowtitle);
 2808:     if ($isTask) {
 2809:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 2810:                                               $udom,$uname);
 2811:         if (($record{'resource.0.version'} eq '') ||
 2812:             ($record{'resource.0.version'} < 2)) {
 2813:             return ($record{'resource.0.version'},
 2814:                     $record{'resource.0.version'},$result,$js);
 2815:         } else {
 2816:             $current = $record{'resource.0.version'};
 2817:         }
 2818:         if ($env{'form.previousversion'}) {
 2819:             $displayed = $env{'form.previousversion'};
 2820:             $rowtitle = &mt('Choose another version:')
 2821:         } else {
 2822:             $displayed = $current;
 2823:             $rowtitle = &mt('Show earlier version:');
 2824:         }
 2825:         $result = '<div class="LC_left_float">';
 2826:         my $list;
 2827:         my $numversions = 0;
 2828:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
 2829:             if ($i == $current) {
 2830:                 if (!$env{'form.previousversion'} || $nomenu) {
 2831:                     next;
 2832:                 } else {
 2833:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
 2834:                     $numversions ++;
 2835:                 }
 2836:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
 2837:                 unless ($i == $env{'form.previousversion'}) {
 2838:                     $numversions ++;
 2839:                 }
 2840:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
 2841:             }
 2842:         }
 2843:         if ($numversions) {
 2844:             $symb = &HTML::Entities::encode($symb,'<>"&');
 2845:             $result .=
 2846:                 '<form name="getprev" method="post" action=""'.
 2847:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
 2848:                 &Apache::loncommon::start_data_table().
 2849:                 &Apache::loncommon::start_data_table_row().
 2850:                 '<th align="left">'.$rowtitle.'</th>'.
 2851:                 '<td><select name="version">'.
 2852:                 '<option>'.&mt('Select').'</option>'.
 2853:                 $list.
 2854:                 '</select></td>'.
 2855:                 &Apache::loncommon::end_data_table_row();
 2856:             unless ($nomenu) {
 2857:                 $result .= &Apache::loncommon::start_data_table_row().
 2858:                 '<th align="left">'.&mt('Open in new window').'</th>'.
 2859:                 '<td><span class="LC_nobreak">'.
 2860:                 '<label><input type="radio" name="prevwin" value="1" />'.
 2861:                 &mt('Yes').'</label>'.
 2862:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
 2863:                 '</span></td>'.
 2864:                 &Apache::loncommon::end_data_table_row();
 2865:             }
 2866:             $result .=
 2867:                 &Apache::loncommon::start_data_table_row().
 2868:                 '<th align="left">&nbsp;</th>'.
 2869:                 '<td>'.
 2870:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
 2871:                 '</td>'.
 2872:                 &Apache::loncommon::end_data_table_row().
 2873:                 &Apache::loncommon::end_data_table().
 2874:                 '</form>';
 2875:             $js = &previous_display_javascript($nomenu,$current);
 2876:         } elsif ($displayed && $nomenu) {
 2877:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
 2878:         } else {
 2879:             $result .= &mt('No previous versions to show for this student');
 2880:         }
 2881:         $result .= '</div>';
 2882:     }
 2883:     return ($current,$displayed,$result,$js);
 2884: }
 2885: 
 2886: sub previous_display_javascript {
 2887:     my ($nomenu,$current) = @_;
 2888:     my $js = <<"JSONE";
 2889: <script type="text/javascript">
 2890: // <![CDATA[
 2891: function previousVersion(uname,udom,symb) {
 2892:     var current = '$current';
 2893:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
 2894:     var prevstr = new RegExp("^\\\\d+\$");
 2895:     if (!prevstr.test(version)) {
 2896:         return false;
 2897:     }
 2898:     var url = '';
 2899:     if (version == current) {
 2900:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
 2901:     } else {
 2902:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
 2903:     }
 2904: JSONE
 2905:     if ($nomenu) {
 2906:         $js .= <<"JSTWO";
 2907:     document.location.href = url;
 2908: JSTWO
 2909:     } else {
 2910:         $js .= <<"JSTHREE";
 2911:     var newwin = 0;
 2912:     for (var i=0; i<document.getprev.prevwin.length; i++) {
 2913:         if (document.getprev.prevwin[i].checked == true) {
 2914:             newwin = document.getprev.prevwin[i].value;
 2915:         }
 2916:     }
 2917:     if (newwin == 1) {
 2918:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
 2919:         url = url+'&inhibitmenu=yes';
 2920:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
 2921:             previousWin = window.open(url,'',options,1);
 2922:         } else {
 2923:             previousWin.location.href = url;
 2924:         }
 2925:         previousWin.focus();
 2926:         return false;
 2927:     } else {
 2928:         document.location.href = url;
 2929:         return false;
 2930:     }
 2931: JSTHREE
 2932:     }
 2933:     $js .= <<"ENDJS";
 2934:     return false;
 2935: }
 2936: // ]]>
 2937: </script>
 2938: ENDJS
 2939: 
 2940: }
 2941: 
 2942: #--- Called from submission routine
 2943: sub processHandGrade {
 2944:     my ($request,$symb) = @_;
 2945:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2946:     my $button = $env{'form.gradeOpt'};
 2947:     my $ngrade = $env{'form.NCT'};
 2948:     my $ntstu  = $env{'form.NTSTU'};
 2949:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2950:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2951: 
 2952:     if ($button eq 'Save & Next') {
 2953: 	my $ctr = 0;
 2954: 	while ($ctr < $ngrade) {
 2955: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2956: 	    my ($errorflag,$pts,$wgt,$numhidden) = 
 2957:                 &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2958: 	    if ($errorflag eq 'no_score') {
 2959: 		$ctr++;
 2960: 		next;
 2961: 	    }
 2962: 	    if ($errorflag eq 'not_allowed') {
 2963: 		$request->print(
 2964:                     '<span class="LC_error">'
 2965:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
 2966:                    .'</span>');
 2967: 		$ctr++;
 2968: 		next;
 2969: 	    }
 2970:             if ($numhidden) {
 2971:                 $request->print(
 2972:                     '<span class="LC_info">'
 2973:                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
 2974:                    .'</span><br />');
 2975:             }
 2976: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2977: 	    my ($subject,$message,$msgstatus) = ('','','');
 2978: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2979:             my ($feedurl,$showsymb) =
 2980: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2981: 	    my $messagetail;
 2982: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2983: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2984: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2985: 		$subject.=' ['.$restitle.']';
 2986: 		my (@msgnum) = split(/,/,$includemsg);
 2987: 		foreach (@msgnum) {
 2988: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2989: 		}
 2990: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2991: 		if ($env{'form.withgrades'.$ctr}) {
 2992: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2993: 		    $messagetail = " for <a href=\"".
 2994: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
 2995: 		}
 2996: 		$msgstatus = 
 2997:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2998: 						     $message.$messagetail,
 2999:                                                      undef,$feedurl,undef,
 3000:                                                      undef,undef,$showsymb,
 3001:                                                      $restitle);
 3002: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 3003: 				$msgstatus.'<br />');
 3004: 	    }
 3005: 	    if ($env{'form.collaborator'.$ctr}) {
 3006: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 3007: 		foreach my $collabstr (@collabstrs) {
 3008: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 3009: 		    foreach my $collaborator (@collaborators) {
 3010: 			my ($errorflag,$pts,$wgt) = 
 3011: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 3012: 					   $env{'form.unamedom'.$ctr},$part);
 3013: 			if ($errorflag eq 'not_allowed') {
 3014: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 3015: 			    next;
 3016: 			} elsif ($message ne '') {
 3017: 			    my ($baseurl,$showsymb) = 
 3018: 				&get_feedurl_and_symb($symb,$collaborator,
 3019: 						      $udom);
 3020: 			    if ($env{'form.withgrades'.$ctr}) {
 3021: 				$messagetail = " for <a href=\"".
 3022:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
 3023: 			    }
 3024: 			    $msgstatus = 
 3025: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 3026: 			}
 3027: 		    }
 3028: 		}
 3029: 	    }
 3030: 	    $ctr++;
 3031: 	}
 3032:     }
 3033: 
 3034: #    if ($env{'form.handgrade'} eq 'yes') {
 3035:     if (1) {
 3036: 	# Keywords sorted in alphabatical order
 3037: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 3038: 	my %keyhash = ();
 3039: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 3040: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 3041: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 3042: 	$env{'form.keywords'} = join(' ',@keywords);
 3043: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 3044: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 3045: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 3046: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 3047: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 3048: 
 3049: 	# message center - Order of message gets changed. Blank line is eliminated.
 3050: 	# New messages are saved in env for the next student.
 3051: 	# All messages are saved in nohist_handgrade.db
 3052: 	my ($ctr,$idx) = (1,1);
 3053: 	while ($ctr <= $env{'form.savemsgN'}) {
 3054: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 3055: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 3056: 		$idx++;
 3057: 	    }
 3058: 	    $ctr++;
 3059: 	}
 3060: 	$ctr = 0;
 3061: 	while ($ctr < $ngrade) {
 3062: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 3063: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 3064: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 3065: 		$idx++;
 3066: 	    }
 3067: 	    $ctr++;
 3068: 	}
 3069: 	$env{'form.savemsgN'} = --$idx;
 3070: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 3071: 	my $putresult = &Apache::lonnet::put
 3072: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 3073:     }
 3074:     # Called by Save & Refresh from Highlight Attribute Window
 3075:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3076:     if ($env{'form.refresh'} eq 'on') {
 3077: 	my ($ctr,$total) = (0,0);
 3078: 	while ($ctr < $ngrade) {
 3079: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 3080: 	    $ctr++;
 3081: 	}
 3082: 	$env{'form.NTSTU'}=$ngrade;
 3083: 	$ctr = 0;
 3084: 	while ($ctr < $total) {
 3085: 	    my $processUser = $env{'form.unamedom'.$ctr};
 3086: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 3087: 	    $env{'form.fullname'} = $$fullname{$processUser};
 3088: 	    &submission($request,$ctr,$total-1,$symb);
 3089: 	    $ctr++;
 3090: 	}
 3091: 	return '';
 3092:     }
 3093: 
 3094:     # Get the next/previous one or group of students
 3095:     my $firststu = $env{'form.unamedom0'};
 3096:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 3097:     my $ctr = 2;
 3098:     while ($laststu eq '') {
 3099: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 3100: 	$ctr++;
 3101: 	$laststu = $firststu if ($ctr > $ngrade);
 3102:     }
 3103: 
 3104:     my (@parsedlist,@nextlist);
 3105:     my ($nextflg) = 0;
 3106:     foreach my $item (sort 
 3107: 	     {
 3108: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3109: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3110: 		 }
 3111: 		 return $a cmp $b;
 3112: 	     } (keys(%$fullname))) {
 3113: # FIXME: this is fishy, looks like the button label
 3114: 	if ($nextflg == 1 && $button =~ /Next$/) {
 3115: 	    push(@parsedlist,$item);
 3116: 	}
 3117: 	$nextflg = 1 if ($item eq $laststu);
 3118: 	if ($button eq 'Previous') {
 3119: 	    last if ($item eq $firststu);
 3120: 	    push(@parsedlist,$item);
 3121: 	}
 3122:     }
 3123:     $ctr = 0;
 3124: # FIXME: this is fishy, looks like the button label
 3125:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 3126:     my $res_error;
 3127:     my ($partlist) = &response_type($symb,\$res_error);
 3128:     if ($res_error) {
 3129:         $request->print(&navmap_errormsg());
 3130:         return;
 3131:     }
 3132:     foreach my $student (@parsedlist) {
 3133: 	my $submitonly=$env{'form.submitonly'};
 3134: 	my ($uname,$udom) = split(/:/,$student);
 3135: 	
 3136: 	if ($submitonly eq 'queued') {
 3137: 	    my %queue_status = 
 3138: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 3139: 							$udom,$uname);
 3140: 	    next if (!defined($queue_status{'gradingqueue'}));
 3141: 	}
 3142: 
 3143: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 3144: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 3145: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 3146: 	    my $submitted = 0;
 3147: 	    my $ungraded = 0;
 3148: 	    my $incorrect = 0;
 3149: 	    foreach my $item (keys(%status)) {
 3150: 		$submitted = 1 if ($status{$item} ne 'nothing');
 3151: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 3152: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 3153: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 3154: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 3155: 		    $submitted = 0;
 3156: 		}
 3157: 	    }
 3158: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 3159: 				     $submitonly eq 'incorrect' ||
 3160: 				     $submitonly eq 'graded'));
 3161: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 3162: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 3163: 	}
 3164: 	push(@nextlist,$student) if ($ctr < $ntstu);
 3165: 	last if ($ctr == $ntstu);
 3166: 	$ctr++;
 3167:     }
 3168: 
 3169:     $ctr = 0;
 3170:     my $total = scalar(@nextlist)-1;
 3171: 
 3172:     foreach (sort(@nextlist)) {
 3173: 	my ($uname,$udom,$submitter) = split(/:/);
 3174: 	$env{'form.student'}  = $uname;
 3175: 	$env{'form.userdom'}  = $udom;
 3176: 	$env{'form.fullname'} = $$fullname{$_};
 3177: 	&submission($request,$ctr,$total,$symb);
 3178: 	$ctr++;
 3179:     }
 3180:     if ($total < 0) {
 3181: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
 3182: 	$request->print($the_end);
 3183:     }
 3184:     return '';
 3185: }
 3186: 
 3187: #---- Save the score and award for each student, if changed
 3188: sub saveHandGrade {
 3189:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 3190:     my @version_parts;
 3191:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 3192: 					   $env{'request.course.id'});
 3193:     if (!&canmodify($usec)) { return('not_allowed'); }
 3194:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 3195:     my @parts_graded;
 3196:     my %newrecord  = ();
 3197:     my ($pts,$wgt,$totchg) = ('','',0);
 3198:     my %aggregate = ();
 3199:     my $aggregateflag = 0;
 3200:     if ($env{'form.HIDE'.$newflg}) {
 3201:         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
 3202:         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
 3203:         $totchg += $numchgs;
 3204:     }
 3205:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 3206:     foreach my $new_part (@parts) {
 3207: 	#collaborator ($submi may vary for different parts
 3208: 	if ($submitter && $new_part ne $part) { next; }
 3209: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 3210: 	if ($dropMenu eq 'excused') {
 3211: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 3212: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 3213: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 3214: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 3215: 		}
 3216: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3217: 	    }
 3218: 	} elsif ($dropMenu eq 'reset status'
 3219: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 3220: 	    foreach my $key (keys(%record)) {
 3221: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 3222: 	    }
 3223: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3224: 		"$env{'user.name'}:$env{'user.domain'}";
 3225:             my $totaltries = $record{'resource.'.$part.'.tries'};
 3226: 
 3227:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 3228: 					       [$new_part]);
 3229:             my $aggtries =$totaltries;
 3230:             if ($last_resets{$new_part}) {
 3231:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 3232: 					   $new_part);
 3233:             }
 3234: 
 3235:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 3236:             if ($aggtries > 0) {
 3237:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3238:                 $aggregateflag = 1;
 3239:             }
 3240: 	} elsif ($dropMenu eq '') {
 3241: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 3242: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 3243: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 3244: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 3245: 		next;
 3246: 	    }
 3247: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 3248: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 3249: 	    my $partial= $pts/$wgt;
 3250: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 3251: 		#do not update score for part if not changed.
 3252:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 3253: 		next;
 3254: 	    } else {
 3255: 	        push(@parts_graded,$new_part);
 3256: 	    }
 3257: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 3258: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 3259: 	    }
 3260: 	    my $reckey = 'resource.'.$new_part.'.solved';
 3261: 	    if ($partial == 0) {
 3262: 		if ($record{$reckey} ne 'incorrect_by_override') {
 3263: 		    $newrecord{$reckey} = 'incorrect_by_override';
 3264: 		}
 3265: 	    } else {
 3266: 		if ($record{$reckey} ne 'correct_by_override') {
 3267: 		    $newrecord{$reckey} = 'correct_by_override';
 3268: 		}
 3269: 	    }	    
 3270: 	    if ($submitter && 
 3271: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 3272: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 3273: 	    }
 3274: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3275: 		"$env{'user.name'}:$env{'user.domain'}";
 3276: 	}
 3277: 	# unless problem has been graded, set flag to version the submitted files
 3278: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 3279: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 3280: 	        $dropMenu eq 'reset status')
 3281: 	   {
 3282: 	    push(@version_parts,$new_part);
 3283: 	}
 3284:     }
 3285:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3286:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3287: 
 3288:     if (%newrecord) {
 3289:         if (@version_parts) {
 3290:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 3291:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 3292: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 3293: 	    foreach my $new_part (@version_parts) {
 3294: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 3295: 				$new_part,\%newrecord);
 3296: 	    }
 3297:         }
 3298: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 3299: 				$env{'request.course.id'},$domain,$stuname);
 3300: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 3301: 				     $cdom,$cnum,$domain,$stuname);
 3302:     }
 3303:     if ($aggregateflag) {
 3304:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3305: 			      $cdom,$cnum);
 3306:     }
 3307:     return ('',$pts,$wgt,$totchg);
 3308: }
 3309: 
 3310: sub makehidden {
 3311:     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
 3312:     return unless (ref($record) eq 'HASH');
 3313:     my %modified;
 3314:     my $numchanged = 0;
 3315:     if (exists($record->{$version.':keys'})) {
 3316:         my $partsregexp = $parts;
 3317:         $partsregexp =~ s/,/|/g;
 3318:         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
 3319:             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
 3320:                  my $item = $1;
 3321:                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
 3322:                      $modified{$key} = $record->{$version.':'.$key};
 3323:                  }
 3324:             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
 3325:                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
 3326:             } elsif ($key =~ /^(ip|timestamp|host)$/) {
 3327:                 $modified{$key} = $record->{$version.':'.$key};
 3328:             }
 3329:         }
 3330:         if (keys(%modified)) {
 3331:             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
 3332:                                           $domain,$stuname,$tolog) eq 'ok') {
 3333:                 $numchanged ++;
 3334:             }
 3335:         }
 3336:     }
 3337:     return $numchanged;
 3338: }
 3339: 
 3340: sub check_and_remove_from_queue {
 3341:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 3342:     my @ungraded_parts;
 3343:     foreach my $part (@{$parts}) {
 3344: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 3345: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 3346: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 3347: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 3348: 		) {
 3349: 	    push(@ungraded_parts, $part);
 3350: 	}
 3351:     }
 3352:     if ( !@ungraded_parts ) {
 3353: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 3354: 					       $cnum,$domain,$stuname);
 3355:     }
 3356: }
 3357: 
 3358: sub handback_files {
 3359:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 3360:     my $portfolio_root = '/userfiles/portfolio';
 3361:     my $res_error;
 3362:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3363:     if ($res_error) {
 3364:         $request->print('<br />'.&navmap_errormsg().'<br />');
 3365:         return;
 3366:     }
 3367:     my @handedback;
 3368:     my $file_msg;
 3369:     my @part_response_id = &flatten_responseType($responseType);
 3370:     foreach my $part_response_id (@part_response_id) {
 3371:     	my ($part_id,$resp_id) = @{ $part_response_id };
 3372: 	my $part_resp = join('_',@{ $part_response_id });
 3373:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
 3374:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
 3375:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
 3376:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
 3377:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
 3378:                     my ($directory,$answer_file) = 
 3379:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
 3380:                     my ($answer_name,$answer_ver,$answer_ext) =
 3381: 		        &Apache::lonnet::file_name_version_ext($answer_file);
 3382: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 3383:                     my $getpropath = 1;
 3384:                     my ($dir_list,$listerror) = 
 3385:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
 3386:                                                  $domain,$stuname,$getpropath);
 3387: 		    my $version = &Apache::lonnet::get_next_version($answer_name,$answer_ext,$dir_list);
 3388:                     # fix filename
 3389:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 3390:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 3391:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
 3392:             	                                $save_file_name);
 3393:                     if ($result !~ m|^/uploaded/|) {
 3394:                         $request->print('<br /><span class="LC_error">'.
 3395:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 3396:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
 3397:                                         '</span>');
 3398:                     } else {
 3399:                         # mark the file as read only
 3400:                         push(@handedback,$save_file_name);
 3401: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 3402: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 3403: 			}
 3404:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 3405: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
 3406:                     }
 3407:                     $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>'));
 3408:                 }
 3409:             }
 3410:         }
 3411:     }
 3412:     if (@handedback > 0) {
 3413:         $request->print('<br />');
 3414:         my @what = ($symb,$env{'request.course.id'},'handback');
 3415:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
 3416:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
 3417:         my ($subject,$message);
 3418:         if (scalar(@handedback) == 1) {
 3419:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
 3420:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
 3421:         } else {
 3422:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
 3423:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
 3424:         }
 3425:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
 3426:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
 3427:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
 3428:         my ($feedurl,$showsymb) =
 3429:             &get_feedurl_and_symb($symb,$domain,$stuname);
 3430:         my $restitle = &Apache::lonnet::gettitle($symb);
 3431:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
 3432:         my $msgstatus =
 3433:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
 3434:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
 3435:                  $restitle);
 3436:         if ($msgstatus) {
 3437:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
 3438:         }
 3439:     }
 3440:     return;
 3441: }
 3442: 
 3443: sub get_feedurl_and_symb {
 3444:     my ($symb,$uname,$udom) = @_;
 3445:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3446:     $url = &Apache::lonnet::clutter($url);
 3447:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 3448: 					$symb,$udom,$uname);
 3449:     if ($encrypturl =~ /^yes$/i) {
 3450: 	&Apache::lonenc::encrypted(\$url,1);
 3451: 	&Apache::lonenc::encrypted(\$symb,1);
 3452:     }
 3453:     return ($url,$symb);
 3454: }
 3455: 
 3456: sub get_submitted_files {
 3457:     my ($udom,$uname,$partid,$respid,$record) = @_;
 3458:     my @files;
 3459:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 3460:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 3461:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 3462:     	    push(@files,$file_url.$file);
 3463:         }
 3464:     }
 3465:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 3466:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 3467:     }
 3468:     return (\@files);
 3469: }
 3470: 
 3471: # ----------- Provides number of tries since last reset.
 3472: sub get_num_tries {
 3473:     my ($record,$last_reset,$part) = @_;
 3474:     my $timestamp = '';
 3475:     my $num_tries = 0;
 3476:     if ($$record{'version'}) {
 3477:         for (my $version=$$record{'version'};$version>=1;$version--) {
 3478:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 3479:                 $timestamp = $$record{$version.':timestamp'};
 3480:                 if ($timestamp > $last_reset) {
 3481:                     $num_tries ++;
 3482:                 } else {
 3483:                     last;
 3484:                 }
 3485:             }
 3486:         }
 3487:     }
 3488:     return $num_tries;
 3489: }
 3490: 
 3491: # ----------- Determine decrements required in aggregate totals 
 3492: sub decrement_aggs {
 3493:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 3494:     my %decrement = (
 3495:                         attempts => 0,
 3496:                         users => 0,
 3497:                         correct => 0
 3498:                     );
 3499:     $decrement{'attempts'} = $aggtries;
 3500:     if ($solvedstatus =~ /^correct/) {
 3501:         $decrement{'correct'} = 1;
 3502:     }
 3503:     if ($aggtries == $totaltries) {
 3504:         $decrement{'users'} = 1;
 3505:     }
 3506:     foreach my $type (keys(%decrement)) {
 3507:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 3508:     }
 3509:     return;
 3510: }
 3511: 
 3512: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3513: sub get_last_resets {
 3514:     my ($symb,$courseid,$partids) =@_;
 3515:     my %last_resets;
 3516:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3517:     my $cname = $env{'course.'.$courseid.'.num'};
 3518:     my @keys;
 3519:     foreach my $part (@{$partids}) {
 3520: 	push(@keys,"$symb\0$part\0resettime");
 3521:     }
 3522:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3523: 				     $cdom,$cname);
 3524:     foreach my $part (@{$partids}) {
 3525: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3526:     }
 3527:     return %last_resets;
 3528: }
 3529: 
 3530: # ----------- Handles creating versions for portfolio files as answers
 3531: sub version_portfiles {
 3532:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3533:     my $version_parts = join('|',@$v_flag);
 3534:     my @returned_keys;
 3535:     my $parts = join('|', @$parts_graded);
 3536:     foreach my $key (keys(%$record)) {
 3537:         my $new_portfiles;
 3538:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3539:             my @versioned_portfiles;
 3540:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3541:             if (@portfiles) {
 3542:                 &Apache::lonnet::portfiles_versioning($symb,$domain,$stu_name,\@portfiles,
 3543:                                                       \@versioned_portfiles);
 3544:             }
 3545:             $$record{$key} = join(',',@versioned_portfiles);
 3546:             push(@returned_keys,$key);
 3547:         }
 3548:     } 
 3549:     return (@returned_keys);   
 3550: }
 3551: 
 3552: #--------------------------------------------------------------------------------------
 3553: #
 3554: #-------------------------- Next few routines handles grading by section or whole class
 3555: #
 3556: #--- Javascript to handle grading by section or whole class
 3557: sub viewgrades_js {
 3558:     my ($request) = shift;
 3559: 
 3560:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3561:     &js_escape(\$alertmsg);
 3562:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
 3563:    function writePoint(partid,weight,point) {
 3564: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3565: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3566: 	if (point == "textval") {
 3567: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3568: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3569: 		alert("$alertmsg"+parseFloat(point));
 3570: 		var resetbox = false;
 3571: 		for (var i=0; i<radioButton.length; i++) {
 3572: 		    if (radioButton[i].checked) {
 3573: 			textbox.value = i;
 3574: 			resetbox = true;
 3575: 		    }
 3576: 		}
 3577: 		if (!resetbox) {
 3578: 		    textbox.value = "";
 3579: 		}
 3580: 		return;
 3581: 	    }
 3582: 	    if (parseFloat(point) > parseFloat(weight)) {
 3583: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3584: 				   ") greater than the weight for the part. Accept?");
 3585: 		if (resp == false) {
 3586: 		    textbox.value = "";
 3587: 		    return;
 3588: 		}
 3589: 	    }
 3590: 	    for (var i=0; i<radioButton.length; i++) {
 3591: 		radioButton[i].checked=false;
 3592: 		if (parseFloat(point) == i) {
 3593: 		    radioButton[i].checked=true;
 3594: 		}
 3595: 	    }
 3596: 
 3597: 	} else {
 3598: 	    textbox.value = parseFloat(point);
 3599: 	}
 3600: 	for (i=0;i<document.classgrade.total.value;i++) {
 3601: 	    var user = document.classgrade["ctr"+i].value;
 3602: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3603: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3604: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3605: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3606: 	    if (saveval != "correct") {
 3607: 		scorename.value = point;
 3608: 		if (selname[0].selected != true) {
 3609: 		    selname[0].selected = true;
 3610: 		}
 3611: 	    }
 3612: 	}
 3613: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3614:     }
 3615: 
 3616:     function writeRadText(partid,weight) {
 3617: 	var selval   = document.classgrade["SELVAL_"+partid];
 3618: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3619:         var override = document.classgrade["FORCE_"+partid].checked;
 3620: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3621: 	if (selval[1].selected || selval[2].selected) {
 3622: 	    for (var i=0; i<radioButton.length; i++) {
 3623: 		radioButton[i].checked=false;
 3624: 
 3625: 	    }
 3626: 	    textbox.value = "";
 3627: 
 3628: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3629: 		var user = document.classgrade["ctr"+i].value;
 3630: 		user = user.replace(new RegExp(':', 'g'),"_");
 3631: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3632: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3633: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3634: 		if ((saveval != "correct") || override) {
 3635: 		    scorename.value = "";
 3636: 		    if (selval[1].selected) {
 3637: 			selname[1].selected = true;
 3638: 		    } else {
 3639: 			selname[2].selected = true;
 3640: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3641: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3642: 		    }
 3643: 		}
 3644: 	    }
 3645: 	} else {
 3646: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3647: 		var user = document.classgrade["ctr"+i].value;
 3648: 		user = user.replace(new RegExp(':', 'g'),"_");
 3649: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3650: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3651: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3652: 		if ((saveval != "correct") || override) {
 3653: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3654: 		    selname[0].selected = true;
 3655: 		}
 3656: 	    }
 3657: 	}	    
 3658:     }
 3659: 
 3660:     function changeSelect(partid,user) {
 3661: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3662: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3663: 	var point  = textbox.value;
 3664: 	var weight = document.classgrade["weight_"+partid].value;
 3665: 
 3666: 	if (isNaN(point) || parseFloat(point) < 0) {
 3667: 	    alert("$alertmsg"+parseFloat(point));
 3668: 	    textbox.value = "";
 3669: 	    return;
 3670: 	}
 3671: 	if (parseFloat(point) > parseFloat(weight)) {
 3672: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3673: 			       ") greater than the weight of the part. Accept?");
 3674: 	    if (resp == false) {
 3675: 		textbox.value = "";
 3676: 		return;
 3677: 	    }
 3678: 	}
 3679: 	selval[0].selected = true;
 3680:     }
 3681: 
 3682:     function changeOneScore(partid,user) {
 3683: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3684: 	if (selval[1].selected || selval[2].selected) {
 3685: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3686: 	    if (selval[2].selected) {
 3687: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3688: 	    }
 3689:         }
 3690:     }
 3691: 
 3692:     function resetEntry(numpart) {
 3693: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3694: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3695: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3696: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3697: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3698: 	    for (var i=0; i<radioButton.length; i++) {
 3699: 		radioButton[i].checked=false;
 3700: 
 3701: 	    }
 3702: 	    textbox.value = "";
 3703: 	    selval[0].selected = true;
 3704: 
 3705: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3706: 		var user = document.classgrade["ctr"+i].value;
 3707: 		user = user.replace(new RegExp(':', 'g'),"_");
 3708: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3709: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3710: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3711: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3712: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3713: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3714: 		if (saveselval == "excused") {
 3715: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3716: 		} else {
 3717: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3718: 		}
 3719: 	    }
 3720: 	}
 3721:     }
 3722: 
 3723: VIEWJAVASCRIPT
 3724: }
 3725: 
 3726: #--- show scores for a section or whole class w/ option to change/update a score
 3727: sub viewgrades {
 3728:     my ($request,$symb) = @_;
 3729:     my ($is_tool,$toolsymb);
 3730:     if ($symb =~ /ext\.tool$/) {
 3731:         $is_tool = 1;
 3732:         $toolsymb = $symb;
 3733:     }
 3734:     &viewgrades_js($request);
 3735: 
 3736:     #need to make sure we have the correct data for later EXT calls, 
 3737:     #thus invalidate the cache
 3738:     &Apache::lonnet::devalidatecourseresdata(
 3739:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3740:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3741:     &Apache::lonnet::clear_EXT_cache_status();
 3742: 
 3743:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3744: 
 3745:     #view individual student submission form - called using Javascript viewOneStudent
 3746:     $result.=&jscriptNform($symb);
 3747: 
 3748:     #beginning of class grading form
 3749:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3750:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3751: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3752: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3753: 	&build_section_inputs().
 3754: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3755: 
 3756:     #retrieve selected groups
 3757:     my (@groups,$group_display);
 3758:     @groups = &Apache::loncommon::get_env_multiple('form.group');
 3759:     if (grep(/^all$/,@groups)) {
 3760:         @groups = ('all');
 3761:     } elsif (grep(/^none$/,@groups)) {
 3762:         @groups = ('none');
 3763:     } elsif (@groups > 0) {
 3764:         $group_display = join(', ',@groups);
 3765:     }
 3766: 
 3767:     my ($common_header,$specific_header,@sections,$section_display);
 3768:     @sections = &Apache::loncommon::get_env_multiple('form.section');
 3769:     if (grep(/^all$/,@sections)) {
 3770:         @sections = ('all');
 3771:         if ($group_display) {
 3772:             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
 3773:             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
 3774:         } elsif (grep(/^none$/,@groups)) {
 3775:             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
 3776:             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
 3777:         } else {
 3778: 	    $common_header = &mt('Assign Common Grade to Class');
 3779:             $specific_header = &mt('Assign Grade to Specific Students in Class');
 3780:         }
 3781:     } elsif (grep(/^none$/,@sections)) {
 3782:         @sections = ('none');
 3783:         if ($group_display) {
 3784:             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
 3785:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
 3786:         } elsif (grep(/^none$/,@groups)) {
 3787:             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
 3788:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
 3789:         } else {
 3790:             $common_header = &mt('Assign Common Grade to Students in no Section');
 3791: 	    $specific_header = &mt('Assign Grade to Specific Students in no Section');
 3792:         }
 3793:     } else {
 3794:         $section_display = join (", ",@sections);
 3795:         if ($group_display) {
 3796:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
 3797:                                  $section_display,$group_display);
 3798:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
 3799:                                    $section_display,$group_display);
 3800:         } elsif (grep(/^none$/,@groups)) {
 3801:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
 3802:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
 3803:         } else {
 3804:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3805: 	    $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3806:         }
 3807:     }
 3808:     my %submit_types = &substatus_options();
 3809:     my $submission_status = $submit_types{$env{'form.submitonly'}};
 3810: 
 3811:     if ($env{'form.submitonly'} eq 'all') {
 3812:         $result.= '<h3>'.$common_header.'</h3>';
 3813:     } else {
 3814:         my $text;
 3815:         if ($is_tool) {
 3816:             $text = &mt('(transaction status: "[_1]")',$submission_status);
 3817:         } else {
 3818:             $text = &mt('(submission status: "[_1]")',$submission_status);
 3819:         }
 3820:         $result.= '<h3>'.$common_header.'&nbsp;'.$text.'</h3>';
 3821:     }
 3822:     $result .= &Apache::loncommon::start_data_table();
 3823:     #radio buttons/text box for assigning points for a section or class.
 3824:     #handles different parts of a problem
 3825:     my $res_error;
 3826:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3827:     if ($res_error) {
 3828:         return &navmap_errormsg();
 3829:     }
 3830:     my %weight = ();
 3831:     my $ctsparts = 0;
 3832:     my %seen = ();
 3833:     my @part_response_id;
 3834:     if ($is_tool) {
 3835:         @part_response_id = ([0,'']);
 3836:     } else {
 3837:         @part_response_id = &flatten_responseType($responseType);
 3838:     }
 3839:     foreach my $part_response_id (@part_response_id) {
 3840:     	my ($partid,$respid) = @{ $part_response_id };
 3841: 	my $part_resp = join('_',@{ $part_response_id });
 3842: 	next if $seen{$partid};
 3843: 	$seen{$partid}++;
 3844: #	my $handgrade=$$handgrade{$part_resp};
 3845: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3846: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3847: 
 3848: 	my $display_part=&get_display_part($partid,$symb);
 3849: 	my $radio.='<table border="0"><tr>';  
 3850: 	my $ctr = 0;
 3851: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3852: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3853: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3854: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3855: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3856: 	    $ctr++;
 3857: 	}
 3858: 	$radio.='</tr></table>';
 3859: 	my $line = '<input type="text" name="TEXTVAL_'.
 3860: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 3861: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3862: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3863:         $line.= '<td><b>'.&mt('Grade Status').':</b>'.
 3864:             '<select name="SELVAL_'.$partid.'" '.
 3865:             'onchange="javascript:writeRadText(\''.$partid.'\','.
 3866:                 $weight{$partid}.')"> '.
 3867: 	    '<option selected="selected"> </option>'.
 3868: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3869: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3870: 	    '</select></td>'.
 3871:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3872: 	$line.='<input type="hidden" name="partid_'.
 3873: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3874: 	$line.='<input type="hidden" name="weight_'.
 3875: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3876: 
 3877: 	$result.=
 3878: 	    &Apache::loncommon::start_data_table_row()."\n".
 3879: 	    '<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>'.
 3880: 	    &Apache::loncommon::end_data_table_row()."\n";
 3881: 	$ctsparts++;
 3882:     }
 3883:     $result.=&Apache::loncommon::end_data_table()."\n".
 3884: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3885:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3886: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 3887: 
 3888:     #table listing all the students in a section/class
 3889:     #header of table
 3890:     if ($env{'form.submitonly'} eq 'all') {
 3891:         $result.= '<h3>'.$specific_header.'</h3>';
 3892:     } else {
 3893:         my $text;
 3894:         if ($is_tool) {
 3895:             $text = &mt('(transaction status: "[_1]")',$submission_status);
 3896:         } else {
 3897:             $text = &mt('(submission status: "[_1]")',$submission_status);
 3898:         }
 3899:         $result.= '<h3>'.$specific_header.'&nbsp;'.$text.'</h3>';
 3900:     }
 3901:     $result.= &Apache::loncommon::start_data_table().
 3902: 	      &Apache::loncommon::start_data_table_header_row().
 3903: 	      '<th>'.&mt('No.').'</th>'.
 3904: 	      '<th>'.&nameUserString('header')."</th>\n";
 3905:     my $partserror;
 3906:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3907:     if ($partserror) {
 3908:         return &navmap_errormsg();
 3909:     }
 3910:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3911:     my @partids = ();
 3912:     foreach my $part (@parts) {
 3913: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
 3914:         my $narrowtext = &mt('Tries');
 3915: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3916: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name',$toolsymb); }
 3917: 	my ($partid) = &split_part_type($part);
 3918:         push(@partids,$partid);
 3919: #
 3920: # FIXME: Looks like $display looks at English text
 3921: #
 3922: 	my $display_part=&get_display_part($partid,$symb);
 3923: 	if ($display =~ /^Partial Credit Factor/) {
 3924: 	    $result.='<th>'.
 3925: 		&mt('Score Part: [_1][_2](weight = [_3])',
 3926: 		    $display_part,'<br />',$weight{$partid}).'</th>'."\n";
 3927: 	    next;
 3928: 	    
 3929: 	} else {
 3930: 	    if ($display =~ /Problem Status/) {
 3931: 		my $grade_status_mt = &mt('Grade Status');
 3932: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3933: 	    }
 3934: 	    my $part_mt = &mt('Part:');
 3935: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3936: 	}
 3937: 
 3938: 	$result.='<th>'.$display.'</th>'."\n";
 3939:     }
 3940:     $result.=&Apache::loncommon::end_data_table_header_row();
 3941: 
 3942:     my %last_resets = 
 3943: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3944: 
 3945:     #get info for each student
 3946:     #list all the students - with points and grade status
 3947:     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
 3948:     my $ctr = 0;
 3949:     foreach (sort 
 3950: 	     {
 3951: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3952: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3953: 		 }
 3954: 		 return $a cmp $b;
 3955: 	     } (keys(%$fullname))) {
 3956: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3957: 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets,$is_tool);
 3958:     }
 3959:     $result.=&Apache::loncommon::end_data_table();
 3960:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3961:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3962: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 3963:     if ($ctr == 0) {
 3964:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3965:         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
 3966:                 '<span class="LC_warning">';
 3967:         if ($env{'form.submitonly'} eq 'all') {
 3968:             if (grep(/^all$/,@sections)) {
 3969:                 if (grep(/^all$/,@groups)) {
 3970:                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
 3971:                                    $stu_status);
 3972:                 } elsif (grep(/^none$/,@groups)) {
 3973:                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
 3974:                                    $stu_status); 
 3975:                 } else {
 3976:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
 3977:                                    $group_display,$stu_status);
 3978:                 }
 3979:             } elsif (grep(/^none$/,@sections)) {
 3980:                 if (grep(/^all$/,@groups)) {
 3981:                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
 3982:                                    $stu_status);
 3983:                 } elsif (grep(/^none$/,@groups)) {
 3984:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
 3985:                                    $stu_status);
 3986:                 } else {
 3987:                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
 3988:                                    $group_display,$stu_status);
 3989:                 }
 3990:             } else {
 3991:                 if (grep(/^all$/,@groups)) {
 3992:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3993:                                    $section_display,$stu_status);
 3994:                 } elsif (grep(/^none$/,@groups)) {
 3995:                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
 3996:                                    $section_display,$stu_status);
 3997:                 } else {
 3998:                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
 3999:                                    $section_display,$group_display,$stu_status);
 4000:                 }
 4001:             }
 4002:         } else {
 4003:             if (grep(/^all$/,@sections)) {
 4004:                 if (grep(/^all$/,@groups)) {
 4005:                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4006:                                    $stu_status,$submission_status);
 4007:                 } elsif (grep(/^none$/,@groups)) {
 4008:                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4009:                                    $stu_status,$submission_status);
 4010:                 } else {
 4011:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 4012:                                    $group_display,$stu_status,$submission_status);
 4013:                 }
 4014:             } elsif (grep(/^none$/,@sections)) {
 4015:                 if (grep(/^all$/,@groups)) {
 4016:                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4017:                                    $stu_status,$submission_status);
 4018:                 } elsif (grep(/^none$/,@groups)) {
 4019:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4020:                                    $stu_status,$submission_status);
 4021:                 } else {
 4022:                     $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.',
 4023:                                    $group_display,$stu_status,$submission_status);
 4024:                 }
 4025:             } else {
 4026:                 if (grep(/^all$/,@groups)) {
 4027: 	            $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 4028: 	                           $section_display,$stu_status,$submission_status);
 4029:                 } elsif (grep(/^none$/,@groups)) {
 4030:                     $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.',
 4031:                                    $section_display,$stu_status,$submission_status);
 4032:                 } else {
 4033:                     $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.',
 4034:                                    $section_display,$group_display,$stu_status,$submission_status);
 4035:                 }
 4036:             }
 4037:         }
 4038: 	$result .= '</span><br />';
 4039:     }
 4040:     return $result;
 4041: }
 4042: 
 4043: #--- call by previous routine to display each student who satisfies submission filter. 
 4044: sub viewstudentgrade {
 4045:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets,$is_tool) = @_;
 4046:     my ($uname,$udom) = split(/:/,$student);
 4047:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 4048:     my $submitonly = $env{'form.submitonly'};
 4049:     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
 4050:         my %partstatus = ();
 4051:         if (ref($parts) eq 'ARRAY') {
 4052:             foreach my $apart (@{$parts}) {
 4053:                 my ($part,$type) = &split_part_type($apart);
 4054:                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
 4055:                 $status = 'nothing' if ($status eq '');
 4056:                 $partstatus{$part}      = $status;
 4057:                 my $subkey = "resource.$part.submitted_by";
 4058:                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
 4059:             }
 4060:             my $submitted = 0;
 4061:             my $graded = 0;
 4062:             my $incorrect = 0;
 4063:             foreach my $key (keys(%partstatus)) {
 4064:                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
 4065:                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
 4066:                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
 4067: 
 4068:                 my $partid = (split(/\./,$key))[1];
 4069:                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
 4070:                     $submitted = 0;
 4071:                 }
 4072:             }
 4073:             return if (!$submitted && ($submitonly eq 'yes' ||
 4074:                                        $submitonly eq 'incorrect' ||
 4075:                                        $submitonly eq 'graded'));
 4076:             return if (!$graded && ($submitonly eq 'graded'));
 4077:             return if (!$incorrect && $submitonly eq 'incorrect');
 4078:         }
 4079:     }
 4080:     if ($submitonly eq 'queued') {
 4081:         my ($cdom,$cnum) = split(/_/,$courseid);
 4082:         my %queue_status =
 4083:             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 4084:                                                     $udom,$uname);
 4085:         return if (!defined($queue_status{'gradingqueue'}));
 4086:     }
 4087:     $$ctr++;
 4088:     my %aggregates = ();
 4089:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 4090: 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
 4091: 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
 4092: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 4093: 	'\');" target="_self">'.$fullname.'</a> '.
 4094: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 4095:     $student=~s/:/_/; # colon doen't work in javascript for names
 4096:     foreach my $apart (@$parts) {
 4097: 	my ($part,$type) = &split_part_type($apart);
 4098: 	my $score=$record{"resource.$part.$type"};
 4099:         $result.='<td align="center">';
 4100:         my ($aggtries,$totaltries);
 4101:         unless (exists($aggregates{$part})) {
 4102: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 4103: 	    $aggtries = $totaltries;
 4104:             if ($$last_resets{$part}) {  
 4105:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 4106: 					   $part);
 4107:             }
 4108:             $result.='<input type="hidden" name="'.
 4109:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 4110:             $result.='<input type="hidden" name="'.
 4111:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 4112:             $aggregates{$part} = 1;
 4113:         }
 4114: 	if ($type eq 'awarded') {
 4115: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 4116: 	    $result.='<input type="hidden" name="'.
 4117: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 4118: 	    $result.='<input type="text" name="'.
 4119: 		'GD_'.$student.'_'.$part.'_awarded" '.
 4120:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 4121: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 4122: 	} elsif ($type eq 'solved') {
 4123: 	    my ($status,$foo)=split(/_/,$score,2);
 4124: 	    $status = 'nothing' if ($status eq '');
 4125: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 4126: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 4127: 	    $result.='&nbsp;<select name="'.
 4128: 		'GD_'.$student.'_'.$part.'_solved" '.
 4129:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 4130: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 4131: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 4132: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 4133: 	    $result.="</select>&nbsp;</td>\n";
 4134: 	} else {
 4135: 	    $result.='<input type="hidden" name="'.
 4136: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 4137: 		    "\n";
 4138: 	    $result.='<input type="text" name="'.
 4139: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 4140: 		'value="'.$score.'" size="4" /></td>'."\n";
 4141: 	}
 4142:     }
 4143:     $result.=&Apache::loncommon::end_data_table_row();
 4144:     return $result;
 4145: }
 4146: 
 4147: #--- change scores for all the students in a section/class
 4148: #    record does not get update if unchanged
 4149: sub editgrades {
 4150:     my ($request,$symb) = @_;
 4151:     my $toolsymb;
 4152:     if ($symb =~ /ext\.tool$/) {
 4153:         $toolsymb = $symb;
 4154:     }
 4155: 
 4156:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 4157:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 4158:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 4159: 
 4160:     my $result= &Apache::loncommon::start_data_table().
 4161: 	&Apache::loncommon::start_data_table_header_row().
 4162: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 4163: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 4164:     my %scoreptr = (
 4165: 		    'correct'  =>'correct_by_override',
 4166: 		    'incorrect'=>'incorrect_by_override',
 4167: 		    'excused'  =>'excused',
 4168: 		    'ungraded' =>'ungraded_attempted',
 4169:                     'credited' =>'credit_attempted',
 4170: 		    'nothing'  => '',
 4171: 		    );
 4172:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 4173: 
 4174:     my (@partid);
 4175:     my %weight = ();
 4176:     my %columns = ();
 4177:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 4178: 
 4179:     my $partserror;
 4180:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 4181:     if ($partserror) {
 4182:         return &navmap_errormsg();
 4183:     }
 4184:     my $header;
 4185:     while ($ctr < $env{'form.totalparts'}) {
 4186: 	my $partid = $env{'form.partid_'.$ctr};
 4187: 	push(@partid,$partid);
 4188: 	$weight{$partid} = $env{'form.weight_'.$partid};
 4189: 	$ctr++;
 4190:     }
 4191:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4192:     my $totcolspan = 0;
 4193:     foreach my $partid (@partid) {
 4194: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 4195: 	    '<th align="center">'.&mt('New Score').'</th>';
 4196: 	$columns{$partid}=2;
 4197: 	foreach my $stores (@parts) {
 4198: 	    my ($part,$type) = &split_part_type($stores);
 4199: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 4200: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 4201: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display',$toolsymb);
 4202: 	    $display =~ s/\[Part: \Q$part\E\]//;
 4203:             my $narrowtext = &mt('Tries');
 4204: 	    $display =~ s/Number of Attempts/$narrowtext/;
 4205: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 4206: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 4207: 	    $columns{$partid}+=2;
 4208: 	}
 4209:         $totcolspan += $columns{$partid};
 4210:     }
 4211:     foreach my $partid (@partid) {
 4212: 	my $display_part=&get_display_part($partid,$symb);
 4213: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 4214: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 4215: 	    '</th>';
 4216: 
 4217:     }
 4218:     $result .= &Apache::loncommon::end_data_table_header_row().
 4219: 	&Apache::loncommon::start_data_table_header_row().
 4220: 	$header.
 4221: 	&Apache::loncommon::end_data_table_header_row();
 4222:     my @noupdate;
 4223:     my ($updateCtr,$noupdateCtr) = (1,1);
 4224:     for ($i=0; $i<$env{'form.total'}; $i++) {
 4225: 	my $user = $env{'form.ctr'.$i};
 4226: 	my ($uname,$udom)=split(/:/,$user);
 4227: 	my %newrecord;
 4228: 	my $updateflag = 0;
 4229: 	my $usec=$classlist->{"$uname:$udom"}[5];
 4230: 	my $canmodify = &canmodify($usec);
 4231: 	my $line = '<td'.($canmodify?'':' colspan="2"').'>'.
 4232: 		   &nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 4233: 	if (!$canmodify) {
 4234: 	    push(@noupdate,
 4235: 		 $line."<td colspan=\"$totcolspan\"><span class=\"LC_warning\">".
 4236: 		 &mt('Not allowed to modify student')."</span></td>");
 4237: 	    next;
 4238: 	}
 4239:         my %aggregate = ();
 4240:         my $aggregateflag = 0;
 4241: 	$user=~s/:/_/; # colon doen't work in javascript for names
 4242: 	foreach (@partid) {
 4243: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 4244: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 4245: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 4246: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 4247: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 4248: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 4249: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 4250: 	    my $score;
 4251: 	    if ($partial eq '') {
 4252: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 4253: 	    } elsif ($partial > 0) {
 4254: 		$score = 'correct_by_override';
 4255: 	    } elsif ($partial == 0) {
 4256: 		$score = 'incorrect_by_override';
 4257: 	    }
 4258: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 4259: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 4260: 
 4261: 	    $newrecord{'resource.'.$_.'.regrader'}=
 4262: 		"$env{'user.name'}:$env{'user.domain'}";
 4263: 	    if ($dropMenu eq 'reset status' &&
 4264: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 4265: 		$newrecord{'resource.'.$_.'.tries'} = '';
 4266: 		$newrecord{'resource.'.$_.'.solved'} = '';
 4267: 		$newrecord{'resource.'.$_.'.award'} = '';
 4268: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 4269: 		$updateflag = 1;
 4270:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 4271:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 4272:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 4273:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 4274:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4275:                     $aggregateflag = 1;
 4276:                 }
 4277: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 4278: 		$updateflag = 1;
 4279: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 4280: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 4281: 		$rec_update++;
 4282: 	    }
 4283: 
 4284: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4285: 		'<td align="center">'.$awarded.
 4286: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 4287: 
 4288: 
 4289: 	    my $partid=$_;
 4290: 	    foreach my $stores (@parts) {
 4291: 		my ($part,$type) = &split_part_type($stores);
 4292: 		if ($part !~ m/^\Q$partid\E/) { next;}
 4293: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 4294: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 4295: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 4296: 		if ($awarded ne '' && $awarded ne $old_aw) {
 4297: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 4298: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 4299: 		    $updateflag=1;
 4300: 		}
 4301: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4302: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 4303: 	    }
 4304: 	}
 4305: 	$line.="\n";
 4306: 
 4307: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4308: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4309: 
 4310: 	if ($updateflag) {
 4311: 	    $count++;
 4312: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 4313: 				    $udom,$uname);
 4314: 
 4315: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 4316: 					      $cnum,$udom,$uname)) {
 4317: 		# need to figure out if should be in queue.
 4318: 		my %record =  
 4319: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 4320: 					     $udom,$uname);
 4321: 		my $all_graded = 1;
 4322: 		my $none_graded = 1;
 4323: 		foreach my $part (@parts) {
 4324: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 4325: 			$all_graded = 0;
 4326: 		    } else {
 4327: 			$none_graded = 0;
 4328: 		    }
 4329: 		}
 4330: 
 4331: 		if ($all_graded || $none_graded) {
 4332: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 4333: 							   $symb,$cdom,$cnum,
 4334: 							   $udom,$uname);
 4335: 		}
 4336: 	    }
 4337: 
 4338: 	    $result.=&Apache::loncommon::start_data_table_row().
 4339: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 4340: 		&Apache::loncommon::end_data_table_row();
 4341: 	    $updateCtr++;
 4342: 	} else {
 4343: 	    push(@noupdate,
 4344: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 4345: 	    $noupdateCtr++;
 4346: 	}
 4347:         if ($aggregateflag) {
 4348:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4349: 				  $cdom,$cnum);
 4350:         }
 4351:     }
 4352:     if (@noupdate) {
 4353:         my $numcols=$totcolspan+2;
 4354: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 4355: 	    '<td align="center" colspan="'.$numcols.'">'.
 4356: 	    &mt('No Changes Occurred For the Students Below').
 4357: 	    '</td>'.
 4358: 	    &Apache::loncommon::end_data_table_row();
 4359: 	foreach my $line (@noupdate) {
 4360: 	    $result.=
 4361: 		&Apache::loncommon::start_data_table_row().
 4362: 		$line.
 4363: 		&Apache::loncommon::end_data_table_row();
 4364: 	}
 4365:     }
 4366:     $result .= &Apache::loncommon::end_data_table();
 4367:     my $msg = '<p><b>'.
 4368: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 4369: 	    $rec_update,$count).'</b><br />'.
 4370: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 4371: 	'</b></p>';
 4372:     return $title.$msg.$result;
 4373: }
 4374: 
 4375: sub split_part_type {
 4376:     my ($partstr) = @_;
 4377:     my ($temp,@allparts)=split(/_/,$partstr);
 4378:     my $type=pop(@allparts);
 4379:     my $part=join('_',@allparts);
 4380:     return ($part,$type);
 4381: }
 4382: 
 4383: #------------- end of section for handling grading by section/class ---------
 4384: #
 4385: #----------------------------------------------------------------------------
 4386: 
 4387: 
 4388: #----------------------------------------------------------------------------
 4389: #
 4390: #-------------------------- Next few routines handles grading by csv upload
 4391: #
 4392: #--- Javascript to handle csv upload
 4393: sub csvupload_javascript_reverse_associate {
 4394:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
 4395:     my $error2=&mt('You need to specify at least one grading field');
 4396:   &js_escape(\$error1);
 4397:   &js_escape(\$error2);
 4398:   return(<<ENDPICK);
 4399:   function verify(vf) {
 4400:     var foundsomething=0;
 4401:     var founduname=0;
 4402:     var foundID=0;
 4403:     var foundclicker=0;
 4404:     for (i=0;i<=vf.nfields.value;i++) {
 4405:       tw=eval('vf.f'+i+'.selectedIndex');
 4406:       if (i==0 && tw!=0) { foundID=1; }
 4407:       if (i==1 && tw!=0) { founduname=1; }
 4408:       if (i==2 && tw!=0) { foundclicker=1; }
 4409:       if (i!=0 && i!=1 && i!=2 && i!=3 && tw!=0) { foundsomething=1; }
 4410:     }
 4411:     if (founduname==0 && foundID==0 && foundclicker==0) {
 4412: 	alert('$error1');
 4413: 	return;
 4414:     }
 4415:     if (foundsomething==0) {
 4416: 	alert('$error2');
 4417: 	return;
 4418:     }
 4419:     vf.submit();
 4420:   }
 4421:   function flip(vf,tf) {
 4422:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4423:     var i;
 4424:     for (i=0;i<=vf.nfields.value;i++) {
 4425:       //can not pick the same destination field for both name and domain
 4426:       if (((i ==0)||(i ==1)) && 
 4427:           ((tf==0)||(tf==1)) && 
 4428:           (i!=tf) &&
 4429:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4430:         eval('vf.f'+i+'.selectedIndex=0;')
 4431:       }
 4432:     }
 4433:   }
 4434: ENDPICK
 4435: }
 4436: 
 4437: sub csvupload_javascript_forward_associate {
 4438:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
 4439:     my $error2=&mt('You need to specify at least one grading field');
 4440:   &js_escape(\$error1);
 4441:   &js_escape(\$error2);
 4442:   return(<<ENDPICK);
 4443:   function verify(vf) {
 4444:     var foundsomething=0;
 4445:     var founduname=0;
 4446:     var foundID=0;
 4447:     var foundclicker=0;
 4448:     for (i=0;i<=vf.nfields.value;i++) {
 4449:       tw=eval('vf.f'+i+'.selectedIndex');
 4450:       if (tw==1) { foundID=1; }
 4451:       if (tw==2) { founduname=1; }
 4452:       if (tw==3) { foundclicker=1; }
 4453:       if (tw>4) { foundsomething=1; }
 4454:     }
 4455:     if (founduname==0 && foundID==0 && Æ’oundclicker==0) {
 4456: 	alert('$error1');
 4457: 	return;
 4458:     }
 4459:     if (foundsomething==0) {
 4460: 	alert('$error2');
 4461: 	return;
 4462:     }
 4463:     vf.submit();
 4464:   }
 4465:   function flip(vf,tf) {
 4466:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4467:     var i;
 4468:     //can not pick the same destination field twice
 4469:     for (i=0;i<=vf.nfields.value;i++) {
 4470:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4471:         eval('vf.f'+i+'.selectedIndex=0;')
 4472:       }
 4473:     }
 4474:   }
 4475: ENDPICK
 4476: }
 4477: 
 4478: sub csvuploadmap_header {
 4479:     my ($request,$symb,$datatoken,$distotal)= @_;
 4480:     my $javascript;
 4481:     if ($env{'form.upfile_associate'} eq 'reverse') {
 4482: 	$javascript=&csvupload_javascript_reverse_associate();
 4483:     } else {
 4484: 	$javascript=&csvupload_javascript_forward_associate();
 4485:     }
 4486: 
 4487:     $symb = &Apache::lonenc::check_encrypt($symb);
 4488:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
 4489:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
 4490:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
 4491:     my $reverse=&mt("Reverse Association");
 4492:     $request->print(<<ENDPICK);
 4493: <br />
 4494: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 4495: <input type="hidden" name="associate"  value="" />
 4496: <input type="hidden" name="phase"      value="three" />
 4497: <input type="hidden" name="datatoken"  value="$datatoken" />
 4498: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 4499: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 4500: <input type="hidden" name="upfile_associate" 
 4501:                                        value="$env{'form.upfile_associate'}" />
 4502: <input type="hidden" name="symb"       value="$symb" />
 4503: <input type="hidden" name="command"    value="csvuploadoptions" />
 4504: <hr />
 4505: ENDPICK
 4506:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
 4507:     return '';
 4508: 
 4509: }
 4510: 
 4511: sub csvupload_fields {
 4512:     my ($symb,$errorref) = @_;
 4513:     my $toolsymb;
 4514:     if ($symb =~ /ext\.tool$/) {
 4515:         $toolsymb = $symb;
 4516:     }
 4517:     my (@parts) = &getpartlist($symb,$errorref);
 4518:     if (ref($errorref)) {
 4519:         if ($$errorref) {
 4520:             return;
 4521:         }
 4522:     }
 4523: 
 4524:     my @fields=(['ID','Student/Employee ID'],
 4525: 		['username','Student Username'],
 4526: 		['clicker','Clicker ID'],
 4527: 		['domain','Student Domain']);
 4528:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4529:     foreach my $part (sort(@parts)) {
 4530: 	my @datum;
 4531: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
 4532: 	my $name=$part;
 4533: 	if (!$display) { $display = $name; }
 4534: 	@datum=($name,$display);
 4535: 	if ($name=~/^stores_(.*)_awarded/) {
 4536: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 4537: 	}
 4538: 	push(@fields,\@datum);
 4539:     }
 4540:     return (@fields);
 4541: }
 4542: 
 4543: sub csvuploadmap_footer {
 4544:     my ($request,$i,$keyfields) =@_;
 4545:     my $buttontext = &mt('Assign Grades');
 4546:     $request->print(<<ENDPICK);
 4547: </table>
 4548: <input type="hidden" name="nfields" value="$i" />
 4549: <input type="hidden" name="keyfields" value="$keyfields" />
 4550: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
 4551: </form>
 4552: ENDPICK
 4553: }
 4554: 
 4555: sub checkforfile_js {
 4556:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 4557:     &js_escape(\$alertmsg);
 4558:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
 4559:     function checkUpload(formname) {
 4560: 	if (formname.upfile.value == "") {
 4561: 	    alert("$alertmsg");
 4562: 	    return false;
 4563: 	}
 4564: 	formname.submit();
 4565:     }
 4566: CSVFORMJS
 4567:     return $result;
 4568: }
 4569: 
 4570: sub upcsvScores_form {
 4571:     my ($request,$symb) = @_;
 4572:     if (!$symb) {return '';}
 4573:     my $result=&checkforfile_js();
 4574:     $result.=&Apache::loncommon::start_data_table().
 4575:              &Apache::loncommon::start_data_table_header_row().
 4576:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
 4577:              &Apache::loncommon::end_data_table_header_row().
 4578:              &Apache::loncommon::start_data_table_row().'<td>';
 4579:     my $upload=&mt("Upload Scores");
 4580:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 4581:     my $ignore=&mt('Ignore First Line');
 4582:     $symb = &Apache::lonenc::check_encrypt($symb);
 4583:     $result.=<<ENDUPFORM;
 4584: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4585: <input type="hidden" name="symb" value="$symb" />
 4586: <input type="hidden" name="command" value="csvuploadmap" />
 4587: $upfile_select
 4588: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 4589: </form>
 4590: ENDUPFORM
 4591:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 4592:                            &mt("How do I create a CSV file from a spreadsheet")).
 4593:              '</td>'.
 4594:             &Apache::loncommon::end_data_table_row().
 4595:             &Apache::loncommon::end_data_table();
 4596:     return $result;
 4597: }
 4598: 
 4599: 
 4600: sub csvuploadmap {
 4601:     my ($request,$symb)= @_;
 4602:     if (!$symb) {return '';}
 4603: 
 4604:     my $datatoken;
 4605:     if (!$env{'form.datatoken'}) {
 4606: 	$datatoken=&Apache::loncommon::upfile_store($request);
 4607:     } else {
 4608: 	$datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
 4609:         if ($datatoken ne '') {
 4610: 	    &Apache::loncommon::load_tmp_file($request,$datatoken);
 4611:         }
 4612:     }
 4613:     my @records=&Apache::loncommon::upfile_record_sep();
 4614:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 4615:     my ($i,$keyfields);
 4616:     if (@records) {
 4617:         my $fieldserror;
 4618: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 4619:         if ($fieldserror) {
 4620:             $request->print(&navmap_errormsg());
 4621:             return;
 4622:         }
 4623: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 4624: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 4625: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 4626: 							  \@fields);
 4627: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 4628: 	    chop($keyfields);
 4629: 	} else {
 4630: 	    unshift(@fields,['none','']);
 4631: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 4632: 							    \@fields);
 4633:             foreach my $rec (@records) {
 4634:                 my %temp = &Apache::loncommon::record_sep($rec);
 4635:                 if (%temp) {
 4636:                     $keyfields=join(',',sort(keys(%temp)));
 4637:                     last;
 4638:                 }
 4639:             }
 4640: 	}
 4641:     }
 4642:     &csvuploadmap_footer($request,$i,$keyfields);
 4643: 
 4644:     return '';
 4645: }
 4646: 
 4647: sub csvuploadoptions {
 4648:     my ($request,$symb)= @_;
 4649:     my $overwrite=&mt('Overwrite any existing score');
 4650:     $request->print(<<ENDPICK);
 4651: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4652: <input type="hidden" name="command"    value="csvuploadassign" />
 4653: <p>
 4654: <label>
 4655:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4656:    $overwrite
 4657: </label>
 4658: </p>
 4659: ENDPICK
 4660:     my %fields=&get_fields();
 4661:     if (!defined($fields{'domain'})) {
 4662: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4663: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
 4664:     }
 4665:     foreach my $key (sort(keys(%env))) {
 4666: 	if ($key !~ /^form\.(.*)$/) { next; }
 4667: 	my $cleankey=$1;
 4668: 	if ($cleankey eq 'command') { next; }
 4669: 	$request->print('<input type="hidden" name="'.$cleankey.
 4670: 			'"  value="'.$env{$key}.'" />'."\n");
 4671:     }
 4672:     # FIXME do a check for any duplicated user ids...
 4673:     # FIXME do a check for any invalid user ids?...
 4674:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
 4675: <hr /></form>'."\n");
 4676:     return '';
 4677: }
 4678: 
 4679: sub get_fields {
 4680:     my %fields;
 4681:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4682:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4683: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4684: 	    if ($env{'form.f'.$i} ne 'none') {
 4685: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4686: 	    }
 4687: 	} else {
 4688: 	    if ($env{'form.f'.$i} ne 'none') {
 4689: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4690: 	    }
 4691: 	}
 4692:     }
 4693:     return %fields;
 4694: }
 4695: 
 4696: sub csvuploadassign {
 4697:     my ($request,$symb)= @_;
 4698:     if (!$symb) {return '';}
 4699:     my $error_msg = '';
 4700:     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
 4701:     if ($datatoken ne '') { 
 4702:         &Apache::loncommon::load_tmp_file($request,$datatoken);
 4703:     }
 4704:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4705:     my %fields=&get_fields();
 4706:     my $courseid=$env{'request.course.id'};
 4707:     my ($classlist) = &getclasslist('all',0);
 4708:     my @notallowed;
 4709:     my @skipped;
 4710:     my @warnings;
 4711:     my $countdone=0;
 4712:     foreach my $grade (@gradedata) {
 4713: 	my %entries=&Apache::loncommon::record_sep($grade);
 4714: 	my $domain;
 4715: 	if ($entries{$fields{'domain'}}) {
 4716: 	    $domain=$entries{$fields{'domain'}};
 4717: 	} else {
 4718: 	    $domain=$env{'form.default_domain'};
 4719: 	}
 4720: 	$domain=~s/\s//g;
 4721: 	my $username=$entries{$fields{'username'}};
 4722: 	$username=~s/\s//g;
 4723: 	if (!$username) {
 4724: 	    my $id=$entries{$fields{'ID'}};
 4725: 	    $id=~s/\s//g;
 4726:             if ($id ne '') {
 4727: 	        my %ids=&Apache::lonnet::idget($domain,[$id]);
 4728: 	        $username=$ids{$id};
 4729:             } else {
 4730:                 if ($entries{$fields{'clicker'}}) {
 4731:                     my $clicker = $entries{$fields{'clicker'}};
 4732:                     $clicker=~s/\s//g;
 4733:                     if ($clicker ne '') {
 4734:                         my %clickers = &Apache::lonnet::idget($domain,[$clicker],'clickers');
 4735:                         if ($clickers{$clicker} ne '') {  
 4736:                             my $match = 0;
 4737:                             my @inclass;
 4738:                             foreach my $poss (split(/,/,$clickers{$clicker})) {
 4739:                                 if (exists($$classlist{"$poss:$domain"})) {
 4740:                                     $username = $poss;
 4741:                                     push(@inclass,$poss);
 4742:                                     $match ++;
 4743:                                     
 4744:                                 }
 4745:                             }
 4746:                             if ($match > 1) {
 4747:                                 undef($username); 
 4748:                                 $request->print('<p class="LC_warning">'.
 4749:                                                 &mt('Score not saved for clicker: [_1] (matched multiple usernames: [_2])',
 4750:                                                 $clicker,join(', ',@inclass)).'</p>');
 4751:                             }
 4752:                         }
 4753:                     }
 4754:                 }
 4755:             }
 4756: 	}
 4757: 	if (!exists($$classlist{"$username:$domain"})) {
 4758: 	    my $id=$entries{$fields{'ID'}};
 4759: 	    $id=~s/\s//g;
 4760:             my $clicker = $entries{$fields{'clicker'}};
 4761:             $clicker=~s/\s//g;
 4762:             if ($clicker) {
 4763:                 push(@skipped,"$clicker:$domain");
 4764: 	    } elsif ($id) {
 4765: 		push(@skipped,"$id:$domain");
 4766: 	    } else {
 4767: 		push(@skipped,"$username:$domain");
 4768: 	    }
 4769: 	    next;
 4770: 	}
 4771: 	my $usec=$classlist->{"$username:$domain"}[5];
 4772: 	if (!&canmodify($usec)) {
 4773: 	    push(@notallowed,"$username:$domain");
 4774: 	    next;
 4775: 	}
 4776: 	my %points;
 4777: 	my %grades;
 4778: 	foreach my $dest (keys(%fields)) {
 4779: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4780: 		$dest eq 'domain') { next; }
 4781: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4782: 	    if ($dest=~/stores_(.*)_points/) {
 4783: 		my $part=$1;
 4784: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4785: 					      $symb,$domain,$username);
 4786:                 if ($wgt) {
 4787:                     $entries{$fields{$dest}}=~s/\s//g;
 4788:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4789:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4790:                                           : 'correct_by_override';
 4791:                     if ($pcr>1) {
 4792:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
 4793:                     }
 4794:                     $grades{"resource.$part.awarded"}=$pcr;
 4795:                     $grades{"resource.$part.solved"}=$award;
 4796:                     $points{$part}=1;
 4797:                 } else {
 4798:                     $error_msg = "<br />" .
 4799:                         &mt("Some point values were assigned"
 4800:                             ." for problems with a weight "
 4801:                             ."of zero. These values were "
 4802:                             ."ignored.");
 4803:                 }
 4804: 	    } else {
 4805: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4806: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4807: 		my $store_key=$dest;
 4808: 		$store_key=~s/^stores/resource/;
 4809: 		$store_key=~s/_/\./g;
 4810: 		$grades{$store_key}=$entries{$fields{$dest}};
 4811: 	    }
 4812: 	}
 4813: 	if (! %grades) { 
 4814:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4815:         } else {
 4816: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4817: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4818: 					   $env{'request.course.id'},
 4819: 					   $domain,$username);
 4820: 	   if ($result eq 'ok') {
 4821: # Successfully stored
 4822: 	      $request->print('.');
 4823: # Remove from grading queue
 4824:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
 4825:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
 4826:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
 4827:                                              $domain,$username);
 4828:               $countdone++;
 4829:            } else {
 4830: 	      $request->print("<p><span class=\"LC_error\">".
 4831:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4832:                                   "$username:$domain",$result)."</span></p>");
 4833: 	   }
 4834: 	   $request->rflush();
 4835:         }
 4836:     }
 4837:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 4838:     if (@warnings) {
 4839:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
 4840:         $request->print(join(', ',@warnings));
 4841:     }
 4842:     if (@skipped) {
 4843: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 4844:         $request->print(join(', ',@skipped));
 4845:     }
 4846:     if (@notallowed) {
 4847: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 4848: 	$request->print(join(', ',@notallowed));
 4849:     }
 4850:     $request->print("<br />\n");
 4851:     return $error_msg;
 4852: }
 4853: #------------- end of section for handling csv file upload ---------
 4854: #
 4855: #-------------------------------------------------------------------
 4856: #
 4857: #-------------- Next few routines handle grading by page/sequence
 4858: #
 4859: #--- Select a page/sequence and a student to grade
 4860: sub pickStudentPage {
 4861:     my ($request,$symb) = @_;
 4862: 
 4863:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4864:     &js_escape(\$alertmsg);
 4865:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
 4866: 
 4867: function checkPickOne(formname) {
 4868:     if (radioSelection(formname.student) == null) {
 4869: 	alert("$alertmsg");
 4870: 	return;
 4871:     }
 4872:     ptr = pullDownSelection(formname.selectpage);
 4873:     formname.page.value = formname["page"+ptr].value;
 4874:     formname.title.value = formname["title"+ptr].value;
 4875:     formname.submit();
 4876: }
 4877: 
 4878: LISTJAVASCRIPT
 4879:     &commonJSfunctions($request);
 4880: 
 4881:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4882:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4883:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4884: 
 4885:     my $result='<h3><span class="LC_info">&nbsp;'.
 4886: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4887: 
 4888:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4889:     my $map_error;
 4890:     my ($titles,$symbx) = &getSymbMap($map_error);
 4891:     if ($map_error) {
 4892:         $request->print(&navmap_errormsg());
 4893:         return; 
 4894:     }
 4895:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4896: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4897: #    my $type=($curpage =~ /\.(page|sequence)/);
 4898: 
 4899:     # Collection of hidden fields
 4900:     my $ctr=0;
 4901:     foreach (@$titles) {
 4902:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4903:         $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4904:         $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4905:         $ctr++;
 4906:     }
 4907:     $result.='<input type="hidden" name="page" />'."\n".
 4908:         '<input type="hidden" name="title" />'."\n";
 4909: 
 4910:     $result.=&build_section_inputs();
 4911:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4912:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4913: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4914: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 4915: 
 4916:     # Show grading options
 4917:     $result.=&Apache::lonhtmlcommon::start_pick_box();
 4918:     my $select = '<select name="selectpage">'."\n";
 4919:     $ctr=0;
 4920:     foreach (@$titles) {
 4921: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4922: 	$select.='<option value="'.$ctr.'"'.
 4923: 	    ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
 4924: 	    '>'.$showtitle.'</option>'."\n";
 4925: 	$ctr++;
 4926:     }
 4927:     $select.= '</select>';
 4928: 
 4929:     $result.=
 4930:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
 4931:        .$select
 4932:        .&Apache::lonhtmlcommon::row_closure();
 4933: 
 4934:     $result.=
 4935:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
 4936:        .'<label><input type="radio" name="vProb" value="no"'
 4937:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
 4938:        .'<label><input type="radio" name="vProb" value="yes" />'
 4939:            .&mt('yes').'</label>'."\n"
 4940:        .&Apache::lonhtmlcommon::row_closure();
 4941: 
 4942:     $result.=
 4943:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
 4944:        .'<label><input type="radio" name="lastSub" value="none" /> '
 4945:            .&mt('none').' </label>'."\n"
 4946:        .'<label><input type="radio" name="lastSub" value="datesub"'
 4947:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
 4948:        .'<label><input type="radio" name="lastSub" value="all" /> '
 4949:            .&mt('all submissions with details').' </label>'
 4950:        .&Apache::lonhtmlcommon::row_closure();
 4951:     
 4952:     $result.=
 4953:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
 4954:        .'<input type="text" name="CODE" value="" />'
 4955:        .&Apache::lonhtmlcommon::row_closure(1)
 4956:        .&Apache::lonhtmlcommon::end_pick_box();
 4957: 
 4958:     # Show list of students to select for grading
 4959:     $result.='<br /><input type="button" '.
 4960:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4961: 
 4962:     $request->print($result);
 4963: 
 4964:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4965: 	&Apache::loncommon::start_data_table().
 4966: 	&Apache::loncommon::start_data_table_header_row().
 4967: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4968: 	'<th>'.&nameUserString('header').'</th>'.
 4969: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4970: 	'<th>'.&nameUserString('header').'</th>'.
 4971: 	&Apache::loncommon::end_data_table_header_row();
 4972:  
 4973:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4974:     my $ptr = 1;
 4975:     foreach my $student (sort 
 4976: 			 {
 4977: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4978: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4979: 			     }
 4980: 			     return $a cmp $b;
 4981: 			 } (keys(%$fullname))) {
 4982: 	my ($uname,$udom) = split(/:/,$student);
 4983: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4984:                                   : '</td>');
 4985: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4986: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4987: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4988: 	$studentTable.=
 4989: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4990:                          : '');
 4991: 	$ptr++;
 4992:     }
 4993:     if ($ptr%2 == 0) {
 4994: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4995: 	    &Apache::loncommon::end_data_table_row();
 4996:     }
 4997:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4998:     $studentTable.='<input type="button" '.
 4999:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 5000: 
 5001:     $request->print($studentTable);
 5002: 
 5003:     return '';
 5004: }
 5005: 
 5006: sub getSymbMap {
 5007:     my ($map_error) = @_;
 5008:     my $navmap = Apache::lonnavmaps::navmap->new();
 5009:     unless (ref($navmap)) {
 5010:         if (ref($map_error)) {
 5011:             $$map_error = 'navmap';
 5012:         }
 5013:         return;
 5014:     }
 5015:     my %symbx = ();
 5016:     my @titles = ();
 5017:     my $minder = 0;
 5018: 
 5019:     # Gather every sequence that has problems.
 5020:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 5021: 					       1,0,1);
 5022:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 5023: 	if ($navmap->hasResource($sequence, sub { shift->is_gradable(); }, 0) ) {
 5024: 	    my $title = $minder.'.'.
 5025: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 5026: 	    push(@titles, $title); # minder in case two titles are identical
 5027: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 5028: 	    $minder++;
 5029: 	}
 5030:     }
 5031:     return \@titles,\%symbx;
 5032: }
 5033: 
 5034: #
 5035: #--- Displays a page/sequence w/wo problems, w/wo submissions
 5036: sub displayPage {
 5037:     my ($request,$symb) = @_;
 5038:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5039:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5040:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5041:     my $pageTitle = $env{'form.page'};
 5042:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5043:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5044:     my $usec=$classlist->{$env{'form.student'}}[5];
 5045: 
 5046:     #need to make sure we have the correct data for later EXT calls, 
 5047:     #thus invalidate the cache
 5048:     &Apache::lonnet::devalidatecourseresdata(
 5049:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 5050:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 5051:     &Apache::lonnet::clear_EXT_cache_status();
 5052: 
 5053:     if (!&canview($usec)) {
 5054:         $request->print(
 5055:             '<span class="LC_warning">'.
 5056:             &mt('Unable to view requested student. ([_1])',
 5057:                     $env{'form.student'}).
 5058:             '</span>');
 5059:         return;
 5060:     }
 5061:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5062:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 5063: 	'</h3>'."\n";
 5064:     $env{'form.CODE'} = uc($env{'form.CODE'});
 5065:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 5066: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 5067:     } else {
 5068: 	delete($env{'form.CODE'});
 5069:     }
 5070:     &sub_page_js($request);
 5071:     $request->print($result);
 5072: 
 5073:     my $navmap = Apache::lonnavmaps::navmap->new();
 5074:     unless (ref($navmap)) {
 5075:         $request->print(&navmap_errormsg());
 5076:         return;
 5077:     }
 5078:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 5079:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5080:     if (!$map) {
 5081: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 5082: 	return; 
 5083:     }
 5084:     my $iterator = $navmap->getIterator($map->map_start(),
 5085: 					$map->map_finish());
 5086: 
 5087:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 5088: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 5089: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 5090: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 5091: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 5092: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 5093: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 5094: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
 5095: 
 5096:     if (defined($env{'form.CODE'})) {
 5097: 	$studentTable.=
 5098: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 5099:     }
 5100:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 5101: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 5102: 
 5103:     $studentTable.='&nbsp;<span class="LC_info">'.
 5104:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 5105:         '</span>'."\n".
 5106: 	&Apache::loncommon::start_data_table().
 5107: 	&Apache::loncommon::start_data_table_header_row().
 5108: 	'<th>'.&mt('Prob.').'</th>'.
 5109: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 5110: 	&Apache::loncommon::end_data_table_header_row();
 5111: 
 5112:     &Apache::lonxml::clear_problem_counter();
 5113:     my ($depth,$question,$prob) = (1,1,1);
 5114:     $iterator->next(); # skip the first BEGIN_MAP
 5115:     my $curRes = $iterator->next(); # for "current resource"
 5116:     while ($depth > 0) {
 5117:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5118:         if($curRes == $iterator->END_MAP) { $depth--; }
 5119: 
 5120:         if (ref($curRes) && $curRes->is_gradable()) {
 5121: 	    my $parts = $curRes->parts();
 5122:             my $title = $curRes->compTitle();
 5123: 	    my $symbx = $curRes->symb();
 5124:             my $is_tool = ($symbx =~ /ext\.tool$/);
 5125: 	    $studentTable.=
 5126: 		&Apache::loncommon::start_data_table_row().
 5127: 		'<td align="center" valign="top" >'.$prob.
 5128: 		(scalar(@{$parts}) == 1 ? '' 
 5129: 		                        : '<br />('.&mt('[_1]parts',
 5130: 							scalar(@{$parts}).'&nbsp;').')'
 5131: 		 ).
 5132: 		 '</td>';
 5133: 	    $studentTable.='<td valign="top">';
 5134: 	    my %form = ('CODE' => $env{'form.CODE'},);
 5135:             if ($is_tool) {
 5136:                 $studentTable.='&nbsp;<b>'.$title.'</b><br />';
 5137:             } else {
 5138: 	        if ($env{'form.vProb'} eq 'yes' ) {
 5139: 		    $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 5140: 					         undef,'both',\%form);
 5141: 	        } else {
 5142: 		    my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 5143: 		    $companswer =~ s|<form(.*?)>||g;
 5144: 		    $companswer =~ s|</form>||g;
 5145: #		    while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 5146: #		        $companswer =~ s/$1/ /ms;
 5147: #		        $request->print('match='.$1."<br />\n");
 5148: #		    }
 5149: #		    $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 5150: 		    $studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 5151: 		}
 5152: 	    }
 5153: 
 5154: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 5155: 
 5156: 	    if ($env{'form.lastSub'} eq 'datesub') {
 5157: 		if ($record{'version'} eq '') {
 5158:                     my $msg = &mt('No recorded submission for this problem.');
 5159:                     if ($is_tool) {
 5160:                         $msg = &mt('No recorded transactions for this external tool');
 5161:                     }
 5162: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.$msg.'</span><br />';
 5163: 		} else {
 5164: 		    my %responseType = ();
 5165: 		    foreach my $partid (@{$parts}) {
 5166: 			my @responseIds =$curRes->responseIds($partid);
 5167: 			my @responseType =$curRes->responseType($partid);
 5168: 			my %responseIds;
 5169: 			for (my $i=0;$i<=$#responseIds;$i++) {
 5170: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 5171: 			}
 5172: 			$responseType{$partid} = \%responseIds;
 5173: 		    }
 5174: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 5175: 		}
 5176: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 5177: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 5178:                 my $identifier = (&canmodify($usec)? $prob : ''); 
 5179: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 5180: 									$env{'request.course.id'},
 5181: 									'','.submission',undef,
 5182:                                                                         $usec,$identifier);
 5183:  
 5184: 	    }
 5185: 	    if (&canmodify($usec)) {
 5186:             $studentTable.=&gradeBox_start();
 5187: 		foreach my $partid (@{$parts}) {
 5188: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 5189: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 5190: 		    $question++;
 5191: 		}
 5192:             $studentTable.=&gradeBox_end();
 5193: 		$prob++;
 5194: 	    }
 5195: 	    $studentTable.='</td></tr>';
 5196: 
 5197: 	}
 5198:         $curRes = $iterator->next();
 5199:     }
 5200: 
 5201:     $studentTable.=
 5202:         '</table>'."\n".
 5203:         '<input type="button" value="'.&mt('Save').'" '.
 5204:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 5205:         '</form>'."\n";
 5206:     $request->print($studentTable);
 5207: 
 5208:     return '';
 5209: }
 5210: 
 5211: sub displaySubByDates {
 5212:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 5213:     my $isCODE=0;
 5214:     my $isTask = ($symb =~/\.task$/);
 5215:     my $is_tool = ($symb =~/\.tool$/);
 5216:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 5217:     my $studentTable=&Apache::loncommon::start_data_table().
 5218: 	&Apache::loncommon::start_data_table_header_row().
 5219: 	'<th>'.&mt('Date/Time').'</th>'.
 5220: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 5221:         ($isTask?'<th>'.&mt('Version').'</th>':'').
 5222: 	'<th>'.($is_tool?&mt('Grade'):&mt('Submission')).'</th>'.
 5223: 	'<th>'.&mt('Status').'</th>'.
 5224: 	&Apache::loncommon::end_data_table_header_row();
 5225:     my ($version);
 5226:     my %mark;
 5227:     my %orders;
 5228:     $mark{'correct_by_student'} = $checkIcon;
 5229:     if (!exists($$record{'1:timestamp'})) {
 5230:         if ($is_tool) {
 5231:             return '<br />&nbsp;<span class="LC_warning">'.&mt('No grade passed back.').'</span><br />';
 5232:         } else {
 5233:             return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 5234:         }
 5235:     }
 5236: 
 5237:     my $interaction;
 5238:     my $no_increment = 1;
 5239:     my (%lastrndseed,%lasttype);
 5240:     for ($version=1;$version<=$$record{'version'};$version++) {
 5241: 	my $timestamp = 
 5242: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 5243: 	if (exists($$record{$version.':resource.0.version'})) {
 5244: 	    $interaction = $$record{$version.':resource.0.version'};
 5245: 	}
 5246:         if ($isTask && $env{'form.previousversion'}) {
 5247:             next unless ($interaction == $env{'form.previousversion'});
 5248:         }
 5249: 	my $where = ($isTask ? "$version:resource.$interaction"
 5250: 		             : "$version:resource");
 5251: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 5252: 	    '<td>'.$timestamp.'</td>';
 5253: 	if ($isCODE) {
 5254: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 5255: 	}
 5256:         if ($isTask) {
 5257:             $studentTable.='<td>'.$interaction.'</td>';
 5258:         }
 5259: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 5260: 	my @displaySub = ();
 5261: 	foreach my $partid (@{$parts}) {
 5262:             my ($hidden,$type);
 5263:             $type = $$record{$version.':resource.'.$partid.'.type'};
 5264:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
 5265:                 $hidden = 1;
 5266:             }
 5267:             my @matchKey;
 5268:             if ($isTask) {
 5269:                 @matchKey = sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys);
 5270:             } elsif ($is_tool) {
 5271:                 @matchKey = sort(grep /^resource\.\Q$partid\E\.awarded$/,@versionKeys);
 5272:             } else {
 5273:                 @matchKey = sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys);
 5274:             }
 5275: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 5276: 	    my $display_part=&get_display_part($partid,$symb);
 5277: 	    foreach my $matchKey (@matchKey) {
 5278: 		if (exists($$record{$version.':'.$matchKey}) &&
 5279: 		    $$record{$version.':'.$matchKey} ne '') {
 5280:                     if ($is_tool) {
 5281:                         $displaySub[0].=$$record{"$version:resource.$partid.awarded"};
 5282:                     } else {
 5283: 		        my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 5284: 				                   : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 5285:                         $displaySub[0].='<span class="LC_nobreak">';
 5286:                         $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 5287:                                        .' <span class="LC_internal_info">'
 5288:                                        .'('.&mt('Response ID: [_1]',$responseId).')'
 5289:                                        .'</span>'
 5290:                                        .' <b>';
 5291:                         if ($hidden) {
 5292:                             $displaySub[0].= &mt('Anonymous Survey').'</b>';
 5293:                         } else {
 5294:                             my ($trial,$rndseed,$newvariation);
 5295:                             if ($type eq 'randomizetry') {
 5296:                                 $trial = $$record{"$where.$partid.tries"};
 5297:                                 $rndseed = $$record{"$where.$partid.rndseed"};
 5298:                             }
 5299: 		            if ($$record{"$where.$partid.tries"} eq '') {
 5300: 			        $displaySub[0].=&mt('Trial not counted');
 5301: 		            } else {
 5302: 			        $displaySub[0].=&mt('Trial: [_1]',
 5303: 					        $$record{"$where.$partid.tries"});
 5304:                                 if (($rndseed ne '') && ($lastrndseed{$partid} ne '')) {
 5305:                                     if (($rndseed ne $lastrndseed{$partid}) &&
 5306:                                         (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
 5307:                                         $newvariation = '&nbsp;('.&mt('New variation this try').')';
 5308:                                     }
 5309:                                 }
 5310:                                 $lastrndseed{$partid} = $rndseed;
 5311:                                 $lasttype{$partid} = $type;
 5312: 		            }
 5313: 		            my $responseType=($isTask ? 'Task'
 5314:                                               : $responseType->{$partid}->{$responseId});
 5315: 		            if (!exists($orders{$partid})) { $orders{$partid}={}; }
 5316: 		            if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
 5317: 			        $orders{$partid}->{$responseId}=
 5318: 			            &get_order($partid,$responseId,$symb,$uname,$udom,
 5319:                                                $no_increment,$type,$trial,$rndseed);
 5320: 		            }
 5321: 		            $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
 5322: 		            $displaySub[0].='&nbsp; '.
 5323: 			        &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
 5324:                         }
 5325:                     }
 5326: 		}
 5327: 	    }
 5328: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 5329: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 5330: 				    $$record{"$where.$partid.checkedin"},
 5331: 				    $$record{"$where.$partid.checkedin.slot"}).
 5332: 					'<br />';
 5333: 	    }
 5334: 	    if (exists $$record{"$where.$partid.award"}) {
 5335: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 5336: 		    lc($$record{"$where.$partid.award"}).' '.
 5337: 		    $mark{$$record{"$where.$partid.solved"}}.
 5338: 		    '<br />';
 5339: 	    } elsif (($is_tool) && (exists($$record{"$version:resource.$partid.solved"}))) {
 5340: 		if ($$record{"$version:resource.$partid.solved"} =~ /^(in|)correct_by_passback$/) {
 5341: 		    $displaySub[1].=&mt('Grade passed back by external tool');
 5342: 		}
 5343: 	    }
 5344: 	    if (exists $$record{"$where.$partid.regrader"}) {
 5345: 		$displaySub[2].=$$record{"$where.$partid.regrader"};
 5346: 		unless ($is_tool) {
 5347: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5348: 		}
 5349: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 5350: 		$displaySub[2].=
 5351: 		    $$record{"$version:resource.$partid.regrader"};
 5352:                 unless ($is_tool) {
 5353: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5354:                 }
 5355: 	    }
 5356: 	}
 5357: 	# needed because old essay regrader has not parts info
 5358: 	if (exists $$record{"$version:resource.regrader"}) {
 5359: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 5360: 	}
 5361: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 5362: 	if ($displaySub[2]) {
 5363: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 5364: 	}
 5365: 	$studentTable.='&nbsp;</td>'.
 5366: 	    &Apache::loncommon::end_data_table_row();
 5367:     }
 5368:     $studentTable.=&Apache::loncommon::end_data_table();
 5369:     return $studentTable;
 5370: }
 5371: 
 5372: sub updateGradeByPage {
 5373:     my ($request,$symb) = @_;
 5374: 
 5375:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5376:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5377:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5378:     my $pageTitle = $env{'form.page'};
 5379:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5380:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5381:     my $usec=$classlist->{$env{'form.student'}}[5];
 5382:     if (!&canmodify($usec)) {
 5383: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 5384: 	return;
 5385:     }
 5386:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5387:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 5388: 	'</h3>'."\n";
 5389: 
 5390:     $request->print($result);
 5391: 
 5392: 
 5393:     my $navmap = Apache::lonnavmaps::navmap->new();
 5394:     unless (ref($navmap)) {
 5395:         $request->print(&navmap_errormsg());
 5396:         return;
 5397:     }
 5398:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 5399:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5400:     if (!$map) {
 5401: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 5402: 	return; 
 5403:     }
 5404:     my $iterator = $navmap->getIterator($map->map_start(),
 5405: 					$map->map_finish());
 5406: 
 5407:     my $studentTable=
 5408: 	&Apache::loncommon::start_data_table().
 5409: 	&Apache::loncommon::start_data_table_header_row().
 5410: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 5411: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 5412: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 5413: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 5414: 	&Apache::loncommon::end_data_table_header_row();
 5415: 
 5416:     $iterator->next(); # skip the first BEGIN_MAP
 5417:     my $curRes = $iterator->next(); # for "current resource"
 5418:     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
 5419:     while ($depth > 0) {
 5420:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5421:         if($curRes == $iterator->END_MAP) { $depth--; }
 5422: 
 5423:         if (ref($curRes) && $curRes->is_problem()) {
 5424: 	    my $parts = $curRes->parts();
 5425:             my $title = $curRes->compTitle();
 5426: 	    my $symbx = $curRes->symb();
 5427: 	    $studentTable.=
 5428: 		&Apache::loncommon::start_data_table_row().
 5429: 		'<td align="center" valign="top" >'.$prob.
 5430: 		(scalar(@{$parts}) == 1 ? '' 
 5431:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
 5432: 		.')').'</td>';
 5433: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 5434: 
 5435: 	    my %newrecord=();
 5436: 	    my @displayPts=();
 5437:             my %aggregate = ();
 5438:             my $aggregateflag = 0;
 5439:             if ($env{'form.HIDE'.$prob}) {
 5440:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 5441:                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
 5442:                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
 5443:                 $hideflag += $numchgs;
 5444:             }
 5445: 	    foreach my $partid (@{$parts}) {
 5446: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 5447: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 5448: 
 5449: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 5450: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 5451: 		my $partial = $newpts/$wgt;
 5452: 		my $score;
 5453: 		if ($partial > 0) {
 5454: 		    $score = 'correct_by_override';
 5455: 		} elsif ($newpts ne '') { #empty is taken as 0
 5456: 		    $score = 'incorrect_by_override';
 5457: 		}
 5458: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 5459: 		if ($dropMenu eq 'excused') {
 5460: 		    $partial = '';
 5461: 		    $score = 'excused';
 5462: 		} elsif ($dropMenu eq 'reset status'
 5463: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 5464: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 5465: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 5466: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 5467: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 5468: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 5469: 		    $changeflag++;
 5470: 		    $newpts = '';
 5471:                     
 5472:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 5473:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 5474:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 5475:                     if ($aggtries > 0) {
 5476:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 5477:                         $aggregateflag = 1;
 5478:                     }
 5479: 		}
 5480: 		my $display_part=&get_display_part($partid,$curRes->symb());
 5481: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 5482: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5483: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 5484: 		    '&nbsp;<br />';
 5485: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5486: 		     (($score eq 'excused') ? 'excused' : $newpts).
 5487: 		    '&nbsp;<br />';
 5488: 		$question++;
 5489: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 5490: 
 5491: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 5492: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 5493: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 5494: 		    if (scalar(keys(%newrecord)) > 0);
 5495: 
 5496: 		$changeflag++;
 5497: 	    }
 5498: 	    if (scalar(keys(%newrecord)) > 0) {
 5499: 		my %record = 
 5500: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 5501: 					     $udom,$uname);
 5502: 
 5503: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 5504: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 5505: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 5506: 		    $newrecord{'resource.CODE'} = '';
 5507: 		}
 5508: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 5509: 					$udom,$uname);
 5510: 		%record = &Apache::lonnet::restore($symbx,
 5511: 						   $env{'request.course.id'},
 5512: 						   $udom,$uname);
 5513: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 5514: 					     $cdom,$cnum,$udom,$uname);
 5515: 	    }
 5516: 	    
 5517:             if ($aggregateflag) {
 5518:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 5519:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 5520:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 5521:             }
 5522: 
 5523: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 5524: 		'<td valign="top">'.$displayPts[1].'</td>'.
 5525: 		&Apache::loncommon::end_data_table_row();
 5526: 
 5527: 	    $prob++;
 5528: 	}
 5529:         $curRes = $iterator->next();
 5530:     }
 5531: 
 5532:     $studentTable.=&Apache::loncommon::end_data_table();
 5533:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 5534: 		  &mt('The scores were changed for [quant,_1,problem].',
 5535: 		  $changeflag).'<br />');
 5536:     my $hidemsg=($hideflag == 0 ? '' :
 5537:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
 5538:                      $hideflag).'<br />');
 5539:     $request->print($hidemsg.$grademsg.$studentTable);
 5540: 
 5541:     return '';
 5542: }
 5543: 
 5544: #-------- end of section for handling grading by page/sequence ---------
 5545: #
 5546: #-------------------------------------------------------------------
 5547: 
 5548: #-------------------- Bubblesheet (Scantron) Grading -------------------
 5549: #
 5550: #------ start of section for handling grading by page/sequence ---------
 5551: 
 5552: =pod
 5553: 
 5554: =head1 Bubble sheet grading routines
 5555: 
 5556:   For this documentation:
 5557: 
 5558:    'scanline' refers to the full line of characters
 5559:    from the file that we are parsing that represents one entire sheet
 5560: 
 5561:    'bubble line' refers to the data
 5562:    representing the line of bubbles that are on the physical bubblesheet
 5563: 
 5564: 
 5565: The overall process is that a scanned in bubblesheet data is uploaded
 5566: into a course. When a user wants to grade, they select a
 5567: sequence/folder of resources, a file of bubblesheet info, and pick
 5568: one of the predefined configurations for what each scanline looks
 5569: like.
 5570: 
 5571: Next each scanline is checked for any errors of either 'missing
 5572: bubbles' (it's an error because it may have been mis-scanned
 5573: because too light bubbling), 'double bubble' (each bubble line should
 5574: have no more than one letter picked), invalid or duplicated CODE,
 5575: invalid student/employee ID
 5576: 
 5577: If the CODE option is used that determines the randomization of the
 5578: homework problems, either way the student/employee ID is looked up into a
 5579: username:domain.
 5580: 
 5581: During the validation phase the instructor can choose to skip scanlines. 
 5582: 
 5583: After the validation phase, there are now 3 bubblesheet files
 5584: 
 5585:   scantron_original_filename (unmodified original file)
 5586:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 5587:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 5588: 
 5589: Also there is a separate hash nohist_scantrondata that contains extra
 5590: correction information that isn't representable in the bubblesheet
 5591: file (see &scantron_getfile() for more information)
 5592: 
 5593: After all scanlines are either valid, marked as valid or skipped, then
 5594: foreach line foreach problem in the picked sequence, an ssi request is
 5595: made that simulates a user submitting their selected letter(s) against
 5596: the homework problem.
 5597: 
 5598: =over 4
 5599: 
 5600: 
 5601: 
 5602: =item defaultFormData
 5603: 
 5604:   Returns html hidden inputs used to hold context/default values.
 5605: 
 5606:  Arguments:
 5607:   $symb - $symb of the current resource 
 5608: 
 5609: =cut
 5610: 
 5611: sub defaultFormData {
 5612:     my ($symb)=@_;
 5613:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
 5614: }
 5615: 
 5616: 
 5617: =pod 
 5618: 
 5619: =item getSequenceDropDown
 5620: 
 5621:    Return html dropdown of possible sequences to grade
 5622:  
 5623:  Arguments:
 5624:    $symb - $symb of the current resource
 5625:    $map_error - ref to scalar which will container error if
 5626:                 $navmap object is unavailable in &getSymbMap().
 5627: 
 5628: =cut
 5629: 
 5630: sub getSequenceDropDown {
 5631:     my ($symb,$map_error)=@_;
 5632:     my $result='<select name="selectpage">'."\n";
 5633:     my ($titles,$symbx) = &getSymbMap($map_error);
 5634:     if (ref($map_error)) {
 5635:         return if ($$map_error);
 5636:     }
 5637:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 5638:     my $ctr=0;
 5639:     foreach (@$titles) {
 5640: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5641: 	$result.='<option value="'.$$symbx{$_}.'" '.
 5642: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 5643: 	    '>'.$showtitle.'</option>'."\n";
 5644: 	$ctr++;
 5645:     }
 5646:     $result.= '</select>';
 5647:     return $result;
 5648: }
 5649: 
 5650: my %bubble_lines_per_response;     # no. bubble lines for each response.
 5651:                                    # key is zero-based index - 0, 1, 2 ...
 5652: 
 5653: my %first_bubble_line;             # First bubble line no. for each bubble.
 5654: 
 5655: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 5656:                                    # matchresponse or rankresponse, where 
 5657:                                    # an individual response can have multiple 
 5658:                                    # lines
 5659: 
 5660: my %responsetype_per_response;     # responsetype for each response
 5661: 
 5662: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
 5663:                                    # numbered response. Needed when randomorder
 5664:                                    # or randompick are in use. Key is ID, value 
 5665:                                    # is response number.
 5666: 
 5667: # Save and restore the bubble lines array to the form env.
 5668: 
 5669: 
 5670: sub save_bubble_lines {
 5671:     foreach my $line (keys(%bubble_lines_per_response)) {
 5672: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 5673: 	$env{"form.scantron.first_bubble_line.$line"} =
 5674: 	    $first_bubble_line{$line};
 5675:         $env{"form.scantron.sub_bubblelines.$line"} = 
 5676:             $subdivided_bubble_lines{$line};
 5677:         $env{"form.scantron.responsetype.$line"} =
 5678:             $responsetype_per_response{$line};
 5679:     }
 5680:     foreach my $resid (keys(%masterseq_id_responsenum)) {
 5681:         my $line = $masterseq_id_responsenum{$resid};
 5682:         $env{"form.scantron.residpart.$line"} = $resid;
 5683:     }
 5684: }
 5685: 
 5686: 
 5687: sub restore_bubble_lines {
 5688:     my $line = 0;
 5689:     %bubble_lines_per_response = ();
 5690:     %masterseq_id_responsenum = ();
 5691:     while ($env{"form.scantron.bubblelines.$line"}) {
 5692: 	my $value = $env{"form.scantron.bubblelines.$line"};
 5693: 	$bubble_lines_per_response{$line} = $value;
 5694: 	$first_bubble_line{$line}  =
 5695: 	    $env{"form.scantron.first_bubble_line.$line"};
 5696:         $subdivided_bubble_lines{$line} =
 5697:             $env{"form.scantron.sub_bubblelines.$line"};
 5698:         $responsetype_per_response{$line} =
 5699:             $env{"form.scantron.responsetype.$line"};
 5700:         my $id = $env{"form.scantron.residpart.$line"};
 5701:         $masterseq_id_responsenum{$id} = $line;
 5702: 	$line++;
 5703:     }
 5704: }
 5705: 
 5706: =pod 
 5707: 
 5708: =item scantron_filenames
 5709: 
 5710:    Returns a list of the scantron files in the current course 
 5711: 
 5712: =cut
 5713: 
 5714: sub scantron_filenames {
 5715:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5716:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5717:     my $getpropath = 1;
 5718:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
 5719:                                                         $cname,$getpropath);
 5720:     my @possiblenames;
 5721:     if (ref($dirlist) eq 'ARRAY') {
 5722:         foreach my $filename (sort(@{$dirlist})) {
 5723: 	    ($filename)=split(/&/,$filename);
 5724: 	    if ($filename!~/^scantron_orig_/) { next ; }
 5725: 	    $filename=~s/^scantron_orig_//;
 5726: 	    push(@possiblenames,$filename);
 5727:         }
 5728:     }
 5729:     return @possiblenames;
 5730: }
 5731: 
 5732: =pod 
 5733: 
 5734: =item scantron_uploads
 5735: 
 5736:    Returns  html drop-down list of scantron files in current course.
 5737: 
 5738:  Arguments:
 5739:    $file2grade - filename to set as selected in the dropdown
 5740: 
 5741: =cut
 5742: 
 5743: sub scantron_uploads {
 5744:     my ($file2grade) = @_;
 5745:     my $result=	'<select name="scantron_selectfile">';
 5746:     $result.="<option></option>";
 5747:     foreach my $filename (sort(&scantron_filenames())) {
 5748: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 5749:     }
 5750:     $result.="</select>";
 5751:     return $result;
 5752: }
 5753: 
 5754: =pod 
 5755: 
 5756: =item scantron_scantab
 5757: 
 5758:   Returns html drop down of the scantron formats in the scantronformat.tab
 5759:   file.
 5760: 
 5761: =cut
 5762: 
 5763: sub scantron_scantab {
 5764:     my $result='<select name="scantron_format">'."\n";
 5765:     $result.='<option></option>'."\n";
 5766:     my @lines = &get_scantronformat_file();
 5767:     if (@lines > 0) {
 5768:         foreach my $line (@lines) {
 5769:             next if (($line =~ /^\#/) || ($line eq ''));
 5770: 	    my ($name,$descrip)=split(/:/,$line);
 5771: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 5772:         }
 5773:     }
 5774:     $result.='</select>'."\n";
 5775:     return $result;
 5776: }
 5777: 
 5778: =pod
 5779: 
 5780: =item get_scantronformat_file
 5781: 
 5782:   Returns an array containing lines from the scantron format file for
 5783:   the domain of the course.
 5784: 
 5785:   If a url for a custom.tab file is listed in domain's configuration.db, 
 5786:   lines are from this file.
 5787: 
 5788:   Otherwise, if a default.tab has been published in RES space by the 
 5789:   domainconfig user, lines are from this file.
 5790: 
 5791:   Otherwise, fall back to getting lines from the legacy file on the
 5792:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 5793: 
 5794: =cut
 5795: 
 5796: sub get_scantronformat_file {
 5797:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5798:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 5799:     my $gottab = 0;
 5800:     my @lines;
 5801:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5802:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5803:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5804:             if ($formatfile ne '-1') {
 5805:                 @lines = split("\n",$formatfile,-1);
 5806:                 $gottab = 1;
 5807:             }
 5808:         }
 5809:     }
 5810:     if (!$gottab) {
 5811:         my $confname = $cdom.'-domainconfig';
 5812:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5813:         my $formatfile =  &Apache::lonnet::getfile($default);
 5814:         if ($formatfile ne '-1') {
 5815:             @lines = split("\n",$formatfile,-1);
 5816:             $gottab = 1;
 5817:         }
 5818:     }
 5819:     if (!$gottab) {
 5820:         my @domains = &Apache::lonnet::current_machine_domains();
 5821:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5822:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5823:             @lines = <$fh>;
 5824:             close($fh);
 5825:         } else {
 5826:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 5827:             @lines = <$fh>;
 5828:             close($fh);
 5829:         }
 5830:     }
 5831:     return @lines;
 5832: }
 5833: 
 5834: =pod 
 5835: 
 5836: =item scantron_CODElist
 5837: 
 5838:   Returns html drop down of the saved CODE lists from current course,
 5839:   generated from earlier printings.
 5840: 
 5841: =cut
 5842: 
 5843: sub scantron_CODElist {
 5844:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5845:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5846:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5847:     my $namechoice='<option></option>';
 5848:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5849: 	if ($name =~ /^error: 2 /) { next; }
 5850: 	if ($name =~ /^type\0/) { next; }
 5851: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5852:     }
 5853:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5854:     return $namechoice;
 5855: }
 5856: 
 5857: =pod 
 5858: 
 5859: =item scantron_CODEunique
 5860: 
 5861:   Returns the html for "Each CODE to be used once" radio.
 5862: 
 5863: =cut
 5864: 
 5865: sub scantron_CODEunique {
 5866:     my $result='<span class="LC_nobreak">
 5867:                  <label><input type="radio" name="scantron_CODEunique"
 5868:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5869:                 </span>
 5870:                 <span class="LC_nobreak">
 5871:                  <label><input type="radio" name="scantron_CODEunique"
 5872:                         value="no" />'.&mt('No').' </label>
 5873:                 </span>';
 5874:     return $result;
 5875: }
 5876: 
 5877: =pod 
 5878: 
 5879: =item scantron_selectphase
 5880: 
 5881:   Generates the initial screen to start the bubblesheet process.
 5882:   Allows for - starting a grading run.
 5883:              - downloading existing scan data (original, corrected
 5884:                                                 or skipped info)
 5885: 
 5886:              - uploading new scan data
 5887: 
 5888:  Arguments:
 5889:   $r          - The Apache request object
 5890:   $file2grade - name of the file that contain the scanned data to score
 5891: 
 5892: =cut
 5893: 
 5894: sub scantron_selectphase {
 5895:     my ($r,$file2grade,$symb) = @_;
 5896:     if (!$symb) {return '';}
 5897:     my $map_error;
 5898:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 5899:     if ($map_error) {
 5900:         $r->print('<br />'.&navmap_errormsg().'<br />');
 5901:         return;
 5902:     }
 5903:     my $default_form_data=&defaultFormData($symb);
 5904:     my $file_selector=&scantron_uploads($file2grade);
 5905:     my $format_selector=&scantron_scantab();
 5906:     my $CODE_selector=&scantron_CODElist();
 5907:     my $CODE_unique=&scantron_CODEunique();
 5908:     my $result;
 5909: 
 5910:     $ssi_error = 0;
 5911: 
 5912:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5913:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5914: 
 5915: 	# Chunk of form to prompt for a scantron file upload.
 5916: 
 5917:         $r->print('
 5918:     <br />
 5919:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5920:        '.&Apache::loncommon::start_data_table_header_row().'
 5921:             <th>
 5922:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 5923:             </th>
 5924:        '.&Apache::loncommon::end_data_table_header_row().'
 5925:        '.&Apache::loncommon::start_data_table_row().'
 5926:             <td>
 5927: ');
 5928:     my $default_form_data=&defaultFormData($symb);
 5929:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5930:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5931:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 5932:     &js_escape(\$alertmsg);
 5933:     $r->print(&Apache::lonhtmlcommon::scripttag('
 5934:     function checkUpload(formname) {
 5935: 	if (formname.upfile.value == "") {
 5936: 	    alert("'.$alertmsg.'");
 5937: 	    return false;
 5938: 	}
 5939: 	formname.submit();
 5940:     }'));
 5941:     $r->print('
 5942:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5943:                 '.$default_form_data.'
 5944:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5945:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5946:                 <input name="command" value="scantronupload_save" type="hidden" />
 5947:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5948:                 <br />
 5949:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 5950:               </form>
 5951: ');
 5952: 
 5953:         $r->print('
 5954:             </td>
 5955:        '.&Apache::loncommon::end_data_table_row().'
 5956:        '.&Apache::loncommon::end_data_table().'
 5957: ');
 5958:     }
 5959: 
 5960:     # Chunk of form to prompt for a file to grade and how:
 5961: 
 5962:     $result.= '
 5963:     <br />
 5964:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5965:     <input type="hidden" name="command" value="scantron_warning" />
 5966:     '.$default_form_data.'
 5967:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5968:        '.&Apache::loncommon::start_data_table_header_row().'
 5969:             <th colspan="2">
 5970:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5971:             </th>
 5972:        '.&Apache::loncommon::end_data_table_header_row().'
 5973:        '.&Apache::loncommon::start_data_table_row().'
 5974:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5975:        '.&Apache::loncommon::end_data_table_row().'
 5976:        '.&Apache::loncommon::start_data_table_row().'
 5977:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 5978:        '.&Apache::loncommon::end_data_table_row().'
 5979:        '.&Apache::loncommon::start_data_table_row().'
 5980:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 5981:        '.&Apache::loncommon::end_data_table_row().'
 5982:        '.&Apache::loncommon::start_data_table_row().'
 5983:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5984:        '.&Apache::loncommon::end_data_table_row().'
 5985:        '.&Apache::loncommon::start_data_table_row().'
 5986:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5987:        '.&Apache::loncommon::end_data_table_row().'
 5988:        '.&Apache::loncommon::start_data_table_row().'
 5989: 	    <td> '.&mt('Options:').' </td>
 5990:             <td>
 5991: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5992:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5993:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5994: 	    </td>
 5995:        '.&Apache::loncommon::end_data_table_row().'
 5996:        '.&Apache::loncommon::start_data_table_row().'
 5997:             <td colspan="2">
 5998:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 5999:             </td>
 6000:        '.&Apache::loncommon::end_data_table_row().'
 6001:     '.&Apache::loncommon::end_data_table().'
 6002:     </form>
 6003: ';
 6004:    
 6005:     $r->print($result);
 6006: 
 6007: 
 6008: 
 6009:     # Chunk of the form that prompts to view a scoring office file,
 6010:     # corrected file, skipped records in a file.
 6011: 
 6012:     $r->print('
 6013:    <br />
 6014:    <form action="/adm/grades" name="scantron_download">
 6015:      '.$default_form_data.'
 6016:      <input type="hidden" name="command" value="scantron_download" />
 6017:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 6018:        '.&Apache::loncommon::start_data_table_header_row().'
 6019:               <th>
 6020:                 &nbsp;'.&mt('Download a scoring office file').'
 6021:               </th>
 6022:        '.&Apache::loncommon::end_data_table_header_row().'
 6023:        '.&Apache::loncommon::start_data_table_row().'
 6024:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 6025:                 <br />
 6026:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 6027:        '.&Apache::loncommon::end_data_table_row().'
 6028:      '.&Apache::loncommon::end_data_table().'
 6029:    </form>
 6030:    <br />
 6031: ');
 6032: 
 6033:     &Apache::lonpickcode::code_list($r,2);
 6034: 
 6035:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
 6036:              $default_form_data."\n".
 6037:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 6038:              &Apache::loncommon::start_data_table_header_row()."\n".
 6039:              '<th colspan="2">
 6040:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 6041:              '</th>'."\n".
 6042:               &Apache::loncommon::end_data_table_header_row()."\n".
 6043:               &Apache::loncommon::start_data_table_row()."\n".
 6044:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 6045:               '<td> '.$sequence_selector.' </td>'.
 6046:               &Apache::loncommon::end_data_table_row()."\n".
 6047:               &Apache::loncommon::start_data_table_row()."\n".
 6048:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 6049:               '<td> '.$file_selector.' </td>'."\n".
 6050:               &Apache::loncommon::end_data_table_row()."\n".
 6051:               &Apache::loncommon::start_data_table_row()."\n".
 6052:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 6053:               '<td> '.$format_selector.' </td>'."\n".
 6054:               &Apache::loncommon::end_data_table_row()."\n".
 6055:               &Apache::loncommon::start_data_table_row()."\n".
 6056:               '<td> '.&mt('Options').' </td>'."\n".
 6057:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 6058:               &Apache::loncommon::end_data_table_row()."\n".
 6059:               &Apache::loncommon::start_data_table_row()."\n".
 6060:               '<td colspan="2">'."\n".
 6061:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 6062:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 6063:               '</td>'."\n".
 6064:               &Apache::loncommon::end_data_table_row()."\n".
 6065:               &Apache::loncommon::end_data_table()."\n".
 6066:               '</form><br />');
 6067:     return;
 6068: }
 6069: 
 6070: =pod
 6071: 
 6072: =item get_scantron_config
 6073: 
 6074:    Parse and return the bubblesheet configuration line selected as a
 6075:    hash of configuration file fields.
 6076: 
 6077:  Arguments:
 6078:     which - the name of the configuration to parse from the file.
 6079: 
 6080: 
 6081:  Returns:
 6082:             If the named configuration is not in the file, an empty
 6083:             hash is returned.
 6084:     a hash with the fields
 6085:       name         - internal name for the this configuration setup
 6086:       description  - text to display to operator that describes this config
 6087:       CODElocation - if 0 or the string 'none'
 6088:                           - no CODE exists for this config
 6089:                      if -1 || the string 'letter'
 6090:                           - a CODE exists for this config and is
 6091:                             a string of letters
 6092:                      Unsupported value (but planned for future support)
 6093:                           if a positive integer
 6094:                                - The CODE exists as the first n items from
 6095:                                  the question section of the form
 6096:                           if the string 'number'
 6097:                                - The CODE exists for this config and is
 6098:                                  a string of numbers
 6099:       CODEstart   - (only matter if a CODE exists) column in the line where
 6100:                      the CODE starts
 6101:       CODElength  - length of the CODE
 6102:       IDstart     - column where the student/employee ID starts
 6103:       IDlength    - length of the student/employee ID info
 6104:       Qstart      - column where the information from the bubbled
 6105:                     'questions' start
 6106:       Qlength     - number of columns comprising a single bubble line from
 6107:                     the sheet. (usually either 1 or 10)
 6108:       Qon         - either a single character representing the character used
 6109:                     to signal a bubble was chosen in the positional setup, or
 6110:                     the string 'letter' if the letter of the chosen bubble is
 6111:                     in the final, or 'number' if a number representing the
 6112:                     chosen bubble is in the file (1->A 0->J)
 6113:       Qoff        - the character used to represent that a bubble was
 6114:                     left blank
 6115:       PaperID     - if the scanning process generates a unique number for each
 6116:                     sheet scanned the column that this ID number starts in
 6117:       PaperIDlength - number of columns that comprise the unique ID number
 6118:                       for the sheet of paper
 6119:       FirstName   - column that the first name starts in
 6120:       FirstNameLength - number of columns that the first name spans
 6121:  
 6122:       LastName    - column that the last name starts in
 6123:       LastNameLength - number of columns that the last name spans
 6124:       BubblesPerRow - number of bubbles available in each row used to 
 6125:                       bubble an answer. (If not specified, 10 assumed).
 6126: 
 6127: =cut
 6128: 
 6129: sub get_scantron_config {
 6130:     my ($which) = @_;
 6131:     my @lines = &get_scantronformat_file();
 6132:     my %config;
 6133:     #FIXME probably should move to XML it has already gotten a bit much now
 6134:     foreach my $line (@lines) {
 6135: 	my ($name,$descrip)=split(/:/,$line);
 6136: 	if ($name ne $which ) { next; }
 6137: 	chomp($line);
 6138: 	my @config=split(/:/,$line);
 6139: 	$config{'name'}=$config[0];
 6140: 	$config{'description'}=$config[1];
 6141: 	$config{'CODElocation'}=$config[2];
 6142: 	$config{'CODEstart'}=$config[3];
 6143: 	$config{'CODElength'}=$config[4];
 6144: 	$config{'IDstart'}=$config[5];
 6145: 	$config{'IDlength'}=$config[6];
 6146: 	$config{'Qstart'}=$config[7];
 6147:  	$config{'Qlength'}=$config[8];
 6148: 	$config{'Qoff'}=$config[9];
 6149: 	$config{'Qon'}=$config[10];
 6150: 	$config{'PaperID'}=$config[11];
 6151: 	$config{'PaperIDlength'}=$config[12];
 6152: 	$config{'FirstName'}=$config[13];
 6153: 	$config{'FirstNamelength'}=$config[14];
 6154: 	$config{'LastName'}=$config[15];
 6155: 	$config{'LastNamelength'}=$config[16];
 6156:         $config{'BubblesPerRow'}=$config[17];
 6157: 	last;
 6158:     }
 6159:     return %config;
 6160: }
 6161: 
 6162: =pod 
 6163: 
 6164: =item username_to_idmap
 6165: 
 6166:     creates a hash keyed by student/employee ID with values of the corresponding
 6167:     student username:domain. If a single ID occurs for more than one student,
 6168:     the status of the student is checked, and if Active, the value in the hash
 6169:     will be set to the Active student.
 6170: 
 6171:   Arguments:
 6172: 
 6173:     $classlist - reference to the class list hash. This is a hash
 6174:                  keyed by student name:domain  whose elements are references
 6175:                  to arrays containing various chunks of information
 6176:                  about the student. (See loncoursedata for more info).
 6177: 
 6178:   Returns
 6179:     %idmap - the constructed hash
 6180: 
 6181: =cut
 6182: 
 6183: sub username_to_idmap {
 6184:     my ($classlist)= @_;
 6185:     my %idmap;
 6186:     foreach my $student (keys(%$classlist)) {
 6187:         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
 6188:         unless ($id eq '') {
 6189:             if (!exists($idmap{$id})) {
 6190:                 $idmap{$id} = $student;
 6191:             } else {
 6192:                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
 6193:                 if ($status eq 'Active') {
 6194:                     $idmap{$id} = $student;
 6195:                 }
 6196:             }
 6197:         }
 6198:     }
 6199:     return %idmap;
 6200: }
 6201: 
 6202: =pod
 6203: 
 6204: =item scantron_fixup_scanline
 6205: 
 6206:    Process a requested correction to a scanline.
 6207: 
 6208:   Arguments:
 6209:     $scantron_config   - hash from &get_scantron_config()
 6210:     $scan_data         - hash of correction information 
 6211:                           (see &scantron_getfile())
 6212:     $line              - existing scanline
 6213:     $whichline         - line number of the passed in scanline
 6214:     $field             - type of change to process 
 6215:                          (either 
 6216:                           'ID'     -> correct the student/employee ID
 6217:                           'CODE'   -> correct the CODE
 6218:                           'answer' -> fixup the submitted answers)
 6219:     
 6220:    $args               - hash of additional info,
 6221:                           - 'ID' 
 6222:                                'newid' -> studentID to use in replacement
 6223:                                           of existing one
 6224:                           - 'CODE' 
 6225:                                'CODE_ignore_dup' - set to true if duplicates
 6226:                                                    should be ignored.
 6227: 	                       'CODE' - is new code or 'use_unfound'
 6228:                                         if the existing unfound code should
 6229:                                         be used as is
 6230:                           - 'answer'
 6231:                                'response' - new answer or 'none' if blank
 6232:                                'question' - the bubble line to change
 6233:                                'questionnum' - the question identifier,
 6234:                                                may include subquestion. 
 6235: 
 6236:   Returns:
 6237:     $line - the modified scanline
 6238: 
 6239:   Side effects: 
 6240:     $scan_data - may be updated
 6241: 
 6242: =cut
 6243: 
 6244: 
 6245: sub scantron_fixup_scanline {
 6246:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 6247:     if ($field eq 'ID') {
 6248: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 6249: 	    return ($line,1,'New value too large');
 6250: 	}
 6251: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 6252: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 6253: 				     $args->{'newid'});
 6254: 	}
 6255: 	substr($line,$$scantron_config{'IDstart'}-1,
 6256: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 6257: 	if ($args->{'newid'}=~/^\s*$/) {
 6258: 	    &scan_data($scan_data,"$whichline.user",
 6259: 		       $args->{'username'}.':'.$args->{'domain'});
 6260: 	}
 6261:     } elsif ($field eq 'CODE') {
 6262: 	if ($args->{'CODE_ignore_dup'}) {
 6263: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 6264: 	}
 6265: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 6266: 	if ($args->{'CODE'} ne 'use_unfound') {
 6267: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 6268: 		return ($line,1,'New CODE value too large');
 6269: 	    }
 6270: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 6271: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 6272: 	    }
 6273: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 6274: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 6275: 	}
 6276:     } elsif ($field eq 'answer') {
 6277: 	my $length=$scantron_config->{'Qlength'};
 6278: 	my $off=$scantron_config->{'Qoff'};
 6279: 	my $on=$scantron_config->{'Qon'};
 6280: 	my $answer=${off}x$length;
 6281: 	if ($args->{'response'} eq 'none') {
 6282: 	    &scan_data($scan_data,
 6283: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 6284: 	} else {
 6285: 	    if ($on eq 'letter') {
 6286: 		my @alphabet=('A'..'Z');
 6287: 		$answer=$alphabet[$args->{'response'}];
 6288: 	    } elsif ($on eq 'number') {
 6289: 		$answer=$args->{'response'}+1;
 6290: 		if ($answer == 10) { $answer = '0'; }
 6291: 	    } else {
 6292: 		substr($answer,$args->{'response'},1)=$on;
 6293: 	    }
 6294: 	    &scan_data($scan_data,
 6295: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 6296: 	}
 6297: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 6298: 	substr($line,$where-1,$length)=$answer;
 6299:     }
 6300:     return $line;
 6301: }
 6302: 
 6303: =pod
 6304: 
 6305: =item scan_data
 6306: 
 6307:     Edit or look up  an item in the scan_data hash.
 6308: 
 6309:   Arguments:
 6310:     $scan_data  - The hash (see scantron_getfile)
 6311:     $key        - shorthand of the key to edit (actual key is
 6312:                   scantronfilename_key).
 6313:     $data        - New value of the hash entry.
 6314:     $delete      - If true, the entry is removed from the hash.
 6315: 
 6316:   Returns:
 6317:     The new value of the hash table field (undefined if deleted).
 6318: 
 6319: =cut
 6320: 
 6321: 
 6322: sub scan_data {
 6323:     my ($scan_data,$key,$value,$delete)=@_;
 6324:     my $filename=$env{'form.scantron_selectfile'};
 6325:     if (defined($value)) {
 6326: 	$scan_data->{$filename.'_'.$key} = $value;
 6327:     }
 6328:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 6329:     return $scan_data->{$filename.'_'.$key};
 6330: }
 6331: 
 6332: # ----- These first few routines are general use routines.----
 6333: 
 6334: # Return the number of occurences of a pattern in a string.
 6335: 
 6336: sub occurence_count {
 6337:     my ($string, $pattern) = @_;
 6338: 
 6339:     my @matches = ($string =~ /$pattern/g);
 6340: 
 6341:     return scalar(@matches);
 6342: }
 6343: 
 6344: 
 6345: # Take a string known to have digits and convert all the
 6346: # digits into letters in the range J,A..I.
 6347: 
 6348: sub digits_to_letters {
 6349:     my ($input) = @_;
 6350: 
 6351:     my @alphabet = ('J', 'A'..'I');
 6352: 
 6353:     my @input    = split(//, $input);
 6354:     my $output ='';
 6355:     for (my $i = 0; $i < scalar(@input); $i++) {
 6356: 	if ($input[$i] =~ /\d/) {
 6357: 	    $output .= $alphabet[$input[$i]];
 6358: 	} else {
 6359: 	    $output .= $input[$i];
 6360: 	}
 6361:     }
 6362:     return $output;
 6363: }
 6364: 
 6365: =pod 
 6366: 
 6367: =item scantron_parse_scanline
 6368: 
 6369:   Decodes a scanline from the selected bubblesheet file
 6370: 
 6371:  Arguments:
 6372:     line             - The text of the bubblesheet file line to process
 6373:     whichline        - Line number
 6374:     scantron_config  - Hash describing the format of the bubblesheet lines.
 6375:     scan_data        - Hash of extra information about the scanline
 6376:                        (see scantron_getfile for more information)
 6377:     just_header      - True if should not process question answers but only
 6378:                        the stuff to the left of the answers.
 6379:     randomorder      - True if randomorder in use
 6380:     randompick       - True if randompick in use
 6381:     sequence         - Exam folder URL
 6382:     master_seq       - Ref to array containing symbs in exam folder
 6383:     symb_to_resource - Ref to hash of symbs for resources in exam folder
 6384:                        (corresponding values are resource objects)
 6385:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
 6386:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
 6387:                        are refs to an array of resource objects, ordered
 6388:                        according to order used for CODE, when randomorder
 6389:                        and or randompick are in use.
 6390:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
 6391:                        for current line to question number used for same question
 6392:                         in "Master Sequence" (as seen by Course Coordinator).
 6393:     startline        - Ref to hash where key is question number (0 is first)
 6394:                        and value is number of first bubble line for current 
 6395:                        student or code-based randompick and/or randomorder.
 6396:     totalref         - Ref of scalar used to score total number of bubble
 6397:                        lines needed for responses in a scan line (used when
 6398:                        randompick in use. 
 6399:     
 6400:  Returns:
 6401:    Hash containing the result of parsing the scanline
 6402: 
 6403:    Keys are all proceeded by the string 'scantron.'
 6404: 
 6405:        CODE    - the CODE in use for this scanline
 6406:        useCODE - 1 if the CODE is invalid but it usage has been forced
 6407:                  by the operator
 6408:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 6409:                             CODEs were selected, but the usage has been
 6410:                             forced by the operator
 6411:        ID  - student/employee ID
 6412:        PaperID - if used, the ID number printed on the sheet when the 
 6413:                  paper was scanned
 6414:        FirstName - first name from the sheet
 6415:        LastName  - last name from the sheet
 6416: 
 6417:      if just_header was not true these key may also exist
 6418: 
 6419:        missingerror - a list of bubble ranges that are considered to be answers
 6420:                       to a single question that don't have any bubbles filled in.
 6421:                       Of the form questionnumber:firstbubblenumber:count.
 6422:        doubleerror  - a list of bubble ranges that are considered to be answers
 6423:                       to a single question that have more than one bubble filled in.
 6424:                       Of the form questionnumber::firstbubblenumber:count
 6425:    
 6426:                 In the above, count is the number of bubble responses in the
 6427:                 input line needed to represent the possible answers to the question.
 6428:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 6429:                 per line would have count = 2.
 6430: 
 6431:        maxquest     - the number of the last bubble line that was parsed
 6432: 
 6433:        (<number> starts at 1)
 6434:        <number>.answer - zero or more letters representing the selected
 6435:                          letters from the scanline for the bubble line 
 6436:                          <number>.
 6437:                          if blank there was either no bubble or there where
 6438:                          multiple bubbles, (consult the keys missingerror and
 6439:                          doubleerror if this is an error condition)
 6440: 
 6441: =cut
 6442: 
 6443: sub scantron_parse_scanline {
 6444:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
 6445:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
 6446:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
 6447: 
 6448:     my %record;
 6449:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
 6450:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 6451: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 6452: 	if ($$scantron_config{'CODElocation'} < 0 ||
 6453: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 6454: 	    $$scantron_config{'CODElocation'} eq 'number') {
 6455: 	    $record{'scantron.CODE'}=substr($data,
 6456: 					    $$scantron_config{'CODEstart'}-1,
 6457: 					    $$scantron_config{'CODElength'});
 6458: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 6459: 		$record{'scantron.useCODE'}=1;
 6460: 	    }
 6461: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 6462: 		$record{'scantron.CODE_ignore_dup'}=1;
 6463: 	    }
 6464: 	} else {
 6465: 	    #FIXME interpret first N questions
 6466: 	}
 6467:     }
 6468:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 6469: 				  $$scantron_config{'IDlength'});
 6470:     $record{'scantron.PaperID'}=
 6471: 	substr($data,$$scantron_config{'PaperID'}-1,
 6472: 	       $$scantron_config{'PaperIDlength'});
 6473:     $record{'scantron.FirstName'}=
 6474: 	substr($data,$$scantron_config{'FirstName'}-1,
 6475: 	       $$scantron_config{'FirstNamelength'});
 6476:     $record{'scantron.LastName'}=
 6477: 	substr($data,$$scantron_config{'LastName'}-1,
 6478: 	       $$scantron_config{'LastNamelength'});
 6479:     if ($just_header) { return \%record; }
 6480: 
 6481:     my @alphabet=('A'..'Z');
 6482:     my $questnum=0;
 6483:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 6484: 
 6485:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 6486:     if ($randompick || $randomorder) {
 6487:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
 6488:                                          $master_seq,$symb_to_resource,
 6489:                                          $partids_by_symb,$orderedforcode,
 6490:                                          $respnumlookup,$startline);
 6491:         if ($total) {
 6492:             $lastpos = $total*$$scantron_config{'Qlength'}; 
 6493:         }
 6494:         if (ref($totalref)) {
 6495:             $$totalref = $total;
 6496:         }
 6497:     }
 6498:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 6499:     chomp($questions);		# Get rid of any trailing \n.
 6500:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 6501:     while (length($questions)) {
 6502:         my $answers_needed;
 6503:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6504:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
 6505:         } else {
 6506: 	    $answers_needed = $bubble_lines_per_response{$questnum};
 6507:         }
 6508:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 6509:                              || 1;
 6510:         $questnum++;
 6511:         my $quest_id = $questnum;
 6512:         my $currentquest = substr($questions,0,$answer_length);
 6513:         $questions       = substr($questions,$answer_length);
 6514:         if (length($currentquest) < $answer_length) { next; }
 6515: 
 6516:         my $subdivided;
 6517:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6518:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
 6519:         } else {
 6520:             $subdivided = $subdivided_bubble_lines{$questnum-1};
 6521:         }
 6522:         if ($subdivided =~ /,/) {
 6523:             my $subquestnum = 1;
 6524:             my $subquestions = $currentquest;
 6525:             my @subanswers_needed = split(/,/,$subdivided);
 6526:             foreach my $subans (@subanswers_needed) {
 6527:                 my $subans_length =
 6528:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 6529:                 my $currsubquest = substr($subquestions,0,$subans_length);
 6530:                 $subquestions   = substr($subquestions,$subans_length);
 6531:                 $quest_id = "$questnum.$subquestnum";
 6532:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 6533:                     ($$scantron_config{'Qon'} eq 'number')) {
 6534:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 6535:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6536:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6537:                         $randomorder,$randompick,$respnumlookup);
 6538:                 } else {
 6539:                     $ansnum = &scantron_validator_positional($ansnum,
 6540:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6541:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6542:                         $randomorder,$randompick,$respnumlookup);
 6543:                 }
 6544:                 $subquestnum ++;
 6545:             }
 6546:         } else {
 6547:             if (($$scantron_config{'Qon'} eq 'letter') ||
 6548:                 ($$scantron_config{'Qon'} eq 'number')) {
 6549:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 6550:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6551:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6552:                     $randomorder,$randompick,$respnumlookup);
 6553:             } else {
 6554:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 6555:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6556:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6557:                     $randomorder,$randompick,$respnumlookup);
 6558:             }
 6559:         }
 6560:     }
 6561:     $record{'scantron.maxquest'}=$questnum;
 6562:     return \%record;
 6563: }
 6564: 
 6565: sub get_master_seq {
 6566:     my ($resources,$master_seq,$symb_to_resource) = @_;
 6567:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') && 
 6568:                    (ref($symb_to_resource) eq 'HASH'));
 6569:     my $resource_error;
 6570:     foreach my $resource (@{$resources}) {
 6571:         my $ressymb;
 6572:         if (ref($resource)) {
 6573:             $ressymb = $resource->symb();
 6574:             push(@{$master_seq},$ressymb);
 6575:             $symb_to_resource->{$ressymb} = $resource;
 6576:         } else {
 6577:             $resource_error = 1;
 6578:             last;
 6579:         }
 6580:     }
 6581:     return $resource_error;
 6582: }
 6583: 
 6584: sub get_respnum_lookups {
 6585:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
 6586:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
 6587:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
 6588:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
 6589:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
 6590:                    (ref($startline) eq 'HASH'));
 6591:     my ($user,$scancode);
 6592:     if ((exists($record->{'scantron.CODE'})) &&
 6593:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
 6594:         $scancode = $record->{'scantron.CODE'};
 6595:     } else {
 6596:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
 6597:     }
 6598:     my @mapresources =
 6599:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
 6600:                      $orderedforcode);
 6601:     my $total = 0;
 6602:     my $count = 0;
 6603:     foreach my $resource (@mapresources) {
 6604:         my $id = $resource->id();
 6605:         my $symb = $resource->symb();
 6606:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
 6607:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
 6608:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
 6609:                 if ($respnum ne '') {
 6610:                     $respnumlookup->{$count} = $respnum;
 6611:                     $startline->{$count} = $total;
 6612:                     $total += $bubble_lines_per_response{$respnum};
 6613:                     $count ++;
 6614:                 }
 6615:             }
 6616:         }
 6617:     }
 6618:     return $total;
 6619: }
 6620: 
 6621: sub scantron_validator_lettnum {
 6622:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 6623:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
 6624:         $randompick,$respnumlookup) = @_;
 6625: 
 6626:     # Qon 'letter' implies for each slot in currquest we have:
 6627:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 6628:     #    about anything else (esp. a value of Qoff) for missing
 6629:     #    bubbles.
 6630:     #
 6631:     # Qon 'number' implies each slot gives a digit that indexes the
 6632:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 6633:     #    and * or ? for double bubbles on a single line.
 6634:     #
 6635: 
 6636:     my $matchon;
 6637:     if ($$scantron_config{'Qon'} eq 'letter') {
 6638:         $matchon = '[A-Z]';
 6639:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 6640:         $matchon = '\d';
 6641:     }
 6642:     my $occurrences = 0;
 6643:     my $responsenum = $questnum-1;
 6644:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6645:        $responsenum = $respnumlookup->{$questnum-1} 
 6646:     }
 6647:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6648:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6649:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6650:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6651:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6652:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6653:         my @singlelines = split('',$currquest);
 6654:         foreach my $entry (@singlelines) {
 6655:             $occurrences = &occurence_count($entry,$matchon);
 6656:             if ($occurrences > 1) {
 6657:                 last;
 6658:             }
 6659:         }
 6660:     } else {
 6661:         $occurrences = &occurence_count($currquest,$matchon); 
 6662:     }
 6663:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 6664:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6665:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6666:             my $bubble = substr($currquest,$ans,1);
 6667:             if ($bubble =~ /$matchon/ ) {
 6668:                 if ($$scantron_config{'Qon'} eq 'number') {
 6669:                     if ($bubble == 0) {
 6670:                         $bubble = 10; 
 6671:                     }
 6672:                     $record->{"scantron.$ansnum.answer"} = 
 6673:                         $alphabet->[$bubble-1];
 6674:                 } else {
 6675:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 6676:                 }
 6677:             } else {
 6678:                 $record->{"scantron.$ansnum.answer"}='';
 6679:             }
 6680:             $ansnum++;
 6681:         }
 6682:     } elsif (!defined($currquest)
 6683:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 6684:             || (&occurence_count($currquest,$matchon) == 0)) {
 6685:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6686:             $record->{"scantron.$ansnum.answer"}='';
 6687:             $ansnum++;
 6688:         }
 6689:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6690:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 6691:         }
 6692:     } else {
 6693:         if ($$scantron_config{'Qon'} eq 'number') {
 6694:             $currquest = &digits_to_letters($currquest);            
 6695:         }
 6696:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6697:             my $bubble = substr($currquest,$ans,1);
 6698:             $record->{"scantron.$ansnum.answer"} = $bubble;
 6699:             $ansnum++;
 6700:         }
 6701:     }
 6702:     return $ansnum;
 6703: }
 6704: 
 6705: sub scantron_validator_positional {
 6706:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 6707:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
 6708:         $randomorder,$randompick,$respnumlookup) = @_;
 6709: 
 6710:     # Otherwise there's a positional notation;
 6711:     # each bubble line requires Qlength items, and there are filled in
 6712:     # bubbles for each case where there 'Qon' characters.
 6713:     #
 6714: 
 6715:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 6716: 
 6717:     # If the split only gives us one element.. the full length of the
 6718:     # answer string, no bubbles are filled in:
 6719: 
 6720:     if ($answers_needed eq '') {
 6721:         return;
 6722:     }
 6723: 
 6724:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 6725:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6726:             $record->{"scantron.$ansnum.answer"}='';
 6727:             $ansnum++;
 6728:         }
 6729:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6730:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 6731:         }
 6732:     } elsif (scalar(@array) == 2) {
 6733:         my $location = length($array[0]);
 6734:         my $line_num = int($location / $$scantron_config{'Qlength'});
 6735:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 6736:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6737:             if ($ans eq $line_num) {
 6738:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 6739:             } else {
 6740:                 $record->{"scantron.$ansnum.answer"} = ' ';
 6741:             }
 6742:             $ansnum++;
 6743:          }
 6744:     } else {
 6745:         #  If there's more than one instance of a bubble character
 6746:         #  That's a double bubble; with positional notation we can
 6747:         #  record all the bubbles filled in as well as the
 6748:         #  fact this response consists of multiple bubbles.
 6749:         #
 6750:         my $responsenum = $questnum-1;
 6751:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6752:             $responsenum = $respnumlookup->{$questnum-1}
 6753:         }
 6754:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6755:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6756:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6757:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6758:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6759:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6760:             my $doubleerror = 0;
 6761:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 6762:                    (!$doubleerror)) {
 6763:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 6764:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 6765:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 6766:                if (length(@currarray) > 2) {
 6767:                    $doubleerror = 1;
 6768:                } 
 6769:             }
 6770:             if ($doubleerror) {
 6771:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6772:             }
 6773:         } else {
 6774:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6775:         }
 6776:         my $item = $ansnum;
 6777:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6778:             $record->{"scantron.$item.answer"} = '';
 6779:             $item ++;
 6780:         }
 6781: 
 6782:         my @ans=@array;
 6783:         my $i=0;
 6784:         my $increment = 0;
 6785:         while ($#ans) {
 6786:             $i+=length($ans[0]) + $increment;
 6787:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 6788:             my $bubble = $i%$$scantron_config{'Qlength'};
 6789:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 6790:             shift(@ans);
 6791:             $increment = 1;
 6792:         }
 6793:         $ansnum += $answers_needed;
 6794:     }
 6795:     return $ansnum;
 6796: }
 6797: 
 6798: =pod
 6799: 
 6800: =item scantron_add_delay
 6801: 
 6802:    Adds an error message that occurred during the grading phase to a
 6803:    queue of messages to be shown after grading pass is complete
 6804: 
 6805:  Arguments:
 6806:    $delayqueue  - arrary ref of hash ref of error messages
 6807:    $scanline    - the scanline that caused the error
 6808:    $errormesage - the error message
 6809:    $errorcode   - a numeric code for the error
 6810: 
 6811:  Side Effects:
 6812:    updates the $delayqueue to have a new hash ref of the error
 6813: 
 6814: =cut
 6815: 
 6816: sub scantron_add_delay {
 6817:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 6818:     push(@$delayqueue,
 6819: 	 {'line' => $scanline, 'emsg' => $errormessage,
 6820: 	  'ecode' => $errorcode }
 6821: 	 );
 6822: }
 6823: 
 6824: =pod
 6825: 
 6826: =item scantron_find_student
 6827: 
 6828:    Finds the username for the current scanline
 6829: 
 6830:   Arguments:
 6831:    $scantron_record - hash result from scantron_parse_scanline
 6832:    $scan_data       - hash of correction information 
 6833:                       (see &scantron_getfile() form more information)
 6834:    $idmap           - hash from &username_to_idmap()
 6835:    $line            - number of current scanline
 6836:  
 6837:   Returns:
 6838:    Either 'username:domain' or undef if unknown
 6839: 
 6840: =cut
 6841: 
 6842: sub scantron_find_student {
 6843:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 6844:     my $scanID=$$scantron_record{'scantron.ID'};
 6845:     if ($scanID =~ /^\s*$/) {
 6846:  	return &scan_data($scan_data,"$line.user");
 6847:     }
 6848:     foreach my $id (keys(%$idmap)) {
 6849:  	if (lc($id) eq lc($scanID)) {
 6850:  	    return $$idmap{$id};
 6851:  	}
 6852:     }
 6853:     return undef;
 6854: }
 6855: 
 6856: =pod
 6857: 
 6858: =item scantron_filter
 6859: 
 6860:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 6861:    hidden resources was selected
 6862: 
 6863: =cut
 6864: 
 6865: sub scantron_filter {
 6866:     my ($curres)=@_;
 6867: 
 6868:     if (ref($curres) && $curres->is_problem()) {
 6869: 	# if the user has asked to not have either hidden
 6870: 	# or 'randomout' controlled resources to be graded
 6871: 	# don't include them
 6872: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6873: 	    && $curres->randomout) {
 6874: 	    return 0;
 6875: 	}
 6876: 	return 1;
 6877:     }
 6878:     return 0;
 6879: }
 6880: 
 6881: =pod
 6882: 
 6883: =item scantron_process_corrections
 6884: 
 6885:    Gets correction information out of submitted form data and corrects
 6886:    the scanline
 6887: 
 6888: =cut
 6889: 
 6890: sub scantron_process_corrections {
 6891:     my ($r) = @_;
 6892:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6893:     my ($scanlines,$scan_data)=&scantron_getfile();
 6894:     my $classlist=&Apache::loncoursedata::get_classlist();
 6895:     my $which=$env{'form.scantron_line'};
 6896:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 6897:     my ($skip,$err,$errmsg);
 6898:     if ($env{'form.scantron_skip_record'}) {
 6899: 	$skip=1;
 6900:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 6901: 	my $newstudent=$env{'form.scantron_username'}.':'.
 6902: 	    $env{'form.scantron_domain'};
 6903: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 6904: 	($line,$err,$errmsg)=
 6905: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6906: 				     'ID',{'newid'=>$newid,
 6907: 				    'username'=>$env{'form.scantron_username'},
 6908: 				    'domain'=>$env{'form.scantron_domain'}});
 6909:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 6910: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 6911: 	my $newCODE;
 6912: 	my %args;
 6913: 	if      ($resolution eq 'use_unfound') {
 6914: 	    $newCODE='use_unfound';
 6915: 	} elsif ($resolution eq 'use_found') {
 6916: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6917: 	} elsif ($resolution eq 'use_typed') {
 6918: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6919: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6920: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6921: 	}
 6922: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6923: 	    $args{'CODE_ignore_dup'}=1;
 6924: 	}
 6925: 	$args{'CODE'}=$newCODE;
 6926: 	($line,$err,$errmsg)=
 6927: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6928: 				     'CODE',\%args);
 6929:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6930: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6931: 	    ($line,$err,$errmsg)=
 6932: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6933: 					 $which,'answer',
 6934: 					 { 'question'=>$question,
 6935: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6936:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6937: 	    if ($err) { last; }
 6938: 	}
 6939:     }
 6940:     if ($err) {
 6941:         $r->print(
 6942:             '<p class="LC_error">'
 6943:            .&mt('Unable to accept last correction, an error occurred: [_1]',
 6944:                 $errmsg)
 6945:            .'</p>');
 6946:     } else {
 6947: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 6948: 	&scantron_putfile($scanlines,$scan_data);
 6949:     }
 6950: }
 6951: 
 6952: =pod
 6953: 
 6954: =item reset_skipping_status
 6955: 
 6956:    Forgets the current set of remember skipped scanlines (and thus
 6957:    reverts back to considering all lines in the
 6958:    scantron_skipped_<filename> file)
 6959: 
 6960: =cut
 6961: 
 6962: sub reset_skipping_status {
 6963:     my ($scanlines,$scan_data)=&scantron_getfile();
 6964:     &scan_data($scan_data,'remember_skipping',undef,1);
 6965:     &scantron_putfile(undef,$scan_data);
 6966: }
 6967: 
 6968: =pod
 6969: 
 6970: =item start_skipping
 6971: 
 6972:    Marks a scanline to be skipped. 
 6973: 
 6974: =cut
 6975: 
 6976: sub start_skipping {
 6977:     my ($scan_data,$i)=@_;
 6978:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6979:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6980: 	$remembered{$i}=2;
 6981:     } else {
 6982: 	$remembered{$i}=1;
 6983:     }
 6984:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6985: }
 6986: 
 6987: =pod
 6988: 
 6989: =item should_be_skipped
 6990: 
 6991:    Checks whether a scanline should be skipped.
 6992: 
 6993: =cut
 6994: 
 6995: sub should_be_skipped {
 6996:     my ($scanlines,$scan_data,$i)=@_;
 6997:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6998: 	# not redoing old skips
 6999: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 7000: 	return 0;
 7001:     }
 7002:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 7003: 
 7004:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 7005: 	return 0;
 7006:     }
 7007:     return 1;
 7008: }
 7009: 
 7010: =pod
 7011: 
 7012: =item remember_current_skipped
 7013: 
 7014:    Discovers what scanlines are in the scantron_skipped_<filename>
 7015:    file and remembers them into scan_data for later use.
 7016: 
 7017: =cut
 7018: 
 7019: sub remember_current_skipped {
 7020:     my ($scanlines,$scan_data)=&scantron_getfile();
 7021:     my %to_remember;
 7022:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7023: 	if ($scanlines->{'skipped'}[$i]) {
 7024: 	    $to_remember{$i}=1;
 7025: 	}
 7026:     }
 7027: 
 7028:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 7029:     &scantron_putfile(undef,$scan_data);
 7030: }
 7031: 
 7032: =pod
 7033: 
 7034: =item check_for_error
 7035: 
 7036:     Checks if there was an error when attempting to remove a specific
 7037:     scantron_.. bubblesheet data file. Prints out an error if
 7038:     something went wrong.
 7039: 
 7040: =cut
 7041: 
 7042: sub check_for_error {
 7043:     my ($r,$result)=@_;
 7044:     if ($result ne 'ok' && $result ne 'not_found' ) {
 7045: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 7046:     }
 7047: }
 7048: 
 7049: =pod
 7050: 
 7051: =item scantron_warning_screen
 7052: 
 7053:    Interstitial screen to make sure the operator has selected the
 7054:    correct options before we start the validation phase.
 7055: 
 7056: =cut
 7057: 
 7058: sub scantron_warning_screen {
 7059:     my ($button_text,$symb)=@_;
 7060:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 7061:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7062:     my $CODElist;
 7063:     if ($scantron_config{'CODElocation'} &&
 7064: 	$scantron_config{'CODEstart'} &&
 7065: 	$scantron_config{'CODElength'}) {
 7066: 	$CODElist=$env{'form.scantron_CODElist'};
 7067: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
 7068: 	$CODElist=
 7069: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 7070: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 7071:     }
 7072:     my $lastbubblepoints;
 7073:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 7074:         $lastbubblepoints =
 7075:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
 7076:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
 7077:     }
 7078:     return ('
 7079: <p>
 7080: <span class="LC_warning">
 7081: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
 7082: </p>
 7083: <table>
 7084: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 7085: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 7086: '.$CODElist.$lastbubblepoints.'
 7087: </table>
 7088: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
 7089: '.&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>
 7090: 
 7091: <br />
 7092: ');
 7093: }
 7094: 
 7095: =pod
 7096: 
 7097: =item scantron_do_warning
 7098: 
 7099:    Check if the operator has picked something for all required
 7100:    fields. Error out if something is missing.
 7101: 
 7102: =cut
 7103: 
 7104: sub scantron_do_warning {
 7105:     my ($r,$symb)=@_;
 7106:     if (!$symb) {return '';}
 7107:     my $default_form_data=&defaultFormData($symb);
 7108:     $r->print(&scantron_form_start().$default_form_data);
 7109:     if ( $env{'form.selectpage'} eq '' ||
 7110: 	 $env{'form.scantron_selectfile'} eq '' ||
 7111: 	 $env{'form.scantron_format'} eq '' ) {
 7112: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
 7113: 	if ( $env{'form.selectpage'} eq '') {
 7114: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 7115: 	} 
 7116: 	if ( $env{'form.scantron_selectfile'} eq '') {
 7117: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
 7118: 	} 
 7119: 	if ( $env{'form.scantron_format'} eq '') {
 7120: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
 7121: 	} 
 7122:     } else {
 7123: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
 7124:         my $bubbledbyhand=&hand_bubble_option();
 7125: 	$r->print('
 7126: '.$warning.$bubbledbyhand.'
 7127: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 7128: <input type="hidden" name="command" value="scantron_validate" />
 7129: ');
 7130:     }
 7131:     $r->print("</form><br />");
 7132:     return '';
 7133: }
 7134: 
 7135: =pod
 7136: 
 7137: =item scantron_form_start
 7138: 
 7139:     html hidden input for remembering all selected grading options
 7140: 
 7141: =cut
 7142: 
 7143: sub scantron_form_start {
 7144:     my ($max_bubble)=@_;
 7145:     my $result= <<SCANTRONFORM;
 7146: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7147:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 7148:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 7149:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 7150:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 7151:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 7152:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 7153:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 7154:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 7155:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 7156: SCANTRONFORM
 7157: 
 7158:   my $line = 0;
 7159:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 7160:        my $chunk =
 7161: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 7162:        $chunk .=
 7163: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 7164:        $chunk .= 
 7165:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 7166:        $chunk .=
 7167:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 7168:        $chunk .=
 7169:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
 7170:        $result .= $chunk;
 7171:        $line++;
 7172:     }
 7173:     return $result;
 7174: }
 7175: 
 7176: =pod
 7177: 
 7178: =item scantron_validate_file
 7179: 
 7180:     Dispatch routine for doing validation of a bubblesheet data file.
 7181: 
 7182:     Also processes any necessary information resets that need to
 7183:     occur before validation begins (ignore previous corrections,
 7184:     restarting the skipped records processing)
 7185: 
 7186: =cut
 7187: 
 7188: sub scantron_validate_file {
 7189:     my ($r,$symb) = @_;
 7190:     if (!$symb) {return '';}
 7191:     my $default_form_data=&defaultFormData($symb);
 7192:     
 7193:     # do the detection of only doing skipped records first before we delete
 7194:     # them when doing the corrections reset
 7195:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 7196: 	&reset_skipping_status();
 7197:     }
 7198:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 7199: 	&remember_current_skipped();
 7200: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 7201:     }
 7202: 
 7203:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 7204: 	&check_for_error($r,&scantron_remove_file('corrected'));
 7205: 	&check_for_error($r,&scantron_remove_file('skipped'));
 7206: 	&check_for_error($r,&scantron_remove_scan_data());
 7207: 	$env{'form.scantron_options_ignore'}='done';
 7208:     }
 7209: 
 7210:     if ($env{'form.scantron_corrections'}) {
 7211: 	&scantron_process_corrections($r);
 7212:     }
 7213:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 7214:     #get the student pick code ready
 7215:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 7216:     my $nav_error;
 7217:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7218:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 7219:     if ($nav_error) {
 7220:         $r->print(&navmap_errormsg());
 7221:         return '';
 7222:     }
 7223:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 7224:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 7225:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
 7226:     }
 7227:     $r->print($result);
 7228:     
 7229:     my @validate_phases=( 'sequence',
 7230: 			  'ID',
 7231: 			  'CODE',
 7232: 			  'doublebubble',
 7233: 			  'missingbubbles');
 7234:     if (!$env{'form.validatepass'}) {
 7235: 	$env{'form.validatepass'} = 0;
 7236:     }
 7237:     my $currentphase=$env{'form.validatepass'};
 7238: 
 7239: 
 7240:     my $stop=0;
 7241:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 7242: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 7243: 	$r->rflush();
 7244:      
 7245: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 7246: 	{
 7247: 	    no strict 'refs';
 7248: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 7249: 	}
 7250:     }
 7251:     if (!$stop) {
 7252: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
 7253: 	$r->print(&mt('Validation process complete.').'<br />'.
 7254:                   $warning.
 7255:                   &mt('Perform verification for each student after storage of submissions?').
 7256:                   '&nbsp;<span class="LC_nobreak"><label>'.
 7257:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 7258:                   ('&nbsp;'x3).'<label>'.
 7259:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 7260:                   '</label></span><br />'.
 7261:                   &mt('Grading will take longer if you use verification.').'<br />'.
 7262:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
 7263:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 7264:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 7265:     } else {
 7266: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 7267: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 7268:     }
 7269:     if ($stop) {
 7270: 	if ($validate_phases[$currentphase] eq 'sequence') {
 7271: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 7272: 	    $r->print(' '.&mt('this error').' <br />');
 7273: 
 7274: 	    $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>');
 7275: 	} else {
 7276:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 7277: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 7278:             } else {
 7279:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 7280:             }
 7281: 	    $r->print(' '.&mt('using corrected info').' <br />');
 7282: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 7283: 	    $r->print(" ".&mt("this scanline saving it for later."));
 7284: 	}
 7285:     }
 7286:     $r->print(" </form><br />");
 7287:     return '';
 7288: }
 7289: 
 7290: 
 7291: =pod
 7292: 
 7293: =item scantron_remove_file
 7294: 
 7295:    Removes the requested bubblesheet data file, makes sure that
 7296:    scantron_original_<filename> is never removed
 7297: 
 7298: 
 7299: =cut
 7300: 
 7301: sub scantron_remove_file {
 7302:     my ($which)=@_;
 7303:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7304:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7305:     my $file='scantron_';
 7306:     if ($which eq 'corrected' || $which eq 'skipped') {
 7307: 	$file.=$which.'_';
 7308:     } else {
 7309: 	return 'refused';
 7310:     }
 7311:     $file.=$env{'form.scantron_selectfile'};
 7312:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 7313: }
 7314: 
 7315: 
 7316: =pod
 7317: 
 7318: =item scantron_remove_scan_data
 7319: 
 7320:    Removes all scan_data correction for the requested bubblesheet
 7321:    data file.  (In the case that both the are doing skipped records we need
 7322:    to remember the old skipped lines for the time being so that element
 7323:    persists for a while.)
 7324: 
 7325: =cut
 7326: 
 7327: sub scantron_remove_scan_data {
 7328:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7329:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7330:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 7331:     my @todelete;
 7332:     my $filename=$env{'form.scantron_selectfile'};
 7333:     foreach my $key (@keys) {
 7334: 	if ($key=~/^\Q$filename\E_/) {
 7335: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 7336: 		$key=~/remember_skipping/) {
 7337: 		next;
 7338: 	    }
 7339: 	    push(@todelete,$key);
 7340: 	}
 7341:     }
 7342:     my $result;
 7343:     if (@todelete) {
 7344: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 7345: 				       \@todelete,$cdom,$cname);
 7346:     } else {
 7347: 	$result = 'ok';
 7348:     }
 7349:     return $result;
 7350: }
 7351: 
 7352: 
 7353: =pod
 7354: 
 7355: =item scantron_getfile
 7356: 
 7357:     Fetches the requested bubblesheet data file (all 3 versions), and
 7358:     the scan_data hash
 7359:   
 7360:   Arguments:
 7361:     None
 7362: 
 7363:   Returns:
 7364:     2 hash references
 7365: 
 7366:      - first one has 
 7367:          orig      -
 7368:          corrected -
 7369:          skipped   -  each of which points to an array ref of the specified
 7370:                       file broken up into individual lines
 7371:          count     - number of scanlines
 7372:  
 7373:      - second is the scan_data hash possible keys are
 7374:        ($number refers to scanline numbered $number and thus the key affects
 7375:         only that scanline
 7376:         $bubline refers to the specific bubble line element and the aspects
 7377:         refers to that specific bubble line element)
 7378: 
 7379:        $number.user - username:domain to use
 7380:        $number.CODE_ignore_dup 
 7381:                     - ignore the duplicate CODE error 
 7382:        $number.useCODE
 7383:                     - use the CODE in the scanline as is
 7384:        $number.no_bubble.$bubline
 7385:                     - it is valid that there is no bubbled in bubble
 7386:                       at $number $bubline
 7387:        remember_skipping
 7388:                     - a frozen hash containing keys of $number and values
 7389:                       of either 
 7390:                         1 - we are on a 'do skipped records pass' and plan
 7391:                             on processing this line
 7392:                         2 - we are on a 'do skipped records pass' and this
 7393:                             scanline has been marked to skip yet again
 7394: 
 7395: =cut
 7396: 
 7397: sub scantron_getfile {
 7398:     #FIXME really would prefer a scantron directory
 7399:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7400:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7401:     my $lines;
 7402:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7403: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 7404:     my %scanlines;
 7405:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 7406:     my $temp=$scanlines{'orig'};
 7407:     $scanlines{'count'}=$#$temp;
 7408: 
 7409:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7410: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 7411:     if ($lines eq '-1') {
 7412: 	$scanlines{'corrected'}=[];
 7413:     } else {
 7414: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 7415:     }
 7416:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7417: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 7418:     if ($lines eq '-1') {
 7419: 	$scanlines{'skipped'}=[];
 7420:     } else {
 7421: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 7422:     }
 7423:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 7424:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 7425:     my %scan_data = @tmp;
 7426:     return (\%scanlines,\%scan_data);
 7427: }
 7428: 
 7429: =pod
 7430: 
 7431: =item lonnet_putfile
 7432: 
 7433:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 7434: 
 7435:  Arguments:
 7436:    $contents - data to store
 7437:    $filename - filename to store $contents into
 7438: 
 7439:  Returns:
 7440:    result value from &Apache::lonnet::finishuserfileupload
 7441: 
 7442: =cut
 7443: 
 7444: sub lonnet_putfile {
 7445:     my ($contents,$filename)=@_;
 7446:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7447:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7448:     $env{'form.sillywaytopassafilearound'}=$contents;
 7449:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 7450: 
 7451: }
 7452: 
 7453: =pod
 7454: 
 7455: =item scantron_putfile
 7456: 
 7457:     Stores the current version of the bubblesheet data files, and the
 7458:     scan_data hash. (Does not modify the original version only the
 7459:     corrected and skipped versions.
 7460: 
 7461:  Arguments:
 7462:     $scanlines - hash ref that looks like the first return value from
 7463:                  &scantron_getfile()
 7464:     $scan_data - hash ref that looks like the second return value from
 7465:                  &scantron_getfile()
 7466: 
 7467: =cut
 7468: 
 7469: sub scantron_putfile {
 7470:     my ($scanlines,$scan_data) = @_;
 7471:     #FIXME really would prefer a scantron directory
 7472:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7473:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7474:     if ($scanlines) {
 7475: 	my $prefix='scantron_';
 7476: # no need to update orig, shouldn't change
 7477: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 7478: #		    $env{'form.scantron_selectfile'});
 7479: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 7480: 			$prefix.'corrected_'.
 7481: 			$env{'form.scantron_selectfile'});
 7482: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 7483: 			$prefix.'skipped_'.
 7484: 			$env{'form.scantron_selectfile'});
 7485:     }
 7486:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 7487: }
 7488: 
 7489: =pod
 7490: 
 7491: =item scantron_get_line
 7492: 
 7493:    Returns the correct version of the scanline
 7494: 
 7495:  Arguments:
 7496:     $scanlines - hash ref that looks like the first return value from
 7497:                  &scantron_getfile()
 7498:     $scan_data - hash ref that looks like the second return value from
 7499:                  &scantron_getfile()
 7500:     $i         - number of the requested line (starts at 0)
 7501: 
 7502:  Returns:
 7503:    A scanline, (either the original or the corrected one if it
 7504:    exists), or undef if the requested scanline should be
 7505:    skipped. (Either because it's an skipped scanline, or it's an
 7506:    unskipped scanline and we are not doing a 'do skipped scanlines'
 7507:    pass.
 7508: 
 7509: =cut
 7510: 
 7511: sub scantron_get_line {
 7512:     my ($scanlines,$scan_data,$i)=@_;
 7513:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 7514:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 7515:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 7516:     return $scanlines->{'orig'}[$i]; 
 7517: }
 7518: 
 7519: =pod
 7520: 
 7521: =item scantron_todo_count
 7522: 
 7523:     Counts the number of scanlines that need processing.
 7524: 
 7525:  Arguments:
 7526:     $scanlines - hash ref that looks like the first return value from
 7527:                  &scantron_getfile()
 7528:     $scan_data - hash ref that looks like the second return value from
 7529:                  &scantron_getfile()
 7530: 
 7531:  Returns:
 7532:     $count - number of scanlines to process
 7533: 
 7534: =cut
 7535: 
 7536: sub get_todo_count {
 7537:     my ($scanlines,$scan_data)=@_;
 7538:     my $count=0;
 7539:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7540: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7541: 	if ($line=~/^[\s\cz]*$/) { next; }
 7542: 	$count++;
 7543:     }
 7544:     return $count;
 7545: }
 7546: 
 7547: =pod
 7548: 
 7549: =item scantron_put_line
 7550: 
 7551:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
 7552:     data file.
 7553: 
 7554:  Arguments:
 7555:     $scanlines - hash ref that looks like the first return value from
 7556:                  &scantron_getfile()
 7557:     $scan_data - hash ref that looks like the second return value from
 7558:                  &scantron_getfile()
 7559:     $i         - line number to update
 7560:     $newline   - contents of the updated scanline
 7561:     $skip      - if true make the line for skipping and update the
 7562:                  'skipped' file
 7563: 
 7564: =cut
 7565: 
 7566: sub scantron_put_line {
 7567:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 7568:     if ($skip) {
 7569: 	$scanlines->{'skipped'}[$i]=$newline;
 7570: 	&start_skipping($scan_data,$i);
 7571: 	return;
 7572:     }
 7573:     $scanlines->{'corrected'}[$i]=$newline;
 7574: }
 7575: 
 7576: =pod
 7577: 
 7578: =item scantron_clear_skip
 7579: 
 7580:    Remove a line from the 'skipped' file
 7581: 
 7582:  Arguments:
 7583:     $scanlines - hash ref that looks like the first return value from
 7584:                  &scantron_getfile()
 7585:     $scan_data - hash ref that looks like the second return value from
 7586:                  &scantron_getfile()
 7587:     $i         - line number to update
 7588: 
 7589: =cut
 7590: 
 7591: sub scantron_clear_skip {
 7592:     my ($scanlines,$scan_data,$i)=@_;
 7593:     if (exists($scanlines->{'skipped'}[$i])) {
 7594: 	undef($scanlines->{'skipped'}[$i]);
 7595: 	return 1;
 7596:     }
 7597:     return 0;
 7598: }
 7599: 
 7600: =pod
 7601: 
 7602: =item scantron_filter_not_exam
 7603: 
 7604:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 7605:    filter out resources that are not marked as 'exam' mode
 7606: 
 7607: =cut
 7608: 
 7609: sub scantron_filter_not_exam {
 7610:     my ($curres)=@_;
 7611:     
 7612:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 7613: 	# if the user has asked to not have either hidden
 7614: 	# or 'randomout' controlled resources to be graded
 7615: 	# don't include them
 7616: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 7617: 	    && $curres->randomout) {
 7618: 	    return 0;
 7619: 	}
 7620: 	return 1;
 7621:     }
 7622:     return 0;
 7623: }
 7624: 
 7625: =pod
 7626: 
 7627: =item scantron_validate_sequence
 7628: 
 7629:     Validates the selected sequence, checking for resource that are
 7630:     not set to exam mode.
 7631: 
 7632: =cut
 7633: 
 7634: sub scantron_validate_sequence {
 7635:     my ($r,$currentphase) = @_;
 7636: 
 7637:     my $navmap=Apache::lonnavmaps::navmap->new();
 7638:     unless (ref($navmap)) {
 7639:         $r->print(&navmap_errormsg());
 7640:         return (1,$currentphase);
 7641:     }
 7642:     my (undef,undef,$sequence)=
 7643: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7644: 
 7645:     my $map=$navmap->getResourceByUrl($sequence);
 7646: 
 7647:     $r->print('<input type="hidden" name="validate_sequence_exam"
 7648:                                     value="ignore" />');
 7649:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 7650: 	my @resources=
 7651: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 7652: 	if (@resources) {
 7653: 	    $r->print(
 7654:                 '<p class="LC_warning">'
 7655:                .&mt('Some resources in the sequence currently are not set to'
 7656:                    .' bubblesheet exam mode. Grading these resources currently may not'
 7657:                    .' work correctly.')
 7658:                .'</p>'
 7659:             );
 7660: 	    return (1,$currentphase);
 7661: 	}
 7662:     }
 7663: 
 7664:     return (0,$currentphase+1);
 7665: }
 7666: 
 7667: 
 7668: 
 7669: sub scantron_validate_ID {
 7670:     my ($r,$currentphase) = @_;
 7671:     
 7672:     #get student info
 7673:     my $classlist=&Apache::loncoursedata::get_classlist();
 7674:     my %idmap=&username_to_idmap($classlist);
 7675: 
 7676:     #get scantron line setup
 7677:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7678:     my ($scanlines,$scan_data)=&scantron_getfile();
 7679: 
 7680:     my $nav_error;
 7681:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
 7682:     if ($nav_error) {
 7683:         $r->print(&navmap_errormsg());
 7684:         return(1,$currentphase);
 7685:     }
 7686: 
 7687:     my %found=('ids'=>{},'usernames'=>{});
 7688:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7689: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7690: 	if ($line=~/^[\s\cz]*$/) { next; }
 7691: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7692: 						 $scan_data);
 7693: 	my $id=$$scan_record{'scantron.ID'};
 7694: 	my $found;
 7695: 	foreach my $checkid (keys(%idmap)) {
 7696: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 7697: 	}
 7698: 	if ($found) {
 7699: 	    my $username=$idmap{$found};
 7700: 	    if ($found{'ids'}{$found}) {
 7701: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7702: 					 $line,'duplicateID',$found);
 7703: 		return(1,$currentphase);
 7704: 	    } elsif ($found{'usernames'}{$username}) {
 7705: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7706: 					 $line,'duplicateID',$username);
 7707: 		return(1,$currentphase);
 7708: 	    }
 7709: 	    #FIXME store away line we previously saw the ID on to use above
 7710: 	    $found{'ids'}{$found}++;
 7711: 	    $found{'usernames'}{$username}++;
 7712: 	} else {
 7713: 	    if ($id =~ /^\s*$/) {
 7714: 		my $username=&scan_data($scan_data,"$i.user");
 7715: 		if (defined($username) && $found{'usernames'}{$username}) {
 7716: 		    &scantron_get_correction($r,$i,$scan_record,
 7717: 					     \%scantron_config,
 7718: 					     $line,'duplicateID',$username);
 7719: 		    return(1,$currentphase);
 7720: 		} elsif (!defined($username)) {
 7721: 		    &scantron_get_correction($r,$i,$scan_record,
 7722: 					     \%scantron_config,
 7723: 					     $line,'incorrectID');
 7724: 		    return(1,$currentphase);
 7725: 		}
 7726: 		$found{'usernames'}{$username}++;
 7727: 	    } else {
 7728: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7729: 					 $line,'incorrectID');
 7730: 		return(1,$currentphase);
 7731: 	    }
 7732: 	}
 7733:     }
 7734: 
 7735:     return (0,$currentphase+1);
 7736: }
 7737: 
 7738: 
 7739: sub scantron_get_correction {
 7740:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
 7741:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
 7742: #FIXME in the case of a duplicated ID the previous line, probably need
 7743: #to show both the current line and the previous one and allow skipping
 7744: #the previous one or the current one
 7745: 
 7746:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 7747:         $r->print(
 7748:             '<p class="LC_warning">'
 7749:            .&mt('An error was detected ([_1]) for PaperID [_2]',
 7750:                 "<b>$error</b>",
 7751:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
 7752:            ."</p> \n");
 7753:     } else {
 7754:         $r->print(
 7755:             '<p class="LC_warning">'
 7756:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
 7757:                 "<b>$error</b>", $i, "<pre>$line</pre>")
 7758:            ."</p> \n");
 7759:     }
 7760:     my $message =
 7761:         '<p>'
 7762:        .&mt('The ID on the form is [_1]',
 7763:             "<tt>$$scan_record{'scantron.ID'}</tt>")
 7764:        .'<br />'
 7765:        .&mt('The name on the paper is [_1], [_2]',
 7766:             $$scan_record{'scantron.LastName'},
 7767:             $$scan_record{'scantron.FirstName'})
 7768:        .'</p>';
 7769: 
 7770:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 7771:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 7772:                            # Array populated for doublebubble or
 7773:     my @lines_to_correct;  # missingbubble errors to build javascript
 7774:                            # to validate radio button checking   
 7775: 
 7776:     if ($error =~ /ID$/) {
 7777: 	if ($error eq 'incorrectID') {
 7778:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
 7779: 		      "</p>\n");
 7780: 	} elsif ($error eq 'duplicateID') {
 7781:             $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 7782: 	}
 7783: 	$r->print($message);
 7784: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 7785: 	$r->print("\n<ul><li> ");
 7786: 	#FIXME it would be nice if this sent back the user ID and
 7787: 	#could do partial userID matches
 7788: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 7789: 				       'scantron_username','scantron_domain'));
 7790: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 7791: 	$r->print("\n:\n".
 7792: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 7793: 
 7794: 	$r->print('</li>');
 7795:     } elsif ($error =~ /CODE$/) {
 7796: 	if ($error eq 'incorrectCODE') {
 7797: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 7798: 	} elsif ($error eq 'duplicateCODE') {
 7799: 	    $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");
 7800: 	}
 7801: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
 7802: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
 7803:                  ."</p>\n");
 7804: 	$r->print($message);
 7805: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
 7806: 	$r->print("\n<br /> ");
 7807: 	my $i=0;
 7808: 	if ($error eq 'incorrectCODE' 
 7809: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 7810: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 7811: 	    if ($closest > 0) {
 7812: 		foreach my $testcode (@{$closest}) {
 7813: 		    my $checked='';
 7814: 		    if (!$i) { $checked=' checked="checked"'; }
 7815: 		    $r->print("
 7816:    <label>
 7817:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 7818:        ".&mt("Use the similar CODE [_1] instead.",
 7819: 	    "<b><tt>".$testcode."</tt></b>")."
 7820:     </label>
 7821:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 7822: 		    $r->print("\n<br />");
 7823: 		    $i++;
 7824: 		}
 7825: 	    }
 7826: 	}
 7827: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 7828: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 7829: 	    $r->print("
 7830:     <label>
 7831:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 7832:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
 7833: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 7834:     </label>");
 7835: 	    $r->print("\n<br />");
 7836: 	}
 7837: 
 7838: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
 7839: function change_radio(field) {
 7840:     var slct=document.scantronupload.scantron_CODE_resolution;
 7841:     var i;
 7842:     for (i=0;i<slct.length;i++) {
 7843:         if (slct[i].value==field) { slct[i].checked=true; }
 7844:     }
 7845: }
 7846: ENDSCRIPT
 7847: 	my $href="/adm/pickcode?".
 7848: 	   "form=".&escape("scantronupload").
 7849: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 7850: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 7851: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 7852: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 7853: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 7854: 	    $r->print("
 7855:     <label>
 7856:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 7857:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 7858: 	     "<a target='_blank' href='$href'>","</a>")."
 7859:     </label> 
 7860:     ".&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\')" />'));
 7861: 	    $r->print("\n<br />");
 7862: 	}
 7863: 	$r->print("
 7864:     <label>
 7865:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 7866:        ".&mt("Use [_1] as the CODE.",
 7867: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 7868: 	$r->print("\n<br /><br />");
 7869:     } elsif ($error eq 'doublebubble') {
 7870: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 7871: 
 7872: 	# The form field scantron_questions is acutally a list of line numbers.
 7873: 	# represented by this form so:
 7874: 
 7875: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7876:                                                 $respnumlookup,$startline);
 7877: 
 7878: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7879: 		  $line_list.'" />');
 7880: 	$r->print($message);
 7881: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 7882: 	foreach my $question (@{$arg}) {
 7883: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7884:                                                    $scan_record, $error,
 7885:                                                    $randomorder,$randompick,
 7886:                                                    $respnumlookup,$startline);
 7887:             push(@lines_to_correct,@linenums);
 7888: 	}
 7889:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7890:     } elsif ($error eq 'missingbubble') {
 7891: 	$r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
 7892: 	$r->print($message);
 7893: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 7894: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 7895: 
 7896: 	# The form field scantron_questions is actually a list of line numbers not
 7897: 	# a list of question numbers. Therefore:
 7898: 	#
 7899: 
 7900: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7901:                                                 $respnumlookup,$startline);
 7902: 
 7903: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7904: 		  $line_list.'" />');
 7905: 	foreach my $question (@{$arg}) {
 7906: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7907:                                                    $scan_record, $error,
 7908:                                                    $randomorder,$randompick,
 7909:                                                    $respnumlookup,$startline);
 7910:             push(@lines_to_correct,@linenums);
 7911: 	}
 7912:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7913:     } else {
 7914: 	$r->print("\n<ul>");
 7915:     }
 7916:     $r->print("\n</li></ul>");
 7917: }
 7918: 
 7919: sub verify_bubbles_checked {
 7920:     my (@ansnums) = @_;
 7921:     my $ansnumstr = join('","',@ansnums);
 7922:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 7923:     &js_escape(\$warning);
 7924:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
 7925: function verify_bubble_radio(form) {
 7926:     var ansnumArray = new Array ("$ansnumstr");
 7927:     var need_bubble_count = 0;
 7928:     for (var i=0; i<ansnumArray.length; i++) {
 7929:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 7930:             var bubble_picked = 0; 
 7931:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 7932:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 7933:                     bubble_picked = 1;
 7934:                 }
 7935:             }
 7936:             if (bubble_picked == 0) {
 7937:                 need_bubble_count ++;
 7938:             }
 7939:         }
 7940:     }
 7941:     if (need_bubble_count) {
 7942:         alert("$warning");
 7943:         return;
 7944:     }
 7945:     form.submit(); 
 7946: }
 7947: ENDSCRIPT
 7948:     return $output;
 7949: }
 7950: 
 7951: =pod
 7952: 
 7953: =item  questions_to_line_list
 7954: 
 7955: Converts a list of questions into a string of comma separated
 7956: line numbers in the answer sheet used by the questions.  This is
 7957: used to fill in the scantron_questions form field.
 7958: 
 7959:   Arguments:
 7960:      questions    - Reference to an array of questions.
 7961:      randomorder  - True if randomorder in use.
 7962:      randompick   - True if randompick in use.
 7963:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
 7964:                      for current line to question number used for same question
 7965:                      in "Master Seqence" (as seen by Course Coordinator).
 7966:      startline    - Reference to hash where key is question number (0 is first)
 7967:                     and key is number of first bubble line for current student
 7968:                     or code-based randompick and/or randomorder.
 7969: 
 7970: =cut
 7971: 
 7972: 
 7973: sub questions_to_line_list {
 7974:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
 7975:     my @lines;
 7976: 
 7977:     foreach my $item (@{$questions}) {
 7978:         my $question = $item;
 7979:         my ($first,$count,$last);
 7980:         if ($item =~ /^(\d+)\.(\d+)$/) {
 7981:             $question = $1;
 7982:             my $subquestion = $2;
 7983:             my $responsenum = $question-1;
 7984:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7985:                 $responsenum = $respnumlookup->{$question-1};
 7986:                 if (ref($startline) eq 'HASH') {
 7987:                     $first = $startline->{$question-1} + 1;
 7988:                 }
 7989:             } else {
 7990:                 $first = $first_bubble_line{$responsenum} + 1;
 7991:             }
 7992:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 7993:             my $subcount = 1;
 7994:             while ($subcount<$subquestion) {
 7995:                 $first += $subans[$subcount-1];
 7996:                 $subcount ++;
 7997:             }
 7998:             $count = $subans[$subquestion-1];
 7999:         } else {
 8000:             my $responsenum = $question-1;
 8001:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8002:                 $responsenum = $respnumlookup->{$question-1};
 8003:                 if (ref($startline) eq 'HASH') {
 8004:                     $first = $startline->{$question-1} + 1;
 8005:                 }
 8006:             } else {
 8007:                 $first = $first_bubble_line{$responsenum} + 1;
 8008:             }
 8009: 	    $count   = $bubble_lines_per_response{$responsenum};
 8010:         }
 8011:         $last = $first+$count-1;
 8012:         push(@lines, ($first..$last));
 8013:     }
 8014:     return join(',', @lines);
 8015: }
 8016: 
 8017: =pod 
 8018: 
 8019: =item prompt_for_corrections
 8020: 
 8021: Prompts for a potentially multiline correction to the
 8022: user's bubbling (factors out common code from scantron_get_correction
 8023: for multi and missing bubble cases).
 8024: 
 8025:  Arguments:
 8026:    $r           - Apache request object.
 8027:    $question    - The question number to prompt for.
 8028:    $scan_config - The scantron file configuration hash.
 8029:    $scan_record - Reference to the hash that has the the parsed scanlines.
 8030:    $error       - Type of error
 8031:    $randomorder - True if randomorder in use.
 8032:    $randompick  - True if randompick in use.
 8033:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
 8034:                     for current line to question number used for same question
 8035:                     in "Master Seqence" (as seen by Course Coordinator).
 8036:    $startline   - Reference to hash where key is question number (0 is first)
 8037:                   and value is number of first bubble line for current student
 8038:                   or code-based randompick and/or randomorder.
 8039: 
 8040: 
 8041:  Implicit inputs:
 8042:    %bubble_lines_per_response   - Starting line numbers for each question.
 8043:                                   Numbered from 0 (but question numbers are from
 8044:                                   1.
 8045:    %first_bubble_line           - Starting bubble line for each question.
 8046:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 8047:                                   type problems render as separate sub-questions, 
 8048:                                   in exam mode. This hash contains a 
 8049:                                   comma-separated list of the lines per 
 8050:                                   sub-question.
 8051:    %responsetype_per_response   - essayresponse, formularesponse,
 8052:                                   stringresponse, imageresponse, reactionresponse,
 8053:                                   and organicresponse type problem parts can have
 8054:                                   multiple lines per response if the weight
 8055:                                   assigned exceeds 10.  In this case, only
 8056:                                   one bubble per line is permitted, but more 
 8057:                                   than one line might contain bubbles, e.g.
 8058:                                   bubbling of: line 1 - J, line 2 - J, 
 8059:                                   line 3 - B would assign 22 points.  
 8060: 
 8061: =cut
 8062: 
 8063: sub prompt_for_corrections {
 8064:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
 8065:         $randompick, $respnumlookup, $startline) = @_;
 8066:     my ($current_line,$lines);
 8067:     my @linenums;
 8068:     my $questionnum = $question;
 8069:     my ($first,$responsenum);
 8070:     if ($question =~ /^(\d+)\.(\d+)$/) {
 8071:         $question = $1;
 8072:         my $subquestion = $2;
 8073:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8074:             $responsenum = $respnumlookup->{$question-1};
 8075:             if (ref($startline) eq 'HASH') {
 8076:                 $first = $startline->{$question-1};
 8077:             }
 8078:         } else {
 8079:             $responsenum = $question-1;
 8080:             $first = $first_bubble_line{$responsenum};
 8081:         }
 8082:         $current_line = $first + 1 ;
 8083:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8084:         my $subcount = 1;
 8085:         while ($subcount<$subquestion) {
 8086:             $current_line += $subans[$subcount-1];
 8087:             $subcount ++;
 8088:         }
 8089:         $lines = $subans[$subquestion-1];
 8090:     } else {
 8091:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8092:             $responsenum = $respnumlookup->{$question-1};
 8093:             if (ref($startline) eq 'HASH') { 
 8094:                 $first = $startline->{$question-1};
 8095:             }
 8096:         } else {
 8097:             $responsenum = $question-1;
 8098:             $first = $first_bubble_line{$responsenum};
 8099:         }
 8100:         $current_line = $first + 1;
 8101:         $lines        = $bubble_lines_per_response{$responsenum};
 8102:     }
 8103:     if ($lines > 1) {
 8104:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 8105:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 8106:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 8107:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 8108:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 8109:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 8110:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 8111:             $r->print(
 8112:                 &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)
 8113:                .'<br /><br />'
 8114:                .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
 8115:                .'<br />'
 8116:                .&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.')
 8117:                .'<br />'
 8118:                .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
 8119:                .'<br /><br />'
 8120:             );
 8121:         } else {
 8122:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 8123:         }
 8124:     }
 8125:     for (my $i =0; $i < $lines; $i++) {
 8126:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 8127: 	&scantron_bubble_selector($r,$scan_config,$current_line,
 8128: 	        		  $questionnum,$error,split('', $selected));
 8129:         push(@linenums,$current_line);
 8130: 	$current_line++;
 8131:     }
 8132:     if ($lines > 1) {
 8133: 	$r->print("<hr /><br />");
 8134:     }
 8135:     return @linenums;
 8136: }
 8137: 
 8138: =pod
 8139: 
 8140: =item scantron_bubble_selector
 8141:   
 8142:    Generates the html radiobuttons to correct a single bubble line
 8143:    possibly showing the existing the selected bubbles if known
 8144: 
 8145:  Arguments:
 8146:     $r           - Apache request object
 8147:     $scan_config - hash from &get_scantron_config()
 8148:     $line        - Number of the line being displayed.
 8149:     $questionnum - Question number (may include subquestion)
 8150:     $error       - Type of error.
 8151:     @selected    - Array of bubbles picked on this line.
 8152: 
 8153: =cut
 8154: 
 8155: sub scantron_bubble_selector {
 8156:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 8157:     my $max=$$scan_config{'Qlength'};
 8158: 
 8159:     my $scmode=$$scan_config{'Qon'};
 8160:     if ($scmode eq 'number' || $scmode eq 'letter') { 
 8161:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
 8162:             ($$scan_config{'BubblesPerRow'} > 0)) {
 8163:             $max=$$scan_config{'BubblesPerRow'};
 8164:             if (($scmode eq 'number') && ($max > 10)) {
 8165:                 $max = 10;
 8166:             } elsif (($scmode eq 'letter') && $max > 26) {
 8167:                 $max = 26;
 8168:             }
 8169:         } else {
 8170:             $max = 10;
 8171:         }
 8172:     }
 8173: 
 8174:     my @alphabet=('A'..'Z');
 8175:     $r->print(&Apache::loncommon::start_data_table().
 8176:               &Apache::loncommon::start_data_table_row());
 8177:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 8178:     for (my $i=0;$i<$max+1;$i++) {
 8179: 	$r->print("\n".'<td align="center">');
 8180: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 8181: 	else { $r->print('&nbsp;'); }
 8182: 	$r->print('</td>');
 8183:     }
 8184:     $r->print(&Apache::loncommon::end_data_table_row().
 8185:               &Apache::loncommon::start_data_table_row());
 8186:     for (my $i=0;$i<$max;$i++) {
 8187: 	$r->print("\n".
 8188: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 8189: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 8190:     }
 8191:     my $nobub_checked = ' ';
 8192:     if ($error eq 'missingbubble') {
 8193:         $nobub_checked = ' checked = "checked" ';
 8194:     }
 8195:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 8196: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 8197:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 8198:               $line.'" value="'.$questionnum.'" /></td>');
 8199:     $r->print(&Apache::loncommon::end_data_table_row().
 8200:               &Apache::loncommon::end_data_table());
 8201: }
 8202: 
 8203: =pod
 8204: 
 8205: =item num_matches
 8206: 
 8207:    Counts the number of characters that are the same between the two arguments.
 8208: 
 8209:  Arguments:
 8210:    $orig - CODE from the scanline
 8211:    $code - CODE to match against
 8212: 
 8213:  Returns:
 8214:    $count - integer count of the number of same characters between the
 8215:             two arguments
 8216: 
 8217: =cut
 8218: 
 8219: sub num_matches {
 8220:     my ($orig,$code) = @_;
 8221:     my @code=split(//,$code);
 8222:     my @orig=split(//,$orig);
 8223:     my $same=0;
 8224:     for (my $i=0;$i<scalar(@code);$i++) {
 8225: 	if ($code[$i] eq $orig[$i]) { $same++; }
 8226:     }
 8227:     return $same;
 8228: }
 8229: 
 8230: =pod
 8231: 
 8232: =item scantron_get_closely_matching_CODEs
 8233: 
 8234:    Cycles through all CODEs and finds the set that has the greatest
 8235:    number of same characters as the provided CODE
 8236: 
 8237:  Arguments:
 8238:    $allcodes - hash ref returned by &get_codes()
 8239:    $CODE     - CODE from the current scanline
 8240: 
 8241:  Returns:
 8242:    2 element list
 8243:     - first elements is number of how closely matching the best fit is 
 8244:       (5 means best set has 5 matching characters)
 8245:     - second element is an arrary ref containing the set of valid CODEs
 8246:       that best fit the passed in CODE
 8247: 
 8248: =cut
 8249: 
 8250: sub scantron_get_closely_matching_CODEs {
 8251:     my ($allcodes,$CODE)=@_;
 8252:     my @CODEs;
 8253:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 8254: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 8255:     }
 8256: 
 8257:     return ($#CODEs,$CODEs[-1]);
 8258: }
 8259: 
 8260: =pod
 8261: 
 8262: =item get_codes
 8263: 
 8264:    Builds a hash which has keys of all of the valid CODEs from the selected
 8265:    set of remembered CODEs.
 8266: 
 8267:  Arguments:
 8268:   $old_name - name of the set of remembered CODEs
 8269:   $cdom     - domain of the course
 8270:   $cnum     - internal course name
 8271: 
 8272:  Returns:
 8273:   %allcodes - keys are the valid CODEs, values are all 1
 8274: 
 8275: =cut
 8276: 
 8277: sub get_codes {
 8278:     my ($old_name, $cdom, $cnum) = @_;
 8279:     if (!$old_name) {
 8280: 	$old_name=$env{'form.scantron_CODElist'};
 8281:     }
 8282:     if (!$cdom) {
 8283: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 8284:     }
 8285:     if (!$cnum) {
 8286: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 8287:     }
 8288:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 8289: 				    $cdom,$cnum);
 8290:     my %allcodes;
 8291:     if ($result{"type\0$old_name"} eq 'number') {
 8292: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 8293:     } else {
 8294: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 8295:     }
 8296:     return %allcodes;
 8297: }
 8298: 
 8299: =pod
 8300: 
 8301: =item scantron_validate_CODE
 8302: 
 8303:    Validates all scanlines in the selected file to not have any
 8304:    invalid or underspecified CODEs and that none of the codes are
 8305:    duplicated if this was requested.
 8306: 
 8307: =cut
 8308: 
 8309: sub scantron_validate_CODE {
 8310:     my ($r,$currentphase) = @_;
 8311:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8312:     if ($scantron_config{'CODElocation'} &&
 8313: 	$scantron_config{'CODEstart'} &&
 8314: 	$scantron_config{'CODElength'}) {
 8315: 	if (!defined($env{'form.scantron_CODElist'})) {
 8316: 	    &FIXME_blow_up()
 8317: 	}
 8318:     } else {
 8319: 	return (0,$currentphase+1);
 8320:     }
 8321:     
 8322:     my %usedCODEs;
 8323: 
 8324:     my %allcodes=&get_codes();
 8325: 
 8326:     my $nav_error;
 8327:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
 8328:     if ($nav_error) {
 8329:         $r->print(&navmap_errormsg());
 8330:         return(1,$currentphase);
 8331:     }
 8332: 
 8333:     my ($scanlines,$scan_data)=&scantron_getfile();
 8334:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8335: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8336: 	if ($line=~/^[\s\cz]*$/) { next; }
 8337: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8338: 						 $scan_data);
 8339: 	my $CODE=$$scan_record{'scantron.CODE'};
 8340: 	my $error=0;
 8341: 	if (!&Apache::lonnet::validCODE($CODE)) {
 8342: 	    &scantron_get_correction($r,$i,$scan_record,
 8343: 				     \%scantron_config,
 8344: 				     $line,'incorrectCODE',\%allcodes);
 8345: 	    return(1,$currentphase);
 8346: 	}
 8347: 	if (%allcodes && !exists($allcodes{$CODE}) 
 8348: 	    && !$$scan_record{'scantron.useCODE'}) {
 8349: 	    &scantron_get_correction($r,$i,$scan_record,
 8350: 				     \%scantron_config,
 8351: 				     $line,'incorrectCODE',\%allcodes);
 8352: 	    return(1,$currentphase);
 8353: 	}
 8354: 	if (exists($usedCODEs{$CODE}) 
 8355: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 8356: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 8357: 	    &scantron_get_correction($r,$i,$scan_record,
 8358: 				     \%scantron_config,
 8359: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 8360: 	    return(1,$currentphase);
 8361: 	}
 8362: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 8363:     }
 8364:     return (0,$currentphase+1);
 8365: }
 8366: 
 8367: =pod
 8368: 
 8369: =item scantron_validate_doublebubble
 8370: 
 8371:    Validates all scanlines in the selected file to not have any
 8372:    bubble lines with multiple bubbles marked.
 8373: 
 8374: =cut
 8375: 
 8376: sub scantron_validate_doublebubble {
 8377:     my ($r,$currentphase) = @_;
 8378:     #get student info
 8379:     my $classlist=&Apache::loncoursedata::get_classlist();
 8380:     my %idmap=&username_to_idmap($classlist);
 8381:     my (undef,undef,$sequence)=
 8382:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8383: 
 8384:     #get scantron line setup
 8385:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8386:     my ($scanlines,$scan_data)=&scantron_getfile();
 8387: 
 8388:     my $navmap = Apache::lonnavmaps::navmap->new();
 8389:     unless (ref($navmap)) {
 8390:         $r->print(&navmap_errormsg());
 8391:         return(1,$currentphase);
 8392:     }
 8393:     my $map=$navmap->getResourceByUrl($sequence);
 8394:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8395:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8396:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8397:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8398: 
 8399:     my $nav_error;
 8400:     if (ref($map)) {
 8401:         $randomorder = $map->randomorder();
 8402:         $randompick = $map->randompick();
 8403:         if ($randomorder || $randompick) {
 8404:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8405:             if ($nav_error) {
 8406:                 $r->print(&navmap_errormsg());
 8407:                 return(1,$currentphase);
 8408:             }
 8409:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8410:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8411:         }
 8412:     } else {
 8413:         $r->print(&navmap_errormsg());
 8414:         return(1,$currentphase);
 8415:     }
 8416: 
 8417:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
 8418:     if ($nav_error) {
 8419:         $r->print(&navmap_errormsg());
 8420:         return(1,$currentphase);
 8421:     }
 8422: 
 8423:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8424: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8425: 	if ($line=~/^[\s\cz]*$/) { next; }
 8426: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8427: 						 $scan_data,undef,\%idmap,$randomorder,
 8428:                                                  $randompick,$sequence,\@master_seq,
 8429:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8430:                                                  \%orderedforcode,\%respnumlookup,\%startline);
 8431: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 8432: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 8433: 				 'doublebubble',
 8434: 				 $$scan_record{'scantron.doubleerror'},
 8435:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
 8436:     	return (1,$currentphase);
 8437:     }
 8438:     return (0,$currentphase+1);
 8439: }
 8440: 
 8441: 
 8442: sub scantron_get_maxbubble {
 8443:     my ($nav_error,$scantron_config) = @_;
 8444:     if (defined($env{'form.scantron_maxbubble'}) &&
 8445: 	$env{'form.scantron_maxbubble'}) {
 8446: 	&restore_bubble_lines();
 8447: 	return $env{'form.scantron_maxbubble'};
 8448:     }
 8449: 
 8450:     my (undef, undef, $sequence) =
 8451: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8452: 
 8453:     my $navmap=Apache::lonnavmaps::navmap->new();
 8454:     unless (ref($navmap)) {
 8455:         if (ref($nav_error)) {
 8456:             $$nav_error = 1;
 8457:         }
 8458:         return;
 8459:     }
 8460:     my $map=$navmap->getResourceByUrl($sequence);
 8461:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8462:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
 8463: 
 8464:     &Apache::lonxml::clear_problem_counter();
 8465: 
 8466:     my $uname       = $env{'user.name'};
 8467:     my $udom        = $env{'user.domain'};
 8468:     my $cid         = $env{'request.course.id'};
 8469:     my $total_lines = 0;
 8470:     %bubble_lines_per_response = ();
 8471:     %first_bubble_line         = ();
 8472:     %subdivided_bubble_lines   = ();
 8473:     %responsetype_per_response = ();
 8474:     %masterseq_id_responsenum  = ();
 8475: 
 8476:     my $response_number = 0;
 8477:     my $bubble_line     = 0;
 8478:     foreach my $resource (@resources) {
 8479:         my $resid = $resource->id(); 
 8480:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
 8481:                                                           $udom,undef,$bubbles_per_row);
 8482:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 8483: 	    foreach my $part_id (@{$parts}) {
 8484:                 my $lines;
 8485: 
 8486: 	        # TODO - make this a persistent hash not an array.
 8487: 
 8488:                 # optionresponse, matchresponse and rankresponse type items 
 8489:                 # render as separate sub-questions in exam mode.
 8490:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 8491:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 8492:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 8493:                     my ($numbub,$numshown);
 8494:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 8495:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 8496:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 8497:                         }
 8498:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 8499:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 8500:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 8501:                         }
 8502:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 8503:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 8504:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 8505:                         }
 8506:                     }
 8507:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 8508:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 8509:                     }
 8510:                     my $bubbles_per_row =
 8511:                         &bubblesheet_bubbles_per_row($scantron_config);
 8512:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
 8513:                     if (($numbub % $bubbles_per_row) != 0) {
 8514:                         $inner_bubble_lines++;
 8515:                     }
 8516:                     for (my $i=0; $i<$numshown; $i++) {
 8517:                         $subdivided_bubble_lines{$response_number} .= 
 8518:                             $inner_bubble_lines.',';
 8519:                     }
 8520:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 8521:                     $lines = $numshown * $inner_bubble_lines;
 8522:                 } else {
 8523:                     $lines = $analysis->{"$part_id.bubble_lines"};
 8524:                 }
 8525: 
 8526:                 $first_bubble_line{$response_number} = $bubble_line;
 8527: 	        $bubble_lines_per_response{$response_number} = $lines;
 8528:                 $responsetype_per_response{$response_number} = 
 8529:                     $analysis->{$part_id.'.type'};
 8530:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;  
 8531: 	        $response_number++;
 8532: 
 8533: 	        $bubble_line +=  $lines;
 8534: 	        $total_lines +=  $lines;
 8535: 	    }
 8536:         }
 8537:     }
 8538:     &Apache::lonnet::delenv('scantron.');
 8539: 
 8540:     &save_bubble_lines();
 8541:     $env{'form.scantron_maxbubble'} =
 8542: 	$total_lines;
 8543:     return $env{'form.scantron_maxbubble'};
 8544: }
 8545: 
 8546: sub bubblesheet_bubbles_per_row {
 8547:     my ($scantron_config) = @_;
 8548:     my $bubbles_per_row;
 8549:     if (ref($scantron_config) eq 'HASH') {
 8550:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
 8551:     }
 8552:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
 8553:         $bubbles_per_row = 10;
 8554:     }
 8555:     return $bubbles_per_row;
 8556: }
 8557: 
 8558: sub scantron_validate_missingbubbles {
 8559:     my ($r,$currentphase) = @_;
 8560:     #get student info
 8561:     my $classlist=&Apache::loncoursedata::get_classlist();
 8562:     my %idmap=&username_to_idmap($classlist);
 8563:     my (undef,undef,$sequence)=
 8564:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8565: 
 8566:     #get scantron line setup
 8567:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8568:     my ($scanlines,$scan_data)=&scantron_getfile();
 8569: 
 8570:     my $navmap = Apache::lonnavmaps::navmap->new();
 8571:     unless (ref($navmap)) {
 8572:         $r->print(&navmap_errormsg());
 8573:         return(1,$currentphase);
 8574:     }
 8575: 
 8576:     my $map=$navmap->getResourceByUrl($sequence);
 8577:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8578:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8579:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8580:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8581: 
 8582:     my $nav_error;
 8583:     if (ref($map)) {
 8584:         $randomorder = $map->randomorder();
 8585:         $randompick = $map->randompick();
 8586:         if ($randomorder || $randompick) {
 8587:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8588:             if ($nav_error) {
 8589:                 $r->print(&navmap_errormsg());
 8590:                 return(1,$currentphase);
 8591:             }
 8592:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8593:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8594:         }
 8595:     } else {
 8596:         $r->print(&navmap_errormsg());
 8597:         return(1,$currentphase);
 8598:     }
 8599: 
 8600: 
 8601:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 8602:     if ($nav_error) {
 8603:         $r->print(&navmap_errormsg());
 8604:         return(1,$currentphase);
 8605:     }
 8606: 
 8607:     if (!$max_bubble) { $max_bubble=2**31; }
 8608:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8609: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8610: 	if ($line=~/^[\s\cz]*$/) { next; }
 8611: 	my $scan_record =
 8612:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
 8613: 				     $randomorder,$randompick,$sequence,\@master_seq,
 8614:                                      \%symb_to_resource,\%grader_partids_by_symb,
 8615:                                      \%orderedforcode,\%respnumlookup,\%startline);
 8616: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 8617: 	my @to_correct;
 8618: 	
 8619: 	# Probably here's where the error is...
 8620: 
 8621: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 8622:             my $lastbubble;
 8623:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 8624:                my $question = $1;
 8625:                my $subquestion = $2;
 8626:                my ($first,$responsenum);
 8627:                if ($randomorder || $randompick) {
 8628:                    $responsenum = $respnumlookup{$question-1};
 8629:                    $first = $startline{$question-1};
 8630:                } else {
 8631:                    $responsenum = $question-1; 
 8632:                    $first = $first_bubble_line{$responsenum};
 8633:                }
 8634:                if (!defined($first)) { next; }
 8635:                my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8636:                my $subcount = 1;
 8637:                while ($subcount<$subquestion) {
 8638:                    $first += $subans[$subcount-1];
 8639:                    $subcount ++;
 8640:                }
 8641:                my $count = $subans[$subquestion-1];
 8642:                $lastbubble = $first + $count;
 8643:             } else {
 8644:                my ($first,$responsenum);
 8645:                if ($randomorder || $randompick) {
 8646:                    $responsenum = $respnumlookup{$missing-1};
 8647:                    $first = $startline{$missing-1};
 8648:                } else {
 8649:                    $responsenum = $missing-1;
 8650:                    $first = $first_bubble_line{$responsenum};
 8651:                }
 8652:                if (!defined($first)) { next; }
 8653:                $lastbubble = $first + $bubble_lines_per_response{$responsenum};
 8654:             }
 8655:             if ($lastbubble > $max_bubble) { next; }
 8656: 	    push(@to_correct,$missing);
 8657: 	}
 8658: 	if (@to_correct) {
 8659: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 8660: 				     $line,'missingbubble',\@to_correct,
 8661:                                      $randomorder,$randompick,\%respnumlookup,
 8662:                                      \%startline);
 8663: 	    return (1,$currentphase);
 8664: 	}
 8665: 
 8666:     }
 8667:     return (0,$currentphase+1);
 8668: }
 8669: 
 8670: sub hand_bubble_option {
 8671:     my (undef, undef, $sequence) =
 8672:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8673:     return if ($sequence eq '');
 8674:     my $navmap = Apache::lonnavmaps::navmap->new();
 8675:     unless (ref($navmap)) {
 8676:         return;
 8677:     }
 8678:     my $needs_hand_bubbles;
 8679:     my $map=$navmap->getResourceByUrl($sequence);
 8680:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8681:     foreach my $res (@resources) {
 8682:         if (ref($res)) {
 8683:             if ($res->is_problem()) {
 8684:                 my $partlist = $res->parts();
 8685:                 foreach my $part (@{ $partlist }) {
 8686:                     my @types = $res->responseType($part);
 8687:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
 8688:                         $needs_hand_bubbles = 1;
 8689:                         last;
 8690:                     }
 8691:                 }
 8692:             }
 8693:         }
 8694:     }
 8695:     if ($needs_hand_bubbles) {
 8696:         my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8697:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8698:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
 8699:                &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 />').
 8700:                '<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;'.
 8701:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
 8702:     }
 8703:     return;
 8704: }
 8705: 
 8706: sub scantron_process_students {
 8707:     my ($r,$symb) = @_;
 8708: 
 8709:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8710:     if (!$symb) {
 8711: 	return '';
 8712:     }
 8713:     my $default_form_data=&defaultFormData($symb);
 8714: 
 8715:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8716:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config); 
 8717:     my ($scanlines,$scan_data)=&scantron_getfile();
 8718:     my $classlist=&Apache::loncoursedata::get_classlist();
 8719:     my %idmap=&username_to_idmap($classlist);
 8720:     my $navmap=Apache::lonnavmaps::navmap->new();
 8721:     unless (ref($navmap)) {
 8722:         $r->print(&navmap_errormsg());
 8723:         return '';
 8724:     }
 8725:     my $map=$navmap->getResourceByUrl($sequence);
 8726:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8727:         %grader_randomlists_by_symb);
 8728:     if (ref($map)) {
 8729:         $randomorder = $map->randomorder();
 8730:         $randompick = $map->randompick();
 8731:     } else {
 8732:         $r->print(&navmap_errormsg());
 8733:         return '';
 8734:     }
 8735:     my $nav_error;
 8736:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8737:     if ($randomorder || $randompick) {
 8738:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8739:         if ($nav_error) {
 8740:             $r->print(&navmap_errormsg());
 8741:             return '';
 8742:         }
 8743:     }
 8744:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8745:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 8746: 
 8747:     my ($uname,$udom);
 8748:     my $result= <<SCANTRONFORM;
 8749: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 8750:   <input type="hidden" name="command" value="scantron_configphase" />
 8751:   $default_form_data
 8752: SCANTRONFORM
 8753:     $r->print($result);
 8754: 
 8755:     my @delayqueue;
 8756:     my (%completedstudents,%scandata);
 8757:     
 8758:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 8759:     my $count=&get_todo_count($scanlines,$scan_data);
 8760:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 8761:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
 8762:     $r->print('<br />');
 8763:     my $start=&Time::HiRes::time();
 8764:     my $i=-1;
 8765:     my $started;
 8766: 
 8767:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 8768:     if ($nav_error) {
 8769:         $r->print(&navmap_errormsg());
 8770:         return '';
 8771:     }
 8772: 
 8773:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 8774:     # the user and return.
 8775: 
 8776:     if ($ssi_error) {
 8777: 	$r->print("</form>");
 8778: 	&ssi_print_error($r);
 8779:         &Apache::lonnet::remove_lock($lock);
 8780: 	return '';		# Dunno why the other returns return '' rather than just returning.
 8781:     }
 8782: 
 8783:     my %lettdig = &letter_to_digits();
 8784:     my $numletts = scalar(keys(%lettdig));
 8785:     my %orderedforcode;
 8786: 
 8787:     while ($i<$scanlines->{'count'}) {
 8788:  	($uname,$udom)=('','');
 8789:  	$i++;
 8790:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8791:  	if ($line=~/^[\s\cz]*$/) { next; }
 8792: 	if ($started) {
 8793: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 8794: 	}
 8795: 	$started=1;
 8796:         my %respnumlookup = ();
 8797:         my %startline = ();
 8798:         my $total;
 8799:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8800:                                                  $scan_data,undef,\%idmap,$randomorder,
 8801:                                                  $randompick,$sequence,\@master_seq,
 8802:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8803:                                                  \%orderedforcode,\%respnumlookup,\%startline,
 8804:                                                  \$total);
 8805:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 8806:  					      \%idmap,$i)) {
 8807:   	    &scantron_add_delay(\@delayqueue,$line,
 8808:  				'Unable to find a student that matches',1);
 8809:  	    next;
 8810:   	}
 8811:  	if (exists $completedstudents{$uname}) {
 8812:  	    &scantron_add_delay(\@delayqueue,$line,
 8813:  				'Student '.$uname.' has multiple sheets',2);
 8814:  	    next;
 8815:  	}
 8816:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 8817:         my $user = $uname.':'.$usec;
 8818:   	($uname,$udom)=split(/:/,$uname);
 8819: 
 8820:         my $scancode;
 8821:         if ((exists($scan_record->{'scantron.CODE'})) &&
 8822:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 8823:             $scancode = $scan_record->{'scantron.CODE'};
 8824:         } else {
 8825:             $scancode = '';
 8826:         }
 8827: 
 8828:         my @mapresources = @resources;
 8829:         if ($randomorder || $randompick) {
 8830:             @mapresources = 
 8831:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 8832:                              \%orderedforcode);
 8833:         }
 8834:         my (%partids_by_symb,$res_error);
 8835:         foreach my $resource (@mapresources) {
 8836:             my $ressymb;
 8837:             if (ref($resource)) {
 8838:                 $ressymb = $resource->symb();
 8839:             } else {
 8840:                 $res_error = 1;
 8841:                 last;
 8842:             }
 8843:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8844:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8845:                 my $currcode;
 8846:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
 8847:                     $currcode = $scancode;
 8848:                 }
 8849:                 my ($analysis,$parts) =
 8850:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 8851:                                               $uname,$udom,undef,$bubbles_per_row,
 8852:                                               $currcode);
 8853:                 $partids_by_symb{$ressymb} = $parts;
 8854:             } else {
 8855:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 8856:             }
 8857:         }
 8858: 
 8859:         if ($res_error) {
 8860:             &scantron_add_delay(\@delayqueue,$line,
 8861:                                 'An error occurred while grading student '.$uname,2);
 8862:             next;
 8863:         }
 8864: 
 8865: 	&Apache::lonxml::clear_problem_counter();
 8866:   	&Apache::lonnet::appenv($scan_record);
 8867: 
 8868: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 8869: 	    &scantron_putfile($scanlines,$scan_data);
 8870: 	}
 8871: 	
 8872:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8873:                                    \@mapresources,\%partids_by_symb,
 8874:                                    $bubbles_per_row,$randomorder,$randompick,
 8875:                                    \%respnumlookup,\%startline) 
 8876:             eq 'ssi_error') {
 8877:             $ssi_error = 0; # So end of handler error message does not trigger.
 8878:             $r->print("</form>");
 8879:             &ssi_print_error($r);
 8880:             &Apache::lonnet::remove_lock($lock);
 8881:             return '';      # Why return ''?  Beats me.
 8882:         }
 8883: 
 8884:         if (($scancode) && ($randomorder || $randompick)) {
 8885:             my $parmresult =
 8886:                 &Apache::lonparmset::storeparm_by_symb($symb,
 8887:                                                        '0_examcode',2,$scancode,
 8888:                                                        'string_examcode',$uname,
 8889:                                                        $udom);
 8890:         }
 8891: 	$completedstudents{$uname}={'line'=>$line};
 8892:         if ($env{'form.verifyrecord'}) {
 8893:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8894:             if ($randompick) {
 8895:                 if ($total) {
 8896:                     $lastpos = $total*$scantron_config{'Qlength'};
 8897:                 }
 8898:             }
 8899: 
 8900:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8901:             chomp($studentdata);
 8902:             $studentdata =~ s/\r$//;
 8903:             my $studentrecord = '';
 8904:             my $counter = -1;
 8905:             foreach my $resource (@mapresources) {
 8906:                 my $ressymb = $resource->symb();
 8907:                 ($counter,my $recording) =
 8908:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8909:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 8910:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
 8911:                                              $randompick,\%respnumlookup,\%startline);
 8912:                 $studentrecord .= $recording;
 8913:             }
 8914:             if ($studentrecord ne $studentdata) {
 8915:                 &Apache::lonxml::clear_problem_counter();
 8916:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8917:                                            \@mapresources,\%partids_by_symb,
 8918:                                            $bubbles_per_row,$randomorder,$randompick,
 8919:                                            \%respnumlookup,\%startline) 
 8920:                     eq 'ssi_error') {
 8921:                     $ssi_error = 0; # So end of handler error message does not trigger.
 8922:                     $r->print("</form>");
 8923:                     &ssi_print_error($r);
 8924:                     &Apache::lonnet::remove_lock($lock);
 8925:                     delete($completedstudents{$uname});
 8926:                     return '';
 8927:                 }
 8928:                 $counter = -1;
 8929:                 $studentrecord = '';
 8930:                 foreach my $resource (@mapresources) {
 8931:                     my $ressymb = $resource->symb();
 8932:                     ($counter,my $recording) =
 8933:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8934:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 8935:                                                  \%scantron_config,\%lettdig,$numletts,
 8936:                                                  $randomorder,$randompick,\%respnumlookup,
 8937:                                                  \%startline);
 8938:                     $studentrecord .= $recording;
 8939:                 }
 8940:                 if ($studentrecord ne $studentdata) {
 8941:                     $r->print('<p><span class="LC_warning">');
 8942:                     if ($scancode eq '') {
 8943:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
 8944:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 8945:                     } else {
 8946:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
 8947:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 8948:                     }
 8949:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 8950:                               &Apache::loncommon::start_data_table_header_row()."\n".
 8951:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 8952:                               &Apache::loncommon::end_data_table_header_row()."\n".
 8953:                               &Apache::loncommon::start_data_table_row().
 8954:                               '<td>'.&mt('Bubblesheet').'</td>'.
 8955:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
 8956:                               &Apache::loncommon::end_data_table_row().
 8957:                               &Apache::loncommon::start_data_table_row().
 8958:                               '<td>'.&mt('Stored submissions').'</td>'.
 8959:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
 8960:                               &Apache::loncommon::end_data_table_row().
 8961:                               &Apache::loncommon::end_data_table().'</p>');
 8962:                 } else {
 8963:                     $r->print('<br /><span class="LC_warning">'.
 8964:                              &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 />'.
 8965:                              &mt("As a consequence, this user's submission history records two tries.").
 8966:                                  '</span><br />');
 8967:                 }
 8968:             }
 8969:         }
 8970:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 8971:     } continue {
 8972: 	&Apache::lonxml::clear_problem_counter();
 8973: 	&Apache::lonnet::delenv('scantron.');
 8974:     }
 8975:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8976:     &Apache::lonnet::remove_lock($lock);
 8977: #    my $lasttime = &Time::HiRes::time()-$start;
 8978: #    $r->print("<p>took $lasttime</p>");
 8979: 
 8980:     $r->print("</form>");
 8981:     return '';
 8982: }
 8983: 
 8984: sub graders_resources_pass {
 8985:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
 8986:         $bubbles_per_row) = @_;
 8987:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 8988:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 8989:         foreach my $resource (@{$resources}) {
 8990:             my $ressymb = $resource->symb();
 8991:             my ($analysis,$parts) =
 8992:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 8993:                                           $env{'user.name'},$env{'user.domain'},
 8994:                                           1,$bubbles_per_row);
 8995:             $grader_partids_by_symb->{$ressymb} = $parts;
 8996:             if (ref($analysis) eq 'HASH') {
 8997:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 8998:                     $grader_randomlists_by_symb->{$ressymb} =
 8999:                         $analysis->{'parts_withrandomlist'};
 9000:                 }
 9001:             }
 9002:         }
 9003:     }
 9004:     return;
 9005: }
 9006: 
 9007: =pod
 9008: 
 9009: =item users_order
 9010: 
 9011:   Returns array of resources in current map, ordered based on either CODE,
 9012:   if this is a CODEd exam, or based on student's identity if this is a 
 9013:   "NAMEd" exam.
 9014: 
 9015:   Should be used when randomorder and/or randompick applied when the 
 9016:   corresponding exam was printed, prior to students completing bubblesheets 
 9017:   for the version of the exam the student received.
 9018: 
 9019: =cut
 9020: 
 9021: sub users_order  {
 9022:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
 9023:     my @mapresources;
 9024:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
 9025:         return @mapresources;
 9026:     }
 9027:     if ($scancode) {
 9028:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
 9029:             @mapresources = @{$orderedforcode->{$scancode}};
 9030:         } else {
 9031:             $env{'form.CODE'} = $scancode;
 9032:             my $actual_seq =
 9033:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 9034:                                                                $master_seq,
 9035:                                                                $user,$scancode,1);
 9036:             if (ref($actual_seq) eq 'ARRAY') {
 9037:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
 9038:                 if (ref($orderedforcode) eq 'HASH') {
 9039:                     if (@mapresources > 0) { 
 9040:                         $orderedforcode->{$scancode} = \@mapresources;
 9041:                     }
 9042:                 }
 9043:             }
 9044:             delete($env{'form.CODE'});
 9045:         }
 9046:     } else {
 9047:         my $actual_seq =
 9048:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 9049:                                                            $master_seq,
 9050:                                                            $user,undef,1);
 9051:         if (ref($actual_seq) eq 'ARRAY') {
 9052:             @mapresources = 
 9053:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
 9054:         }
 9055:     }
 9056:     return @mapresources;
 9057: }
 9058: 
 9059: sub grade_student_bubbles {
 9060:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
 9061:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
 9062:     my $uselookup = 0;
 9063:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
 9064:         (ref($startline) eq 'HASH')) {
 9065:         $uselookup = 1;
 9066:     }
 9067: 
 9068:     if (ref($resources) eq 'ARRAY') {
 9069:         my $count = 0;
 9070:         foreach my $resource (@{$resources}) {
 9071:             my $ressymb = $resource->symb();
 9072:             my %form = ('submitted'      => 'scantron',
 9073:                         'grade_target'   => 'grade',
 9074:                         'grade_username' => $uname,
 9075:                         'grade_domain'   => $udom,
 9076:                         'grade_courseid' => $env{'request.course.id'},
 9077:                         'grade_symb'     => $ressymb,
 9078:                         'CODE'           => $scancode
 9079:                        );
 9080:             if ($bubbles_per_row ne '') {
 9081:                 $form{'bubbles_per_row'} = $bubbles_per_row;
 9082:             }
 9083:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
 9084:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
 9085:             }
 9086:             if (ref($parts) eq 'HASH') {
 9087:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 9088:                     foreach my $part (@{$parts->{$ressymb}}) {
 9089:                         if ($uselookup) {
 9090:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
 9091:                         } else {
 9092:                             $form{'scantron_questnum_start.'.$part} =
 9093:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
 9094:                         }
 9095:                         $count++;
 9096:                     }
 9097:                 }
 9098:             }
 9099:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 9100:             return 'ssi_error' if ($ssi_error);
 9101:             last if (&Apache::loncommon::connection_aborted($r));
 9102:         }
 9103:     }
 9104:     return;
 9105: }
 9106: 
 9107: sub scantron_upload_scantron_data {
 9108:     my ($r,$symb)=@_;
 9109:     my $dom = $env{'request.role.domain'};
 9110:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 9111:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 9112:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 9113: 							  'domainid',
 9114: 							  'coursename',$dom);
 9115:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 9116:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
 9117:     my $default_form_data=&defaultFormData($symb);
 9118:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 9119:     &js_escape(\$nofile_alert);
 9120:     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.");
 9121:     &js_escape(\$nocourseid_alert);
 9122:     $r->print(&Apache::lonhtmlcommon::scripttag('
 9123:     function checkUpload(formname) {
 9124: 	if (formname.upfile.value == "") {
 9125: 	    alert("'.$nofile_alert.'");
 9126: 	    return false;
 9127: 	}
 9128:         if (formname.courseid.value == "") {
 9129:             alert("'.$nocourseid_alert.'");
 9130:             return false;
 9131:         }
 9132: 	formname.submit();
 9133:     }
 9134: 
 9135:     function ToSyllabus() {
 9136:         var cdom = '."'$dom'".';
 9137:         var cnum = document.rules.courseid.value;
 9138:         if (cdom == "" || cdom == null) {
 9139:             return;
 9140:         }
 9141:         if (cnum == "" || cnum == null) {
 9142:            return;
 9143:         }
 9144:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 9145:                             "height=350,width=350,scrollbars=yes,menubar=no");
 9146:         return;
 9147:     }
 9148: 
 9149: '));
 9150:     $r->print('
 9151: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
 9152: 
 9153: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 9154: '.$default_form_data.
 9155:   &Apache::lonhtmlcommon::start_pick_box().
 9156:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 9157:   '<input name="courseid" type="text" size="30" />'.$select_link.
 9158:   &Apache::lonhtmlcommon::row_closure().
 9159:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 9160:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 9161:   &Apache::lonhtmlcommon::row_closure().
 9162:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 9163:   '<input name="domainid" type="hidden" />'.$domdesc.
 9164:   &Apache::lonhtmlcommon::row_closure().
 9165:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 9166:   '<input type="file" name="upfile" size="50" />'.
 9167:   &Apache::lonhtmlcommon::row_closure(1).
 9168:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 9169: 
 9170: <input name="command" value="scantronupload_save" type="hidden" />
 9171: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 9172: </form>
 9173: ');
 9174:     return '';
 9175: }
 9176: 
 9177: 
 9178: sub scantron_upload_scantron_data_save {
 9179:     my($r,$symb)=@_;
 9180:     my $doanotherupload=
 9181: 	'<br /><form action="/adm/grades" method="post">'."\n".
 9182: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 9183: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 9184: 	'</form>'."\n";
 9185:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 9186: 	!&Apache::lonnet::allowed('usc',
 9187: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 9188: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 9189: 	unless ($symb) {
 9190: 	    $r->print($doanotherupload);
 9191: 	}
 9192: 	return '';
 9193:     }
 9194:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 9195:     my $uploadedfile;
 9196:     $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
 9197:     if (length($env{'form.upfile'}) < 2) {
 9198:         $r->print(
 9199:             &Apache::lonhtmlcommon::confirm_success(
 9200:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
 9201:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
 9202:     } else {
 9203:         my $result = 
 9204:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
 9205:                                             $env{'form.courseid'},$env{'form.domainid'});
 9206:         if ($result =~ m{^/uploaded/}) {
 9207:             $r->print(
 9208:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
 9209:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
 9210:                         (length($env{'form.upfile'})-1),
 9211:                         '<span class="LC_filename">'.$result.'</span>'));
 9212:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 9213:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 9214:                                                        $env{'form.courseid'},$uploadedfile));
 9215:         } else {
 9216:             $r->print(
 9217:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
 9218:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
 9219:                           $result,
 9220: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 9221: 	}
 9222:     }
 9223:     if ($symb) {
 9224: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
 9225:     } else {
 9226: 	$r->print($doanotherupload);
 9227:     }
 9228:     return '';
 9229: }
 9230: 
 9231: sub validate_uploaded_scantron_file {
 9232:     my ($cdom,$cname,$fname) = @_;
 9233:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 9234:     my @lines;
 9235:     if ($scanlines ne '-1') {
 9236:         @lines=split("\n",$scanlines,-1);
 9237:     }
 9238:     my $output;
 9239:     if (@lines) {
 9240:         my (%counts,$max_match_format);
 9241:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
 9242:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 9243:         my %idmap = &username_to_idmap($classlist);
 9244:         foreach my $key (keys(%idmap)) {
 9245:             my $lckey = lc($key);
 9246:             $idmap{$lckey} = $idmap{$key};
 9247:         }
 9248:         my %unique_formats;
 9249:         my @formatlines = &get_scantronformat_file();
 9250:         foreach my $line (@formatlines) {
 9251:             chomp($line);
 9252:             my @config = split(/:/,$line);
 9253:             my $idstart = $config[5];
 9254:             my $idlength = $config[6];
 9255:             if (($idstart ne '') && ($idlength > 0)) {
 9256:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 9257:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 9258:                 } else {
 9259:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 9260:                 }
 9261:             }
 9262:         }
 9263:         foreach my $key (keys(%unique_formats)) {
 9264:             my ($idstart,$idlength) = split(':',$key);
 9265:             %{$counts{$key}} = (
 9266:                                'found'   => 0,
 9267:                                'total'   => 0,
 9268:                               );
 9269:             foreach my $line (@lines) {
 9270:                 next if ($line =~ /^#/);
 9271:                 next if ($line =~ /^[\s\cz]*$/);
 9272:                 my $id = substr($line,$idstart-1,$idlength);
 9273:                 $id = lc($id);
 9274:                 if (exists($idmap{$id})) {
 9275:                     $counts{$key}{'found'} ++;
 9276:                 }
 9277:                 $counts{$key}{'total'} ++;
 9278:             }
 9279:             if ($counts{$key}{'total'}) {
 9280:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 9281:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 9282:                     $max_match_pct = $percent_match;
 9283:                     $max_match_format = $key;
 9284:                     $found_match_count = $counts{$key}{'found'};
 9285:                     $max_match_count = $counts{$key}{'total'};
 9286:                 }
 9287:             }
 9288:         }
 9289:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 9290:             my $format_descs;
 9291:             my $numwithformat = @{$unique_formats{$max_match_format}};
 9292:             for (my $i=0; $i<$numwithformat; $i++) {
 9293:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 9294:                 if ($i<$numwithformat-2) {
 9295:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 9296:                 } elsif ($i==$numwithformat-2) {
 9297:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 9298:                 } elsif ($i==$numwithformat-1) {
 9299:                     $format_descs .= '"<i>'.$desc.'</i>"';
 9300:                 }
 9301:             }
 9302:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 9303:             $output .= '<br />';
 9304:             if ($found_match_count == $max_match_count) {
 9305:                 # 100% matching entries
 9306:                 $output .= &Apache::lonhtmlcommon::confirm_success(
 9307:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
 9308:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
 9309:                 &mt('Comparison of student IDs in the uploaded file with'.
 9310:                     ' the course roster found matches for [_1] of the [_2] entries'.
 9311:                     ' in the file (for the format defined for [_3]).',
 9312:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
 9313:             } else {
 9314:                 # Not all entries matching? -> Show warning and additional info
 9315:                 $output .=
 9316:                     &Apache::lonhtmlcommon::confirm_success(
 9317:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
 9318:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
 9319:                         &mt('Not all entries could be matched!'),1).'<br />'.
 9320:                     &mt('Comparison of student IDs in the uploaded file with'.
 9321:                         ' the course roster found matches for [_1] of the [_2] entries'.
 9322:                         ' in the file (for the format defined for [_3]).',
 9323:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
 9324:                     '<p class="LC_info">'.
 9325:                     &mt('A low percentage of matches results from one of the following:').
 9326:                     '</p><ul>'.
 9327:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
 9328:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
 9329:                                '<i>'.$cdom.'</i>').'</li>'.
 9330:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 9331:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
 9332:                     '</ul>';
 9333:             }
 9334:         }
 9335:     } else {
 9336:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
 9337:     }
 9338:     return $output;
 9339: }
 9340: 
 9341: sub valid_file {
 9342:     my ($requested_file)=@_;
 9343:     foreach my $filename (sort(&scantron_filenames())) {
 9344: 	if ($requested_file eq $filename) { return 1; }
 9345:     }
 9346:     return 0;
 9347: }
 9348: 
 9349: sub scantron_download_scantron_data {
 9350:     my ($r,$symb)=@_;
 9351:     my $default_form_data=&defaultFormData($symb);
 9352:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9353:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9354:     my $file=$env{'form.scantron_selectfile'};
 9355:     if (! &valid_file($file)) {
 9356: 	$r->print('
 9357: 	<p>
 9358: 	    '.&mt('The requested filename was invalid.').'
 9359:         </p>
 9360: ');
 9361: 	return;
 9362:     }
 9363:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 9364:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 9365:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 9366:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 9367:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 9368:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 9369:     $r->print('
 9370:     <p>
 9371: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
 9372: 	      '<a href="'.$orig.'">','</a>').'
 9373:     </p>
 9374:     <p>
 9375: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 9376: 	      '<a href="'.$corrected.'">','</a>').'
 9377:     </p>
 9378:     <p>
 9379: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 9380: 	      '<a href="'.$skipped.'">','</a>').'
 9381:     </p>
 9382: ');
 9383:     return '';
 9384: }
 9385: 
 9386: sub checkscantron_results {
 9387:     my ($r,$symb) = @_;
 9388:     if (!$symb) {return '';}
 9389:     my $cid = $env{'request.course.id'};
 9390:     my %lettdig = &letter_to_digits();
 9391:     my $numletts = scalar(keys(%lettdig));
 9392:     my $cnum = $env{'course.'.$cid.'.num'};
 9393:     my $cdom = $env{'course.'.$cid.'.domain'};
 9394:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 9395:     my %record;
 9396:     my %scantron_config =
 9397:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 9398:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 9399:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 9400:     my $classlist=&Apache::loncoursedata::get_classlist();
 9401:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 9402:     my $navmap=Apache::lonnavmaps::navmap->new();
 9403:     unless (ref($navmap)) {
 9404:         $r->print(&navmap_errormsg());
 9405:         return '';
 9406:     }
 9407:     my $map=$navmap->getResourceByUrl($sequence);
 9408:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 9409:         %grader_randomlists_by_symb,%orderedforcode);
 9410:     if (ref($map)) { 
 9411:         $randomorder=$map->randomorder();
 9412:         $randompick=$map->randompick();
 9413:     }
 9414:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 9415:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 9416:     if ($nav_error) {
 9417:         $r->print(&navmap_errormsg());
 9418:         return '';
 9419:     }
 9420:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 9421:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 9422:     my ($uname,$udom);
 9423:     my (%scandata,%lastname,%bylast);
 9424:     $r->print('
 9425: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 9426: 
 9427:     my @delayqueue;
 9428:     my %completedstudents;
 9429: 
 9430:     my $count=&get_todo_count($scanlines,$scan_data);
 9431:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 9432:     my ($username,$domain,$started);
 9433:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 9434:     if ($nav_error) {
 9435:         $r->print(&navmap_errormsg());
 9436:         return '';
 9437:     }
 9438: 
 9439:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
 9440:     my $start=&Time::HiRes::time();
 9441:     my $i=-1;
 9442: 
 9443:     while ($i<$scanlines->{'count'}) {
 9444:         ($username,$domain,$uname)=('','','');
 9445:         $i++;
 9446:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 9447:         if ($line=~/^[\s\cz]*$/) { next; }
 9448:         if ($started) {
 9449:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 9450:         }
 9451:         $started=1;
 9452:         my $scan_record=
 9453:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 9454:                                                      $scan_data);
 9455:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
 9456:                                               \%idmap,$i)) {
 9457:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9458:                                 'Unable to find a student that matches',1);
 9459:             next;
 9460:         }
 9461:         if (exists $completedstudents{$uname}) {
 9462:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9463:                                 'Student '.$uname.' has multiple sheets',2);
 9464:             next;
 9465:         }
 9466:         my $pid = $scan_record->{'scantron.ID'};
 9467:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 9468:         push(@{$bylast{$lastname{$pid}}},$pid);
 9469:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 9470:         my $user = $uname.':'.$usec;
 9471:         ($username,$domain)=split(/:/,$uname);
 9472: 
 9473:         my $scancode;
 9474:         if ((exists($scan_record->{'scantron.CODE'})) &&
 9475:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 9476:             $scancode = $scan_record->{'scantron.CODE'};
 9477:         } else {
 9478:             $scancode = '';
 9479:         }
 9480: 
 9481:         my @mapresources = @resources;
 9482:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 9483:         my %respnumlookup=();
 9484:         my %startline=();
 9485:         if ($randomorder || $randompick) {
 9486:             @mapresources =
 9487:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 9488:                              \%orderedforcode);
 9489:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
 9490:                                              $scan_record,\@master_seq,\%symb_to_resource,
 9491:                                              \%grader_partids_by_symb,\%orderedforcode,
 9492:                                              \%respnumlookup,\%startline);
 9493:             if ($randompick && $total) {
 9494:                 $lastpos = $total*$scantron_config{'Qlength'};
 9495:             }
 9496:         }
 9497:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 9498:         chomp($scandata{$pid});
 9499:         $scandata{$pid} =~ s/\r$//;
 9500: 
 9501:         my $counter = -1;
 9502:         foreach my $resource (@mapresources) {
 9503:             my $parts;
 9504:             my $ressymb = $resource->symb();
 9505:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 9506:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 9507:                 my $currcode;
 9508:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
 9509:                     $currcode = $scancode;
 9510:                 }
 9511:                 (my $analysis,$parts) =
 9512:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 9513:                                               $username,$domain,undef,
 9514:                                               $bubbles_per_row,$currcode);
 9515:             } else {
 9516:                 $parts = $grader_partids_by_symb{$ressymb};
 9517:             }
 9518:             ($counter,my $recording) =
 9519:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 9520:                                          $scandata{$pid},$parts,
 9521:                                          \%scantron_config,\%lettdig,$numletts,
 9522:                                          $randomorder,$randompick,
 9523:                                          \%respnumlookup,\%startline);
 9524:             $record{$pid} .= $recording;
 9525:         }
 9526:     }
 9527:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 9528:     $r->print('<br />');
 9529:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 9530:     $passed = 0;
 9531:     $failed = 0;
 9532:     $numstudents = 0;
 9533:     foreach my $last (sort(keys(%bylast))) {
 9534:         if (ref($bylast{$last}) eq 'ARRAY') {
 9535:             foreach my $pid (sort(@{$bylast{$last}})) {
 9536:                 my $showscandata = $scandata{$pid};
 9537:                 my $showrecord = $record{$pid};
 9538:                 $showscandata =~ s/\s/&nbsp;/g;
 9539:                 $showrecord =~ s/\s/&nbsp;/g;
 9540:                 if ($scandata{$pid} eq $record{$pid}) {
 9541:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 9542:                     $okstudents .= '<tr class="'.$css_class.'">'.
 9543: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 9544: '</tr>'."\n".
 9545: '<tr class="'.$css_class.'">'."\n".
 9546: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
 9547:                     $passed ++;
 9548:                 } else {
 9549:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 9550:                     $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".
 9551: '</tr>'."\n".
 9552: '<tr class="'.$css_class.'">'."\n".
 9553: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 9554: '</tr>'."\n";
 9555:                     $failed ++;
 9556:                 }
 9557:                 $numstudents ++;
 9558:             }
 9559:         }
 9560:     }
 9561:     $r->print(
 9562:         '<p>'
 9563:        .&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).',
 9564:             '<b>',
 9565:             $numstudents,
 9566:             '</b>',
 9567:             $env{'form.scantron_maxbubble'})
 9568:        .'</p>'
 9569:     );
 9570:     $r->print('<p>'
 9571:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
 9572:              .'<br />'
 9573:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
 9574:              .'</p>'
 9575:     );
 9576:     if ($passed) {
 9577:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 9578:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9579:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9580:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9581:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9582:                  $okstudents."\n".
 9583:                  &Apache::loncommon::end_data_table().'<br />');
 9584:     }
 9585:     if ($failed) {
 9586:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 9587:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9588:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9589:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9590:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9591:                  $badstudents."\n".
 9592:                  &Apache::loncommon::end_data_table()).'<br />'.
 9593:                  &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.');  
 9594:     }
 9595:     $r->print('</form><br />');
 9596:     return;
 9597: }
 9598: 
 9599: sub verify_scantron_grading {
 9600:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 9601:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
 9602:         $respnumlookup,$startline) = @_;
 9603:     my ($record,%expected,%startpos);
 9604:     return ($counter,$record) if (!ref($resource));
 9605:     return ($counter,$record) if (!$resource->is_problem());
 9606:     my $symb = $resource->symb();
 9607:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 9608:     foreach my $part_id (@{$partids}) {
 9609:         $counter ++;
 9610:         $expected{$part_id} = 0;
 9611:         my $respnum = $counter;
 9612:         if ($randomorder || $randompick) {
 9613:             $respnum = $respnumlookup->{$counter};
 9614:             $startpos{$part_id} = $startline->{$counter} + 1;
 9615:         } else {
 9616:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 9617:         }
 9618:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
 9619:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
 9620:             foreach my $item (@sub_lines) {
 9621:                 $expected{$part_id} += $item;
 9622:             }
 9623:         } else {
 9624:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
 9625:         }
 9626:     }
 9627:     if ($symb) {
 9628:         my %recorded;
 9629:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 9630:         if ($returnhash{'version'}) {
 9631:             my %lasthash=();
 9632:             my $version;
 9633:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 9634:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 9635:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 9636:                 }
 9637:             }
 9638:             foreach my $key (keys(%lasthash)) {
 9639:                 if ($key =~ /\.scantron$/) {
 9640:                     my $value = &unescape($lasthash{$key});
 9641:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 9642:                     if ($value eq '') {
 9643:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 9644:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 9645:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9646:                             }
 9647:                         }
 9648:                     } else {
 9649:                         my @tocheck;
 9650:                         my @items = split(//,$value);
 9651:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 9652:                             ($scantron_config->{'Qon'} eq 'number')) {
 9653:                             if (@items < $expected{$part_id}) {
 9654:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 9655:                                 my @singles = split(//,$fragment);
 9656:                                 foreach my $pos (@singles) {
 9657:                                     if ($pos eq ' ') {
 9658:                                         push(@tocheck,$pos);
 9659:                                     } else {
 9660:                                         my $next = shift(@items);
 9661:                                         push(@tocheck,$next);
 9662:                                     }
 9663:                                 }
 9664:                             } else {
 9665:                                 @tocheck = @items;
 9666:                             }
 9667:                             foreach my $letter (@tocheck) {
 9668:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 9669:                                     if ($letter !~ /^[A-J]$/) {
 9670:                                         $letter = $scantron_config->{'Qoff'};
 9671:                                     }
 9672:                                     $recorded{$part_id} .= $letter;
 9673:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 9674:                                     my $digit;
 9675:                                     if ($letter !~ /^[A-J]$/) {
 9676:                                         $digit = $scantron_config->{'Qoff'};
 9677:                                     } else {
 9678:                                         $digit = $lettdig->{$letter};
 9679:                                     }
 9680:                                     $recorded{$part_id} .= $digit;
 9681:                                 }
 9682:                             }
 9683:                         } else {
 9684:                             @tocheck = @items;
 9685:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 9686:                                 my $curr_sub = shift(@tocheck);
 9687:                                 my $digit;
 9688:                                 if ($curr_sub =~ /^[A-J]$/) {
 9689:                                     $digit = $lettdig->{$curr_sub}-1;
 9690:                                 }
 9691:                                 if ($curr_sub eq 'J') {
 9692:                                     $digit += scalar($numletts);
 9693:                                 }
 9694:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9695:                                     if ($j == $digit) {
 9696:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 9697:                                     } else {
 9698:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9699:                                     }
 9700:                                 }
 9701:                             }
 9702:                         }
 9703:                     }
 9704:                 }
 9705:             }
 9706:         }
 9707:         foreach my $part_id (@{$partids}) {
 9708:             if ($recorded{$part_id} eq '') {
 9709:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 9710:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9711:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9712:                     }
 9713:                 }
 9714:             }
 9715:             $record .= $recorded{$part_id};
 9716:         }
 9717:     }
 9718:     return ($counter,$record);
 9719: }
 9720: 
 9721: sub letter_to_digits {
 9722:     my %lettdig = (
 9723:                     A => 1,
 9724:                     B => 2,
 9725:                     C => 3,
 9726:                     D => 4,
 9727:                     E => 5,
 9728:                     F => 6,
 9729:                     G => 7,
 9730:                     H => 8,
 9731:                     I => 9,
 9732:                     J => 0,
 9733:                   );
 9734:     return %lettdig;
 9735: }
 9736: 
 9737: 
 9738: #-------- end of section for handling grading scantron forms -------
 9739: #
 9740: #-------------------------------------------------------------------
 9741: 
 9742: #-------------------------- Menu interface -------------------------
 9743: #
 9744: #--- Href with symb and command ---
 9745: 
 9746: sub href_symb_cmd {
 9747:     my ($symb,$cmd)=@_;
 9748:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
 9749: }
 9750: 
 9751: sub grading_menu {
 9752:     my ($request,$symb) = @_;
 9753:     if (!$symb) {return '';}
 9754: 
 9755:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 9756:                   'command'=>'individual');
 9757:     
 9758:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9759: 
 9760:     $fields{'command'}='ungraded';
 9761:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9762: 
 9763:     $fields{'command'}='table';
 9764:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9765: 
 9766:     $fields{'command'}='all_for_one';
 9767:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9768: 
 9769:     $fields{'command'}='downloadfilesselect';
 9770:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9771: 
 9772:     $fields{'command'} = 'csvform';
 9773:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9774:     
 9775:     $fields{'command'} = 'processclicker';
 9776:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9777:     
 9778:     $fields{'command'} = 'scantron_selectphase';
 9779:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9780: 
 9781:     $fields{'command'} = 'initialverifyreceipt';
 9782:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9783:     
 9784:     my @menu = ({	categorytitle=>'Hand Grading',
 9785:             items =>[
 9786:                         {	linktext => 'Select individual students to grade',
 9787:                     		url => $url1a,
 9788:                     		permission => 'F',
 9789:                     		icon => 'grade_students.png',
 9790:                     		linktitle => 'Grade current resource for a selection of students.'
 9791:                         }, 
 9792:                         {       linktext => 'Grade ungraded submissions.',
 9793:                                 url => $url1b,
 9794:                                 permission => 'F',
 9795:                                 icon => 'ungrade_sub.png',
 9796:                                 linktitle => 'Grade all submissions that have not been graded yet.'
 9797:                         },
 9798: 
 9799:                         {       linktext => 'Grading table',
 9800:                                 url => $url1c,
 9801:                                 permission => 'F',
 9802:                                 icon => 'grading_table.png',
 9803:                                 linktitle => 'Grade current resource for all students.'
 9804:                         },
 9805:                         {       linktext => 'Grade page/folder for one student',
 9806:                                 url => $url1d,
 9807:                                 permission => 'F',
 9808:                                 icon => 'grade_PageFolder.png',
 9809:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
 9810:                         },
 9811:                         {       linktext => 'Download submissions',
 9812:                                 url => $url1e,
 9813:                                 permission => 'F',
 9814:                                 icon => 'download_sub.png',
 9815:                                 linktitle => 'Download all students submissions.'
 9816:                         }]},
 9817:                          { categorytitle=>'Automated Grading',
 9818:                items =>[
 9819: 
 9820:                 	    {	linktext => 'Upload Scores',
 9821:                     		url => $url2,
 9822:                     		permission => 'F',
 9823:                     		icon => 'uploadscores.png',
 9824:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 9825:                 	    },
 9826:                 	    {	linktext => 'Process Clicker',
 9827:                     		url => $url3,
 9828:                     		permission => 'F',
 9829:                     		icon => 'addClickerInfoFile.png',
 9830:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 9831:                 	    },
 9832:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
 9833:                     		url => $url4,
 9834:                     		permission => 'F',
 9835:                     		icon => 'bubblesheet.png',
 9836:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
 9837:                 	    },
 9838:                             {   linktext => 'Verify Receipt Number',
 9839:                                 url => $url5,
 9840:                                 permission => 'F',
 9841:                                 icon => 'receipt_number.png',
 9842:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
 9843:                             }
 9844: 
 9845:                     ]
 9846:             });
 9847: 
 9848:     # Create the menu
 9849:     my $Str;
 9850:     $Str .= '<form method="post" action="" name="gradingMenu">';
 9851:     $Str .= '<input type="hidden" name="command" value="" />'.
 9852:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9853: 
 9854:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
 9855:     return $Str;    
 9856: }
 9857: 
 9858: 
 9859: sub ungraded {
 9860:     my ($request)=@_;
 9861:     &submit_options($request);
 9862: }
 9863: 
 9864: sub submit_options_sequence {
 9865:     my ($request,$symb) = @_;
 9866:     if (!$symb) {return '';}
 9867:     &commonJSfunctions($request);
 9868:     my $result;
 9869: 
 9870:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9871:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9872:     $result.=&selectfield(0).
 9873:             '<input type="hidden" name="command" value="pickStudentPage" />
 9874:             <div>
 9875:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 9876:             </div>
 9877:         </div>
 9878:   </form>';
 9879:     return $result;
 9880: }
 9881: 
 9882: sub submit_options_table {
 9883:     my ($request,$symb) = @_;
 9884:     if (!$symb) {return '';}
 9885:     &commonJSfunctions($request);
 9886:     my $is_tool = ($symb =~ /ext\.tool$/);
 9887:     my $result;
 9888: 
 9889:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9890:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9891: 
 9892:     $result.=&selectfield(1,$is_tool).
 9893:             '<input type="hidden" name="command" value="viewgrades" />
 9894:             <div>
 9895:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 9896:             </div>
 9897:         </div>
 9898:   </form>';
 9899:     return $result;
 9900: }
 9901: 
 9902: sub submit_options_download {
 9903:     my ($request,$symb) = @_;
 9904:     if (!$symb) {return '';}
 9905: 
 9906:     my $is_tool = ($symb =~ /ext\.tool$/);
 9907:     &commonJSfunctions($request);
 9908: 
 9909:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9910:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9911:     $result.='
 9912: <h2>
 9913:   '.&mt('Select Students for whom to Download Submissions').'
 9914: </h2>'.&selectfield(1,$is_tool).'
 9915:                 <input type="hidden" name="command" value="downloadfileslink" /> 
 9916:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 9917:             </div>
 9918:           </div>
 9919: 
 9920: 
 9921:   </form>';
 9922:     return $result;
 9923: }
 9924: 
 9925: #--- Displays the submissions first page -------
 9926: sub submit_options {
 9927:     my ($request,$symb) = @_;
 9928:     if (!$symb) {return '';}
 9929: 
 9930:     my $is_tool = ($symb =~ /ext\.tool$/);
 9931:     &commonJSfunctions($request);
 9932:     my $result;
 9933: 
 9934:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9935: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9936:     $result.=&selectfield(1,$is_tool).'
 9937:                 <input type="hidden" name="command" value="submission" /> 
 9938: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
 9939:             </div>
 9940:           </div>
 9941: 
 9942: 
 9943:   </form>';
 9944:     return $result;
 9945: }
 9946: 
 9947: sub selectfield {
 9948:    my ($full,$is_tool)=@_;
 9949:    my %options;
 9950:    if ($is_tool) {
 9951:        %options =
 9952:            (&transtatus_options,
 9953:             'select_form_order' => ['yes','incorrect','all']);
 9954:    } else {
 9955:        %options = 
 9956:            (&substatus_options,
 9957:             'select_form_order' => ['yes','queued','graded','incorrect','all']);
 9958:    }
 9959:    my $result='<div class="LC_columnSection">
 9960:   
 9961:     <fieldset>
 9962:       <legend>
 9963:        '.&mt('Sections').'
 9964:       </legend>
 9965:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
 9966:     </fieldset>
 9967:   
 9968:     <fieldset>
 9969:       <legend>
 9970:         '.&mt('Groups').'
 9971:       </legend>
 9972:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 9973:     </fieldset>
 9974:   
 9975:     <fieldset>
 9976:       <legend>
 9977:         '.&mt('Access Status').'
 9978:       </legend>
 9979:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
 9980:     </fieldset>';
 9981:     if ($full) {
 9982:         my $heading = &mt('Submission Status');
 9983:         if ($is_tool) {
 9984:             $heading = &mt('Transaction Status');
 9985:         }
 9986:         $result.='
 9987:     <fieldset>
 9988:       <legend>
 9989:         '.$heading.'
 9990:       </legend>'.
 9991:        &Apache::loncommon::select_form('all','submitonly',\%options).
 9992:    '</fieldset>';
 9993:     }
 9994:     $result.='</div><br />';
 9995:     return $result;
 9996: }
 9997: 
 9998: sub substatus_options {
 9999:     return &Apache::lonlocal::texthash(
10000:                                       'yes'       => 'with submissions',
10001:                                       'queued'    => 'in grading queue',
10002:                                       'graded'    => 'with ungraded submissions',
10003:                                       'incorrect' => 'with incorrect submissions',
10004:                                       'all'       => 'with any status',
10005:                                       );
10006: }
10007: 
10008: sub transtatus_options {
10009:     return &Apache::lonlocal::texthash(
10010:                                        'yes'       => 'with score transactions',
10011:                                        'incorrect' => 'with less than full credit',
10012:                                        'all'       => 'with any status',
10013:                                       );
10014: }
10015: 
10016: sub reset_perm {
10017:     undef(%perm);
10018: }
10019: 
10020: sub init_perm {
10021:     &reset_perm();
10022:     foreach my $test_perm ('vgr','mgr','opa') {
10023: 
10024: 	my $scope = $env{'request.course.id'};
10025: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
10026: 
10027: 	    $scope .= '/'.$env{'request.course.sec'};
10028: 	    if ( $perm{$test_perm}=
10029: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
10030: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
10031: 	    } else {
10032: 		delete($perm{$test_perm});
10033: 	    }
10034: 	}
10035:     }
10036: }
10037: 
10038: sub init_old_essays {
10039:     my ($symb,$apath,$adom,$aname) = @_;
10040:     if ($symb ne '') {
10041:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
10042:         if (keys(%essays) > 0) {
10043:             $old_essays{$symb} = \%essays;
10044:         }
10045:     }
10046:     return;
10047: }
10048: 
10049: sub reset_old_essays {
10050:     undef(%old_essays);
10051: }
10052: 
10053: sub gather_clicker_ids {
10054:     my %clicker_ids;
10055: 
10056:     my $classlist = &Apache::loncoursedata::get_classlist();
10057: 
10058:     # Set up a couple variables.
10059:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
10060:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
10061:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
10062: 
10063:     foreach my $student (keys(%$classlist)) {
10064:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
10065:         my $username = $classlist->{$student}->[$username_idx];
10066:         my $domain   = $classlist->{$student}->[$domain_idx];
10067:         my $clickers =
10068: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
10069:         foreach my $id (split(/\,/,$clickers)) {
10070:             $id=~s/^[\#0]+//;
10071:             $id=~s/[\-\:]//g;
10072:             if (exists($clicker_ids{$id})) {
10073: 		$clicker_ids{$id}.=','.$username.':'.$domain;
10074:             } else {
10075: 		$clicker_ids{$id}=$username.':'.$domain;
10076:             }
10077:         }
10078:     }
10079:     return %clicker_ids;
10080: }
10081: 
10082: sub gather_adv_clicker_ids {
10083:     my %clicker_ids;
10084:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
10085:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
10086:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
10087:     foreach my $element (sort(keys(%coursepersonnel))) {
10088:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
10089:             my ($puname,$pudom)=split(/\:/,$person);
10090:             my $clickers =
10091: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
10092:             foreach my $id (split(/\,/,$clickers)) {
10093: 		$id=~s/^[\#0]+//;
10094:                 $id=~s/[\-\:]//g;
10095: 		if (exists($clicker_ids{$id})) {
10096: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
10097: 		} else {
10098: 		    $clicker_ids{$id}=$puname.':'.$pudom;
10099: 		}
10100:             }
10101:         }
10102:     }
10103:     return %clicker_ids;
10104: }
10105: 
10106: sub clicker_grading_parameters {
10107:     return ('gradingmechanism' => 'scalar',
10108:             'upfiletype' => 'scalar',
10109:             'specificid' => 'scalar',
10110:             'pcorrect' => 'scalar',
10111:             'pincorrect' => 'scalar');
10112: }
10113: 
10114: sub process_clicker {
10115:     my ($r,$symb)=@_;
10116:     if (!$symb) {return '';}
10117:     my $result=&checkforfile_js();
10118:     $result.=&Apache::loncommon::start_data_table().
10119:              &Apache::loncommon::start_data_table_header_row().
10120:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
10121:              &Apache::loncommon::end_data_table_header_row().
10122:              &Apache::loncommon::start_data_table_row()."<td>\n";
10123: # Attempt to restore parameters from last session, set defaults if not present
10124:     my %Saveable_Parameters=&clicker_grading_parameters();
10125:     &Apache::loncommon::restore_course_settings('grades_clicker',
10126:                                                  \%Saveable_Parameters);
10127:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
10128:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
10129:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
10130:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
10131: 
10132:     my %checked;
10133:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
10134:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
10135:           $checked{$gradingmechanism}=' checked="checked"';
10136:        }
10137:     }
10138: 
10139:     my $upload=&mt("Evaluate File");
10140:     my $type=&mt("Type");
10141:     my $attendance=&mt("Award points just for participation");
10142:     my $personnel=&mt("Correctness determined from response by course personnel");
10143:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
10144:     my $given=&mt("Correctness determined from given list of answers").' '.
10145:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
10146:     my $pcorrect=&mt("Percentage points for correct solution");
10147:     my $pincorrect=&mt("Percentage points for incorrect solution");
10148:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
10149: 						   {'iclicker' => 'i>clicker',
10150:                                                     'interwrite' => 'interwrite PRS',
10151:                                                     'turning' => 'Turning Technologies'});
10152:     $symb = &Apache::lonenc::check_encrypt($symb);
10153:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
10154: function sanitycheck() {
10155: // Accept only integer percentages
10156:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
10157:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
10158: // Find out grading choice
10159:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
10160:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
10161:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
10162:       }
10163:    }
10164: // By default, new choice equals user selection
10165:    newgradingchoice=gradingchoice;
10166: // Not good to give more points for false answers than correct ones
10167:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
10168:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
10169:    }
10170: // If new choice is attendance only, and old choice was correctness-based, restore defaults
10171:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
10172:       document.forms.gradesupload.pcorrect.value=100;
10173:       document.forms.gradesupload.pincorrect.value=100;
10174:    }
10175: // If the values are different, cannot be attendance only
10176:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
10177:        (gradingchoice=='attendance')) {
10178:        newgradingchoice='personnel';
10179:    }
10180: // Change grading choice to new one
10181:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
10182:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
10183:          document.forms.gradesupload.gradingmechanism[i].checked=true;
10184:       } else {
10185:          document.forms.gradesupload.gradingmechanism[i].checked=false;
10186:       }
10187:    }
10188: // Remember the old state
10189:    document.forms.gradesupload.waschecked.value=newgradingchoice;
10190: }
10191: ENDUPFORM
10192:     $result.= <<ENDUPFORM;
10193: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
10194: <input type="hidden" name="symb" value="$symb" />
10195: <input type="hidden" name="command" value="processclickerfile" />
10196: <input type="file" name="upfile" size="50" />
10197: <br /><label>$type: $selectform</label>
10198: ENDUPFORM
10199:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
10200:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
10201:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
10202: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
10203: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
10204: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
10205: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
10206: <br />&nbsp;&nbsp;&nbsp;
10207: <input type="text" name="givenanswer" size="50" />
10208: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
10209: ENDGRADINGFORM
10210:          $result.='</td>'.&Apache::loncommon::end_data_table_row().
10211:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
10212:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
10213: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
10214: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
10215: </form>'
10216: ENDPERCFORM
10217:     $result.='</td>'.
10218:              &Apache::loncommon::end_data_table_row().
10219:              &Apache::loncommon::end_data_table();
10220:     return $result;
10221: }
10222: 
10223: sub process_clicker_file {
10224:     my ($r,$symb)=@_;
10225:     if (!$symb) {return '';}
10226: 
10227:     my %Saveable_Parameters=&clicker_grading_parameters();
10228:     &Apache::loncommon::store_course_settings('grades_clicker',
10229:                                               \%Saveable_Parameters);
10230:     my $result='';
10231:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
10232: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
10233: 	return $result;
10234:     }
10235:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
10236:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
10237:         return $result;
10238:     }
10239:     my $foundgiven=0;
10240:     if ($env{'form.gradingmechanism'} eq 'given') {
10241:         $env{'form.givenanswer'}=~s/^\s*//gs;
10242:         $env{'form.givenanswer'}=~s/\s*$//gs;
10243:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
10244:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
10245:         my @answers=split(/\,/,$env{'form.givenanswer'});
10246:         $foundgiven=$#answers+1;
10247:     }
10248:     my %clicker_ids=&gather_clicker_ids();
10249:     my %correct_ids;
10250:     if ($env{'form.gradingmechanism'} eq 'personnel') {
10251: 	%correct_ids=&gather_adv_clicker_ids();
10252:     }
10253:     if ($env{'form.gradingmechanism'} eq 'specific') {
10254: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
10255: 	   $correct_id=~tr/a-z/A-Z/;
10256: 	   $correct_id=~s/\s//gs;
10257: 	   $correct_id=~s/^[\#0]+//;
10258:            $correct_id=~s/[\-\:]//g;
10259:            if ($correct_id) {
10260: 	      $correct_ids{$correct_id}='specified';
10261:            }
10262:         }
10263:     }
10264:     if ($env{'form.gradingmechanism'} eq 'attendance') {
10265: 	$result.=&mt('Score based on attendance only');
10266:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
10267:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
10268:     } else {
10269: 	my $number=0;
10270: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
10271: 	foreach my $id (sort(keys(%correct_ids))) {
10272: 	    $result.='<br /><tt>'.$id.'</tt> - ';
10273: 	    if ($correct_ids{$id} eq 'specified') {
10274: 		$result.=&mt('specified');
10275: 	    } else {
10276: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
10277: 		$result.=&Apache::loncommon::plainname($uname,$udom);
10278: 	    }
10279: 	    $number++;
10280: 	}
10281:         $result.="</p>\n";
10282:         if ($number==0) {
10283:             $result .=
10284:                  &Apache::lonhtmlcommon::confirm_success(
10285:                      &mt('No IDs found to determine correct answer'),1);
10286:             return $result;
10287:         }
10288:     }
10289:     if (length($env{'form.upfile'}) < 2) {
10290:         $result .=
10291:             &Apache::lonhtmlcommon::confirm_success(
10292:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
10293:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
10294:         return $result;
10295:     }
10296: 
10297: # Were able to get all the info needed, now analyze the file
10298: 
10299:     $result.=&Apache::loncommon::studentbrowser_javascript();
10300:     $symb = &Apache::lonenc::check_encrypt($symb);
10301:     $result.=&Apache::loncommon::start_data_table().
10302:              &Apache::loncommon::start_data_table_header_row().
10303:              '<th>'.&mt('Evaluate clicker file').'</th>'.
10304:              &Apache::loncommon::end_data_table_header_row().
10305:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
10306: <td>
10307: <form method="post" action="/adm/grades" name="clickeranalysis">
10308: <input type="hidden" name="symb" value="$symb" />
10309: <input type="hidden" name="command" value="assignclickergrades" />
10310: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
10311: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
10312: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
10313: ENDHEADER
10314:     if ($env{'form.gradingmechanism'} eq 'given') {
10315:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
10316:     } 
10317:     my %responses;
10318:     my @questiontitles;
10319:     my $errormsg='';
10320:     my $number=0;
10321:     if ($env{'form.upfiletype'} eq 'iclicker') {
10322: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
10323:     }
10324:     if ($env{'form.upfiletype'} eq 'interwrite') {
10325:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
10326:     }
10327:     if ($env{'form.upfiletype'} eq 'turning') {
10328:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
10329:     }
10330:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
10331:              '<input type="hidden" name="number" value="'.$number.'" />'.
10332:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
10333:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
10334:              '<br />';
10335:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
10336:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
10337:        return $result;
10338:     } 
10339: # Remember Question Titles
10340: # FIXME: Possibly need delimiter other than ":"
10341:     for (my $i=0;$i<$number;$i++) {
10342:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
10343:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
10344:     }
10345:     my $correct_count=0;
10346:     my $student_count=0;
10347:     my $unknown_count=0;
10348: # Match answers with usernames
10349: # FIXME: Possibly need delimiter other than ":"
10350:     foreach my $id (keys(%responses)) {
10351:        if ($correct_ids{$id}) {
10352:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
10353:           $correct_count++;
10354:        } elsif ($clicker_ids{$id}) {
10355:           if ($clicker_ids{$id}=~/\,/) {
10356: # More than one user with the same clicker!
10357:              $result.="</td>".&Apache::loncommon::end_data_table_row().
10358:                            &Apache::loncommon::start_data_table_row()."<td>".
10359:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
10360:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10361:                            "<select name='multi".$id."'>";
10362:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
10363:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
10364:              }
10365:              $result.='</select>';
10366:              $unknown_count++;
10367:           } else {
10368: # Good: found one and only one user with the right clicker
10369:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
10370:              $student_count++;
10371:           }
10372:        } else {
10373:           $result.="</td>".&Apache::loncommon::end_data_table_row().
10374:                            &Apache::loncommon::start_data_table_row()."<td>".
10375:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
10376:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10377:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
10378:                    "\n".&mt("Domain").": ".
10379:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
10380:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
10381:           $unknown_count++;
10382:        }
10383:     }
10384:     $result.='<hr />'.
10385:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
10386:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
10387:        if ($correct_count==0) {
10388:           $errormsg.="Found no correct answers for grading!";
10389:        } elsif ($correct_count>1) {
10390:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
10391:        }
10392:     }
10393:     if ($number<1) {
10394:        $errormsg.="Found no questions.";
10395:     }
10396:     if ($errormsg) {
10397:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
10398:     } else {
10399:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
10400:     }
10401:     $result.='</form></td>'.
10402:              &Apache::loncommon::end_data_table_row().
10403:              &Apache::loncommon::end_data_table();
10404:     return $result;
10405: }
10406: 
10407: sub iclicker_eval {
10408:     my ($questiontitles,$responses)=@_;
10409:     my $number=0;
10410:     my $errormsg='';
10411:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10412:         my %components=&Apache::loncommon::record_sep($line);
10413:         my @entries=map {$components{$_}} (sort(keys(%components)));
10414: 	if ($entries[0] eq 'Question') {
10415: 	    for (my $i=3;$i<$#entries;$i+=6) {
10416: 		$$questiontitles[$number]=$entries[$i];
10417: 		$number++;
10418: 	    }
10419: 	}
10420: 	if ($entries[0]=~/^\#/) {
10421: 	    my $id=$entries[0];
10422: 	    my @idresponses;
10423: 	    $id=~s/^[\#0]+//;
10424: 	    for (my $i=0;$i<$number;$i++) {
10425: 		my $idx=3+$i*6;
10426:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
10427: 		push(@idresponses,$entries[$idx]);
10428: 	    }
10429: 	    $$responses{$id}=join(',',@idresponses);
10430: 	}
10431:     }
10432:     return ($errormsg,$number);
10433: }
10434: 
10435: sub interwrite_eval {
10436:     my ($questiontitles,$responses)=@_;
10437:     my $number=0;
10438:     my $errormsg='';
10439:     my $skipline=1;
10440:     my $questionnumber=0;
10441:     my %idresponses=();
10442:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10443:         my %components=&Apache::loncommon::record_sep($line);
10444:         my @entries=map {$components{$_}} (sort(keys(%components)));
10445:         if ($entries[1] eq 'Time') { $skipline=0; next; }
10446:         if ($entries[1] eq 'Response') { $skipline=1; }
10447:         next if $skipline;
10448:         if ($entries[0]!=$questionnumber) {
10449:            $questionnumber=$entries[0];
10450:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
10451:            $number++;
10452:         }
10453:         my $id=$entries[4];
10454:         $id=~s/^[\#0]+//;
10455:         $id=~s/^v\d*\://i;
10456:         $id=~s/[\-\:]//g;
10457:         $idresponses{$id}[$number]=$entries[6];
10458:     }
10459:     foreach my $id (keys(%idresponses)) {
10460:        $$responses{$id}=join(',',@{$idresponses{$id}});
10461:        $$responses{$id}=~s/^\s*\,//;
10462:     }
10463:     return ($errormsg,$number);
10464: }
10465: 
10466: sub turning_eval {
10467:     my ($questiontitles,$responses)=@_;
10468:     my $number=0;
10469:     my $errormsg='';
10470:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10471:         my %components=&Apache::loncommon::record_sep($line);
10472:         my @entries=map {$components{$_}} (sort(keys(%components)));
10473:         if ($#entries>$number) { $number=$#entries; }
10474:         my $id=$entries[0];
10475:         my @idresponses;
10476:         $id=~s/^[\#0]+//;
10477:         unless ($id) { next; }
10478:         for (my $idx=1;$idx<=$#entries;$idx++) {
10479:             $entries[$idx]=~s/\,/\;/g;
10480:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
10481:             push(@idresponses,$entries[$idx]);
10482:         }
10483:         $$responses{$id}=join(',',@idresponses);
10484:     }
10485:     for (my $i=1; $i<=$number; $i++) {
10486:         $$questiontitles[$i]=&mt('Question [_1]',$i);
10487:     }
10488:     return ($errormsg,$number);
10489: }
10490: 
10491: 
10492: sub assign_clicker_grades {
10493:     my ($r,$symb)=@_;
10494:     if (!$symb) {return '';}
10495: # See which part we are saving to
10496:     my $res_error;
10497:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
10498:     if ($res_error) {
10499:         return &navmap_errormsg();
10500:     }
10501: # FIXME: This should probably look for the first handgradeable part
10502:     my $part=$$partlist[0];
10503: # Start screen output
10504:     my $result=&Apache::loncommon::start_data_table().
10505:              &Apache::loncommon::start_data_table_header_row().
10506:              '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
10507:              &Apache::loncommon::end_data_table_header_row().
10508:              &Apache::loncommon::start_data_table_row().'<td>';
10509: # Get correct result
10510: # FIXME: Possibly need delimiter other than ":"
10511:     my @correct=();
10512:     my $gradingmechanism=$env{'form.gradingmechanism'};
10513:     my $number=$env{'form.number'};
10514:     if ($gradingmechanism ne 'attendance') {
10515:        foreach my $key (keys(%env)) {
10516:           if ($key=~/^form\.correct\:/) {
10517:              my @input=split(/\,/,$env{$key});
10518:              for (my $i=0;$i<=$#input;$i++) {
10519:                  if (($correct[$i]) && ($input[$i]) &&
10520:                      ($correct[$i] ne $input[$i])) {
10521:                     $result.='<br /><span class="LC_warning">'.
10522:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
10523:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
10524:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
10525:                     $correct[$i]=$input[$i];
10526:                  }
10527:              }
10528:           }
10529:        }
10530:        for (my $i=0;$i<$number;$i++) {
10531:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
10532:              $result.='<br /><span class="LC_error">'.
10533:                       &mt('No correct result given for question "[_1]"!',
10534:                           $env{'form.question:'.$i}).'</span>';
10535:           }
10536:        }
10537:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
10538:     }
10539: # Start grading
10540:     my $pcorrect=$env{'form.pcorrect'};
10541:     my $pincorrect=$env{'form.pincorrect'};
10542:     my $storecount=0;
10543:     my %users=();
10544:     foreach my $key (keys(%env)) {
10545:        my $user='';
10546:        if ($key=~/^form\.student\:(.*)$/) {
10547:           $user=$1;
10548:        }
10549:        if ($key=~/^form\.unknown\:(.*)$/) {
10550:           my $id=$1;
10551:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
10552:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
10553:           } elsif ($env{'form.multi'.$id}) {
10554:              $user=$env{'form.multi'.$id};
10555:           }
10556:        }
10557:        if ($user) {
10558:           if ($users{$user}) {
10559:              $result.='<br /><span class="LC_warning">'.
10560:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
10561:                       '</span><br />';
10562:           }
10563:           $users{$user}=1; 
10564:           my @answer=split(/\,/,$env{$key});
10565:           my $sum=0;
10566:           my $realnumber=$number;
10567:           for (my $i=0;$i<$number;$i++) {
10568:              if  ($correct[$i] eq '-') {
10569:                 $realnumber--;
10570:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/))  {
10571:                 if ($gradingmechanism eq 'attendance') {
10572:                    $sum+=$pcorrect;
10573:                 } elsif ($correct[$i] eq '*') {
10574:                    $sum+=$pcorrect;
10575:                 } else {
10576: # We actually grade if correct or not
10577:                    my $increment=$pincorrect;
10578: # Special case: numerical answer "0"
10579:                    if ($correct[$i] eq '0') {
10580:                       if ($answer[$i]=~/^[0\.]+$/) {
10581:                          $increment=$pcorrect;
10582:                       }
10583: # General numerical answer, both evaluate to something non-zero
10584:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
10585:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
10586:                          $increment=$pcorrect;
10587:                       }
10588: # Must be just alphanumeric
10589:                    } elsif ($answer[$i] eq $correct[$i]) {
10590:                       $increment=$pcorrect;
10591:                    }
10592:                    $sum+=$increment;
10593:                 }
10594:              }
10595:           }
10596:           my $ave=$sum/(100*$realnumber);
10597: # Store
10598:           my ($username,$domain)=split(/\:/,$user);
10599:           my %grades=();
10600:           $grades{"resource.$part.solved"}='correct_by_override';
10601:           $grades{"resource.$part.awarded"}=$ave;
10602:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
10603:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
10604:                                                  $env{'request.course.id'},
10605:                                                  $domain,$username);
10606:           if ($returncode ne 'ok') {
10607:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
10608:           } else {
10609:              $storecount++;
10610:           }
10611:        }
10612:     }
10613: # We are done
10614:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
10615:              '</td>'.
10616:              &Apache::loncommon::end_data_table_row().
10617:              &Apache::loncommon::end_data_table();
10618:     return $result;
10619: }
10620: 
10621: sub navmap_errormsg {
10622:     return '<div class="LC_error">'.
10623:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
10624:            &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>').
10625:            '</div>';
10626: }
10627: 
10628: sub startpage {
10629:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js) = @_;
10630:     if ($nomenu) {
10631:         $r->print(&Apache::loncommon::start_page("Student's Version",$js,{'only_body' => '1'}));
10632:     } else {
10633:         unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
10634:         $r->print(&Apache::loncommon::start_page('Grading',$js,
10635:                                                  {'bread_crumbs' => $crumbs}));
10636:         &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
10637:     }
10638:     unless ($nodisplayflag) {
10639:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
10640:     }
10641: }
10642: 
10643: sub select_problem {
10644:     my ($r)=@_;
10645:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
10646:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1,undef,undef,undef,undef,1));
10647:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
10648:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
10649: }
10650: 
10651: sub handler {
10652:     my $request=$_[0];
10653:     &reset_caches();
10654:     if ($request->header_only) {
10655:         &Apache::loncommon::content_type($request,'text/html');
10656:         $request->send_http_header;
10657:         return OK;
10658:     }
10659:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
10660: 
10661: # see what command we need to execute
10662: 
10663:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
10664:     my $command=$commands[0];
10665: 
10666:     &init_perm();
10667:     if (!$env{'request.course.id'}) {
10668:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
10669:                 ($command =~ /^scantronupload/)) {
10670:             # Not in a course.
10671:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
10672:             return HTTP_NOT_ACCEPTABLE;
10673:         }
10674:     } elsif (!%perm) {
10675:         $request->internal_redirect('/adm/quickgrades');
10676:         return OK;
10677:     }
10678:     &Apache::loncommon::content_type($request,'text/html');
10679:     $request->send_http_header;
10680: 
10681:     if ($#commands > 0) {
10682: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
10683:     }
10684: 
10685: # see what the symb is
10686: 
10687:     my $symb=$env{'form.symb'};
10688:     unless ($symb) {
10689:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
10690:        $symb=&Apache::lonnet::symbread($url);
10691:     }
10692:     &Apache::lonenc::check_decrypt(\$symb);
10693: 
10694:     $ssi_error = 0;
10695:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
10696: #
10697: # Not called from a resource, but inside a course
10698: #    
10699:         &startpage($request,undef,[],1,1);
10700:         &select_problem($request);
10701:     } else {
10702: 	if ($command eq 'submission' && $perm{'vgr'}) {
10703:             my ($stuvcurrent,$stuvdisp,$versionform,$js);
10704:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
10705:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
10706:                     &choose_task_version_form($symb,$env{'form.student'},
10707:                                               $env{'form.userdom'});
10708:             }
10709:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
10710:             if ($versionform) {
10711:                 $request->print($versionform);
10712:             }
10713:             $request->print('<br clear="all" />');
10714: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
10715:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
10716:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
10717:                 &choose_task_version_form($symb,$env{'form.student'},
10718:                                           $env{'form.userdom'},
10719:                                           $env{'form.inhibitmenu'});
10720:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
10721:             if ($versionform) {
10722:                 $request->print($versionform);
10723:             }
10724:             $request->print('<br clear="all" />');
10725:             $request->print(&show_previous_task_version($request,$symb));
10726: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
10727:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10728:                                        {href=>'',text=>'Select student'}],1,1);
10729: 	    &pickStudentPage($request,$symb);
10730: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
10731:             &startpage($request,$symb,
10732:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10733:                                        {href=>'',text=>'Select student'},
10734:                                        {href=>'',text=>'Grade student'}],1,1);
10735: 	    &displayPage($request,$symb);
10736: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
10737:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10738:                                        {href=>'',text=>'Select student'},
10739:                                        {href=>'',text=>'Grade student'},
10740:                                        {href=>'',text=>'Store grades'}],1,1);
10741: 	    &updateGradeByPage($request,$symb);
10742: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
10743:             &startpage($request,$symb,[{href=>'',text=>'...'},
10744:                                        {href=>'',text=>'Modify grades'}]);
10745: 	    &processGroup($request,$symb);
10746: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
10747:             &startpage($request,$symb);
10748: 	    $request->print(&grading_menu($request,$symb));
10749: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
10750:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
10751: 	    $request->print(&submit_options($request,$symb));
10752:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
10753:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
10754:             $request->print(&listStudents($request,$symb,'graded'));
10755:         } elsif ($command eq 'table' && $perm{'vgr'}) {
10756:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
10757:             $request->print(&submit_options_table($request,$symb));
10758:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
10759:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
10760:             $request->print(&submit_options_sequence($request,$symb));
10761: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
10762:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
10763: 	    $request->print(&viewgrades($request,$symb));
10764: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
10765:             &startpage($request,$symb,[{href=>'',text=>'...'},
10766:                                        {href=>'',text=>'Store grades'}]);
10767: 	    $request->print(&processHandGrade($request,$symb));
10768: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
10769:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
10770:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
10771:                                                                              text=>"Modify grades"},
10772:                                        {href=>'', text=>"Store grades"}]);
10773: 	    $request->print(&editgrades($request,$symb));
10774:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
10775:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
10776:             $request->print(&initialverifyreceipt($request,$symb));
10777: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
10778:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
10779:                                        {href=>'',text=>'Verification Result'}]);
10780: 	    $request->print(&verifyreceipt($request,$symb));
10781:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
10782:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
10783:             $request->print(&process_clicker($request,$symb));
10784:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
10785:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
10786:                                        {href=>'', text=>'Process clicker file'}]);
10787:             $request->print(&process_clicker_file($request,$symb));
10788:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
10789:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
10790:                                        {href=>'', text=>'Process clicker file'},
10791:                                        {href=>'', text=>'Store grades'}]);
10792:             $request->print(&assign_clicker_grades($request,$symb));
10793: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
10794:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10795: 	    $request->print(&upcsvScores_form($request,$symb));
10796: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
10797:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10798: 	    $request->print(&csvupload($request,$symb));
10799: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
10800:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10801: 	    $request->print(&csvuploadmap($request,$symb));
10802: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
10803: 	    if ($env{'form.associate'} ne 'Reverse Association') {
10804:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10805: 		$request->print(&csvuploadoptions($request,$symb));
10806: 	    } else {
10807: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
10808: 		    $env{'form.upfile_associate'} = 'reverse';
10809: 		} else {
10810: 		    $env{'form.upfile_associate'} = 'forward';
10811: 		}
10812:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10813: 		$request->print(&csvuploadmap($request,$symb));
10814: 	    }
10815: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
10816:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10817: 	    $request->print(&csvuploadassign($request,$symb));
10818: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
10819:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10820: 	    $request->print(&scantron_selectphase($request,undef,$symb));
10821:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
10822:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10823:  	    $request->print(&scantron_do_warning($request,$symb));
10824: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
10825:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10826: 	    $request->print(&scantron_validate_file($request,$symb));
10827: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
10828:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10829: 	    $request->print(&scantron_process_students($request,$symb));
10830:  	} elsif ($command eq 'scantronupload' && 
10831:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10832: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10833:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10834:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
10835:  	} elsif ($command eq 'scantronupload_save' &&
10836:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10837: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10838:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10839:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
10840:  	} elsif ($command eq 'scantron_download' &&
10841: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
10842:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10843:  	    $request->print(&scantron_download_scantron_data($request,$symb));
10844:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
10845:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10846:             $request->print(&checkscantron_results($request,$symb));
10847:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
10848:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
10849:             $request->print(&submit_options_download($request,$symb));
10850:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
10851:             &startpage($request,$symb,
10852:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
10853:     {href=>'', text=>'Download submitted files'}]);
10854:             &submit_download_link($request,$symb);
10855: 	} elsif ($command) {
10856:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
10857: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
10858: 	}
10859:     }
10860:     if ($ssi_error) {
10861: 	&ssi_print_error($request);
10862:     }
10863:     if ($env{'form.inhibitmenu'}) {
10864:         $request->print(&Apache::loncommon::end_page());
10865:     } else {
10866:         &Apache::lonquickgrades::endGradeScreen($request);
10867:     }
10868:     &reset_caches();
10869:     return OK;
10870: }
10871: 
10872: 1;
10873: 
10874: __END__;
10875: 
10876: 
10877: =head1 NAME
10878: 
10879: Apache::grades
10880: 
10881: =head1 SYNOPSIS
10882: 
10883: Handles the viewing of grades.
10884: 
10885: This is part of the LearningOnline Network with CAPA project
10886: described at http://www.lon-capa.org.
10887: 
10888: =head1 OVERVIEW
10889: 
10890: Do an ssi with retries:
10891: While I'd love to factor out this with the version in lonprintout,
10892: 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
10893: I'm not quite ready to invent (e.g. an ssi_with_retry object).
10894: 
10895: At least the logic that drives this has been pulled out into loncommon.
10896: 
10897: 
10898: 
10899: ssi_with_retries - Does the server side include of a resource.
10900:                      if the ssi call returns an error we'll retry it up to
10901:                      the number of times requested by the caller.
10902:                      If we still have a problem, no text is appended to the
10903:                      output and we set some global variables.
10904:                      to indicate to the caller an SSI error occurred.  
10905:                      All of this is supposed to deal with the issues described
10906:                      in LON-CAPA BZ 5631 see:
10907:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
10908:                      by informing the user that this happened.
10909: 
10910: Parameters:
10911:   resource   - The resource to include.  This is passed directly, without
10912:                interpretation to lonnet::ssi.
10913:   form       - The form hash parameters that guide the interpretation of the resource
10914:                
10915:   retries    - Number of retries allowed before giving up completely.
10916: Returns:
10917:   On success, returns the rendered resource identified by the resource parameter.
10918: Side Effects:
10919:   The following global variables can be set:
10920:    ssi_error                - If an unrecoverable error occurred this becomes true.
10921:                               It is up to the caller to initialize this to false
10922:                               if desired.
10923:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
10924:                               of the resource that could not be rendered by the ssi
10925:                               call.
10926:    ssi_error_message   - The error string fetched from the ssi response
10927:                               in the event of an error.
10928: 
10929: 
10930: =head1 HANDLER SUBROUTINE
10931: 
10932: ssi_with_retries()
10933: 
10934: =head1 SUBROUTINES
10935: 
10936: =over
10937: 
10938: =head1 Routines to display previous version of a Task for a specific student
10939: 
10940: Tasks are graded pass/fail. Students who have yet to pass a particular Task
10941: can receive another opportunity. Access to tasks is slot-based. If a slot
10942: requires a proctor to check-in the student, a new version of the Task will
10943: be created when the student is checked in to the new opportunity.
10944: 
10945: If a particular student has tried two or more versions of a particular task,
10946: the submission screen provides a user with vgr privileges (e.g., a Course
10947: Coordinator) the ability to display a previous version worked on by the
10948: student.  By default, the current version is displayed. If a previous version
10949: has been selected for display, submission data are only shown that pertain
10950: to that particular version, and the interface to submit grades is not shown.
10951: 
10952: =over 4
10953: 
10954: =item show_previous_task_version()
10955: 
10956: Displays a specified version of a student's Task, as the student sees it.
10957: 
10958: Inputs: 2
10959:         request - request object
10960:         symb    - unique symb for current instance of resource
10961: 
10962: Output: None.
10963: 
10964: Side Effects: calls &show_problem() to print version of Task, with
10965:               version contained in form item: $env{'form.previousversion'}
10966: 
10967: =item choose_task_version_form()
10968: 
10969: Displays a web form used to select which version of a student's view of a
10970: Task should be displayed.  Either launches a pop-up window, or replaces
10971: content in existing pop-up, or replaces page in main window.
10972: 
10973: Inputs: 4
10974:         symb    - unique symb for current instance of resource
10975:         uname   - username of student
10976:         udom    - domain of student
10977:         nomenu  - 1 if display is in a pop-up window, and hence no menu
10978:                   breadcrumbs etc., are displayed
10979: 
10980: Output: 4
10981:         current   - student's current version
10982:         displayed - student's version being displayed
10983:         result    - scalar containing HTML for web form used to switch to
10984:                     a different version (or a link to close window, if pop-up).
10985:         js        - javascript for processing selection in versions web form
10986: 
10987: Side Effects: None.
10988: 
10989: =item previous_display_javascript()
10990: 
10991: Inputs: 2
10992:         nomenu  - 1 if display is in a pop-up window, and hence no menu
10993:                   breadcrumbs etc., are displayed.
10994:         current - student's current version number.
10995: 
10996: Output: 1
10997:         js      - javascript for processing selection in versions web form.
10998: 
10999: Side Effects: None.
11000: 
11001: =back
11002: 
11003: =head1 Routines to process bubblesheet data.
11004: 
11005: =over 4
11006: 
11007: =item scantron_get_correction() : 
11008: 
11009:    Builds the interface screen to interact with the operator to fix a
11010:    specific error condition in a specific scanline
11011: 
11012:  Arguments:
11013:     $r           - Apache request object
11014:     $i           - number of the current scanline
11015:     $scan_record - hash ref as returned from &scantron_parse_scanline()
11016:     $scan_config - hash ref as returned from &get_scantron_config()
11017:     $line        - full contents of the current scanline
11018:     $error       - error condition, valid values are
11019:                    'incorrectCODE', 'duplicateCODE',
11020:                    'doublebubble', 'missingbubble',
11021:                    'duplicateID', 'incorrectID'
11022:     $arg         - extra information needed
11023:        For errors:
11024:          - duplicateID   - paper number that this studentID was seen before on
11025:          - duplicateCODE - array ref of the paper numbers this CODE was
11026:                            seen on before
11027:          - incorrectCODE - current incorrect CODE 
11028:          - doublebubble  - array ref of the bubble lines that have double
11029:                            bubble errors
11030:          - missingbubble - array ref of the bubble lines that have missing
11031:                            bubble errors
11032: 
11033:    $randomorder - True if exam folder has randomorder set
11034:    $randompick  - True if exam folder has randompick set
11035:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
11036:                      for current line to question number used for same question
11037:                      in "Master Seqence" (as seen by Course Coordinator).
11038:    $startline   - Reference to hash where key is question number (0 is first)
11039:                   and value is number of first bubble line for current student
11040:                   or code-based randompick and/or randomorder.
11041: 
11042: 
11043: 
11044: =item  scantron_get_maxbubble() : 
11045: 
11046:    Arguments:
11047:        $nav_error  - Reference to scalar which is a flag to indicate a
11048:                       failure to retrieve a navmap object.
11049:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
11050:        calling routine should trap the error condition and display the warning
11051:        found in &navmap_errormsg().
11052: 
11053:        $scantron_config - Reference to bubblesheet format configuration hash.
11054: 
11055:    Returns the maximum number of bubble lines that are expected to
11056:    occur. Does this by walking the selected sequence rendering the
11057:    resource and then checking &Apache::lonxml::get_problem_counter()
11058:    for what the current value of the problem counter is.
11059: 
11060:    Caches the results to $env{'form.scantron_maxbubble'},
11061:    $env{'form.scantron.bubble_lines.n'}, 
11062:    $env{'form.scantron.first_bubble_line.n'} and
11063:    $env{"form.scantron.sub_bubblelines.n"}
11064:    which are the total number of bubble lines, the number of bubble
11065:    lines for response n and number of the first bubble line for response n,
11066:    and a comma separated list of numbers of bubble lines for sub-questions
11067:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
11068: 
11069: 
11070: =item  scantron_validate_missingbubbles() : 
11071: 
11072:    Validates all scanlines in the selected file to not have any
11073:     answers that don't have bubbles that have not been verified
11074:     to be bubble free.
11075: 
11076: =item  scantron_process_students() : 
11077: 
11078:    Routine that does the actual grading of the bubblesheet information.
11079: 
11080:    The parsed scanline hash is added to %env 
11081: 
11082:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
11083:    foreach resource , with the form data of
11084: 
11085: 	'submitted'     =>'scantron' 
11086: 	'grade_target'  =>'grade',
11087: 	'grade_username'=> username of student
11088: 	'grade_domain'  => domain of student
11089: 	'grade_courseid'=> of course
11090: 	'grade_symb'    => symb of resource to grade
11091: 
11092:     This triggers a grading pass. The problem grading code takes care
11093:     of converting the bubbled letter information (now in %env) into a
11094:     valid submission.
11095: 
11096: =item  scantron_upload_scantron_data() :
11097: 
11098:     Creates the screen for adding a new bubblesheet data file to a course.
11099: 
11100: =item  scantron_upload_scantron_data_save() : 
11101: 
11102:    Adds a provided bubble information data file to the course if user
11103:    has the correct privileges to do so. 
11104: 
11105: =item  valid_file() :
11106: 
11107:    Validates that the requested bubble data file exists in the course.
11108: 
11109: =item  scantron_download_scantron_data() : 
11110: 
11111:    Shows a list of the three internal files (original, corrected,
11112:    skipped) for a specific bubblesheet data file that exists in the
11113:    course.
11114: 
11115: =item  scantron_validate_ID() : 
11116: 
11117:    Validates all scanlines in the selected file to not have any
11118:    invalid or underspecified student/employee IDs
11119: 
11120: =item navmap_errormsg() :
11121: 
11122:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
11123:    Should be called whenever the request to instantiate a navmap object fails.
11124: 
11125: =back
11126: 
11127: =back
11128: 
11129: =cut

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