File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.732: download - view: text, annotated - select for diffs
Sun Feb 22 01:34:48 2015 UTC (9 years, 2 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6476
  - Store rawrndseed for parts with all responsetypes.
  - Eliminate storage of rndseed, since rawrndseed is the item needed to
    reconstruct the randomization for a problem in Authoring Space.
  - If questiontype is randomizetry rawrndseed and rndseed are the same,
    so use rawrndseed from the submission history, where it exists.
  - Support use of randomizetry for script blocks outside a part block in
    problems with a single <part></part> tag.
  - Support use of randomizetry for script blocks inside part blocks.
Note: randomizetry does not apply to randomization in script blocks
outside part blocks for problems with multiple parts, because the
number of tries is not uniquely defined.

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.732 2015/02/22 01:34:48 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: 
   30: 
   31: package Apache::grades;
   32: use strict;
   33: use Apache::style;
   34: use Apache::lonxml;
   35: use Apache::lonnet;
   36: use Apache::loncommon;
   37: use Apache::lonhtmlcommon;
   38: use Apache::lonnavmaps;
   39: use Apache::lonhomework;
   40: use Apache::lonpickcode;
   41: use Apache::loncoursedata;
   42: use Apache::lonmsg();
   43: use Apache::Constants qw(:common :http);
   44: use Apache::lonlocal;
   45: use Apache::lonenc;
   46: use Apache::lonstathelpers;
   47: use Apache::lonquickgrades;
   48: use Apache::bridgetask();
   49: use String::Similarity;
   50: use LONCAPA;
   51: 
   52: use POSIX qw(floor);
   53: 
   54: 
   55: 
   56: my %perm=();
   57: my %old_essays=();
   58: 
   59: #  These variables are used to recover from ssi errors
   60: 
   61: my $ssi_retries = 5;
   62: my $ssi_error;
   63: my $ssi_error_resource;
   64: my $ssi_error_message;
   65: 
   66: 
   67: sub ssi_with_retries {
   68:     my ($resource, $retries, %form) = @_;
   69:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
   70:     if ($response->is_error) {
   71: 	$ssi_error          = 1;
   72: 	$ssi_error_resource = $resource;
   73: 	$ssi_error_message  = $response->code . " " . $response->message;
   74:     }
   75: 
   76:     return $content;
   77: 
   78: }
   79: #
   80: #  Prodcuces an ssi retry failure error message to the user:
   81: #
   82: 
   83: sub ssi_print_error {
   84:     my ($r) = @_;
   85:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
   86:     $r->print('
   87: <br />
   88: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
   89: <p>
   90: '.&mt('Unable to retrieve a resource from a server:').'<br />
   91: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
   92: '.&mt('Error:').' '.$ssi_error_message.'
   93: </p>
   94: <p>'.
   95: &mt('It is recommended that you try again later, as this error may mean the server was just temporarily unavailable, or is down for maintenance.').'<br />'.
   96: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
   97: '</p>');
   98:     return;
   99: }
  100: 
  101: #
  102: # --- Retrieve the parts from the metadata file.---
  103: # Returns an array of everything that the resources stores away
  104: #
  105: 
  106: sub getpartlist {
  107:     my ($symb,$errorref) = @_;
  108: 
  109:     my $navmap   = Apache::lonnavmaps::navmap->new();
  110:     unless (ref($navmap)) {
  111:         if (ref($errorref)) { 
  112:             $$errorref = 'navmap';
  113:             return;
  114:         }
  115:     }
  116:     my $res      = $navmap->getBySymb($symb);
  117:     my $partlist = $res->parts();
  118:     my $url      = $res->src();
  119:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
  120: 
  121:     my @stores;
  122:     foreach my $part (@{ $partlist }) {
  123: 	foreach my $key (@metakeys) {
  124: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
  125: 	}
  126:     }
  127:     return @stores;
  128: }
  129: 
  130: #--- Format fullname, username:domain if different for display
  131: #--- Use anywhere where the student names are listed
  132: sub nameUserString {
  133:     my ($type,$fullname,$uname,$udom) = @_;
  134:     if ($type eq 'header') {
  135: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
  136:     } else {
  137: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
  138: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
  139:     }
  140: }
  141: 
  142: #--- Get the partlist and the response type for a given problem. ---
  143: #--- Indicate if a response type is coded handgraded or not. ---
  144: #--- Sets response_error pointer to "1" if navmaps object broken ---
  145: sub response_type {
  146:     my ($symb,$response_error) = @_;
  147: 
  148:     my $navmap = Apache::lonnavmaps::navmap->new();
  149:     unless (ref($navmap)) {
  150:         if (ref($response_error)) {
  151:             $$response_error = 1;
  152:         }
  153:         return;
  154:     }
  155:     my $res = $navmap->getBySymb($symb);
  156:     unless (ref($res)) {
  157:         $$response_error = 1;
  158:         return;
  159:     }
  160:     my $partlist = $res->parts();
  161:     my %vPart = 
  162: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
  163:     my (%response_types,%handgrade);
  164:     foreach my $part (@{ $partlist }) {
  165: 	next if (%vPart && !exists($vPart{$part}));
  166: 
  167: 	my @types = $res->responseType($part);
  168: 	my @ids = $res->responseIds($part);
  169: 	for (my $i=0; $i < scalar(@ids); $i++) {
  170: 	    $response_types{$part}{$ids[$i]} = $types[$i];
  171: 	    $handgrade{$part.'_'.$ids[$i]} = 
  172: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
  173: 				     '.handgrade',$symb);
  174: 	}
  175:     }
  176:     return ($partlist,\%handgrade,\%response_types);
  177: }
  178: 
  179: sub flatten_responseType {
  180:     my ($responseType) = @_;
  181:     my @part_response_id =
  182: 	map { 
  183: 	    my $part = $_;
  184: 	    map {
  185: 		[$part,$_]
  186: 		} sort(keys(%{ $responseType->{$part} }));
  187: 	} sort(keys(%$responseType));
  188:     return @part_response_id;
  189: }
  190: 
  191: sub get_display_part {
  192:     my ($partID,$symb)=@_;
  193:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
  194:     if (defined($display) and $display ne '') {
  195:         $display.= ' (<span class="LC_internal_info">'
  196:                   .&mt('Part ID: [_1]',$partID).'</span>)';
  197:     } else {
  198: 	$display=$partID;
  199:     }
  200:     return $display;
  201: }
  202: 
  203: sub reset_caches {
  204:     &reset_analyze_cache();
  205:     &reset_perm();
  206:     &reset_old_essays();
  207: }
  208: 
  209: {
  210:     my %analyze_cache;
  211:     my %analyze_cache_formkeys;
  212: 
  213:     sub reset_analyze_cache {
  214: 	undef(%analyze_cache);
  215:         undef(%analyze_cache_formkeys);
  216:     }
  217: 
  218:     sub get_analyze {
  219: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
  220: 	my $key = "$symb\0$uname\0$udom";
  221:         if ($type eq 'randomizetry') {
  222:             if ($trial ne '') {
  223:                 $key .= "\0".$trial;
  224:             }
  225:         }
  226: 	if (exists($analyze_cache{$key})) {
  227:             my $getupdate = 0;
  228:             if (ref($add_to_hash) eq 'HASH') {
  229:                 foreach my $item (keys(%{$add_to_hash})) {
  230:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
  231:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
  232:                             $getupdate = 1;
  233:                             last;
  234:                         }
  235:                     } else {
  236:                         $getupdate = 1;
  237:                     }
  238:                 }
  239:             }
  240:             if (!$getupdate) {
  241:                 return $analyze_cache{$key};
  242:             }
  243:         }
  244: 
  245: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  246: 	$url=&Apache::lonnet::clutter($url);
  247:         my %form = ('grade_target'      => 'analyze',
  248:                     'grade_domain'      => $udom,
  249:                     'grade_symb'        => $symb,
  250:                     'grade_courseid'    =>  $env{'request.course.id'},
  251:                     'grade_username'    => $uname,
  252:                     'grade_noincrement' => $no_increment);
  253:         if ($bubbles_per_row ne '') {
  254:             $form{'bubbles_per_row'} = $bubbles_per_row;
  255:         }
  256:         if ($type eq 'randomizetry') {
  257:             $form{'grade_questiontype'} = $type;
  258:             if ($rndseed ne '') {
  259:                 $form{'grade_rndseed'} = $rndseed;
  260:             }
  261:         }
  262:         if (ref($add_to_hash)) {
  263:             %form = (%form,%{$add_to_hash});
  264:         }
  265: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
  266: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  267: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  268:         if (ref($add_to_hash) eq 'HASH') {
  269:             $analyze_cache_formkeys{$key} = $add_to_hash;
  270:         } else {
  271:             $analyze_cache_formkeys{$key} = {};
  272:         }
  273: 	return $analyze_cache{$key} = \%analyze;
  274:     }
  275: 
  276:     sub get_order {
  277: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
  278: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
  279: 	return $analyze->{"$partid.$respid.shown"};
  280:     }
  281: 
  282:     sub get_radiobutton_correct_foil {
  283: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
  284: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
  285:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
  286:         if (ref($foils) eq 'ARRAY') {
  287: 	    foreach my $foil (@{$foils}) {
  288: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  289: 		    return $foil;
  290: 	        }
  291: 	    }
  292: 	}
  293:     }
  294: 
  295:     sub scantron_partids_tograde {
  296:         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row) = @_;
  297:         my (%analysis,@parts);
  298:         if (ref($resource)) {
  299:             my $symb = $resource->symb();
  300:             my $add_to_form;
  301:             if ($check_for_randomlist) {
  302:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
  303:             }
  304:             my $analyze = 
  305:                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
  306:                              undef,undef,undef,$bubbles_per_row);
  307:             if (ref($analyze) eq 'HASH') {
  308:                 %analysis = %{$analyze};
  309:             }
  310:             if (ref($analysis{'parts'}) eq 'ARRAY') {
  311:                 foreach my $part (@{$analysis{'parts'}}) {
  312:                     my ($id,$respid) = split(/\./,$part);
  313:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
  314:                         push(@parts,$part);
  315:                     }
  316:                 }
  317:             }
  318:         }
  319:         return (\%analysis,\@parts);
  320:     }
  321: 
  322: }
  323: 
  324: #--- Clean response type for display
  325: #--- Currently filters option/rank/radiobutton/match/essay/Task
  326: #        response types only.
  327: sub cleanRecord {
  328:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  329: 	$uname,$udom,$type,$trial,$rndseed) = @_;
  330:     my $grayFont = '<span class="LC_internal_info">';
  331:     if ($response =~ /^(option|rank)$/) {
  332: 	my %answer=&Apache::lonnet::str2hash($answer);
  333:         my @answer = %answer;
  334:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
  335: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  336: 	my ($toprow,$bottomrow);
  337: 	foreach my $foil (@$order) {
  338: 	    if ($grading{$foil} == 1) {
  339: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  340: 	    } else {
  341: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  342: 	    }
  343: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  344: 	}
  345: 	return '<blockquote><table border="1">'.
  346: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  347: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  348: 	    $bottomrow.'</tr></table></blockquote>';
  349:     } elsif ($response eq 'match') {
  350: 	my %answer=&Apache::lonnet::str2hash($answer);
  351:         my @answer = %answer;
  352:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
  353: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  354: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  355: 	my ($toprow,$middlerow,$bottomrow);
  356: 	foreach my $foil (@$order) {
  357: 	    my $item=shift(@items);
  358: 	    if ($grading{$foil} == 1) {
  359: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  360: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  361: 	    } else {
  362: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  363: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  364: 	    }
  365: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  366: 	}
  367: 	return '<blockquote><table border="1">'.
  368: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  369: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  370: 	    $middlerow.'</tr>'.
  371: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  372: 	    $bottomrow.'</tr></table></blockquote>';
  373:     } elsif ($response eq 'radiobutton') {
  374: 	my %answer=&Apache::lonnet::str2hash($answer);
  375:         my @answer = %answer;
  376:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
  377: 	my ($toprow,$bottomrow);
  378: 	my $correct = 
  379: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
  380: 	foreach my $foil (@$order) {
  381: 	    if (exists($answer{$foil})) {
  382: 		if ($foil eq $correct) {
  383: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  384: 		} else {
  385: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  386: 		}
  387: 	    } else {
  388: 		$toprow.='<td>'.&mt('false').'</td>';
  389: 	    }
  390: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  391: 	}
  392: 	return '<blockquote><table border="1">'.
  393: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  394: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  395: 	    $bottomrow.'</tr></table></blockquote>';
  396:     } elsif ($response eq 'essay') {
  397: 	if (! exists ($env{'form.'.$symb})) {
  398: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  399: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  400: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  401: 
  402: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  403: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  404: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  405: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  406: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  407: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  408: 	}
  409: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  410: 
  411:     } elsif ( $response eq 'organic') {
  412:         my $result=&mt('Smile representation: [_1]',
  413:                            '"<tt>'.&HTML::Entities::encode($answer, '"<>&').'</tt>"');
  414: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  415: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  416: 	return $result;
  417:     } elsif ( $response eq 'Task') {
  418: 	if ( $answer eq 'SUBMITTED') {
  419: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  420: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  421: 	    return $result;
  422: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  423: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  424: 			       keys(%{$record}));
  425: 	    return join('<br />',($version,@matches));
  426: 			       
  427: 			       
  428: 	} else {
  429: 	    my $result =
  430: 		'<p>'
  431: 		.&mt('Overall result: [_1]',
  432: 		     $record->{$version."resource.$respid.$partid.status"})
  433: 		.'</p>';
  434: 	    
  435: 	    $result .= '<ul>';
  436: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  437: 			     keys(%{$record}));
  438: 	    foreach my $grade (sort(@grade)) {
  439: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  440: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  441: 				     $dim, $record->{$grade}).
  442: 			  '</li>';
  443: 	    }
  444: 	    $result.='</ul>';
  445: 	    return $result;
  446: 	}
  447:     } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
  448:         # Respect multiple input fields, see Bug #5409
  449: 	$answer = 
  450: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  451: 							      $answer);
  452: 	return $answer;
  453:     }
  454:     return &HTML::Entities::encode($answer, '"<>&');
  455: }
  456: 
  457: #-- A couple of common js functions
  458: sub commonJSfunctions {
  459:     my $request = shift;
  460:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
  461:     function radioSelection(radioButton) {
  462: 	var selection=null;
  463: 	if (radioButton.length > 1) {
  464: 	    for (var i=0; i<radioButton.length; i++) {
  465: 		if (radioButton[i].checked) {
  466: 		    return radioButton[i].value;
  467: 		}
  468: 	    }
  469: 	} else {
  470: 	    if (radioButton.checked) return radioButton.value;
  471: 	}
  472: 	return selection;
  473:     }
  474: 
  475:     function pullDownSelection(selectOne) {
  476: 	var selection="";
  477: 	if (selectOne.length > 1) {
  478: 	    for (var i=0; i<selectOne.length; i++) {
  479: 		if (selectOne[i].selected) {
  480: 		    return selectOne[i].value;
  481: 		}
  482: 	    }
  483: 	} else {
  484:             // only one value it must be the selected one
  485: 	    return selectOne.value;
  486: 	}
  487:     }
  488: COMMONJSFUNCTIONS
  489: }
  490: 
  491: #--- Dumps the class list with usernames,list of sections,
  492: #--- section, ids and fullnames for each user.
  493: sub getclasslist {
  494:     my ($getsec,$filterlist,$getgroup) = @_;
  495:     my @getsec;
  496:     my @getgroup;
  497:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  498:     if (!ref($getsec)) {
  499: 	if ($getsec ne '' && $getsec ne 'all') {
  500: 	    @getsec=($getsec);
  501: 	}
  502:     } else {
  503: 	@getsec=@{$getsec};
  504:     }
  505:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  506:     if (!ref($getgroup)) {
  507: 	if ($getgroup ne '' && $getgroup ne 'all') {
  508: 	    @getgroup=($getgroup);
  509: 	}
  510:     } else {
  511: 	@getgroup=@{$getgroup};
  512:     }
  513:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  514: 
  515:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  516:     # Bail out if we were unable to get the classlist
  517:     return if (! defined($classlist));
  518:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  519:     #
  520:     my %sections;
  521:     my %fullnames;
  522:     foreach my $student (keys(%$classlist)) {
  523:         my $end      = 
  524:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  525:         my $start    = 
  526:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  527:         my $id       = 
  528:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  529:         my $section  = 
  530:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  531:         my $fullname = 
  532:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  533:         my $status   = 
  534:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  535:         my $group   = 
  536:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  537: 	# filter students according to status selected
  538: 	if ($filterlist && (!($stu_status =~ /Any/))) {
  539: 	    if (!($stu_status =~ $status)) {
  540: 		delete($classlist->{$student});
  541: 		next;
  542: 	    }
  543: 	}
  544: 	# filter students according to groups selected
  545: 	my @stu_groups = split(/,/,$group);
  546: 	if (@getgroup) {
  547: 	    my $exclude = 1;
  548: 	    foreach my $grp (@getgroup) {
  549: 	        foreach my $stu_group (@stu_groups) {
  550: 	            if ($stu_group eq $grp) {
  551: 	                $exclude = 0;
  552:     	            } 
  553: 	        }
  554:     	        if (($grp eq 'none') && !$group) {
  555:         	        $exclude = 0;
  556:         	}
  557: 	    }
  558: 	    if ($exclude) {
  559: 	        delete($classlist->{$student});
  560: 	    }
  561: 	}
  562: 	$section = ($section ne '' ? $section : 'none');
  563: 	if (&canview($section)) {
  564: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  565: 		$sections{$section}++;
  566: 		if ($classlist->{$student}) {
  567: 		    $fullnames{$student}=$fullname;
  568: 		}
  569: 	    } else {
  570: 		delete($classlist->{$student});
  571: 	    }
  572: 	} else {
  573: 	    delete($classlist->{$student});
  574: 	}
  575:     }
  576:     my %seen = ();
  577:     my @sections = sort(keys(%sections));
  578:     return ($classlist,\@sections,\%fullnames);
  579: }
  580: 
  581: sub canmodify {
  582:     my ($sec)=@_;
  583:     if ($perm{'mgr'}) {
  584: 	if (!defined($perm{'mgr_section'})) {
  585: 	    # can modify whole class
  586: 	    return 1;
  587: 	} else {
  588: 	    if ($sec eq $perm{'mgr_section'}) {
  589: 		#can modify the requested section
  590: 		return 1;
  591: 	    } else {
  592: 		# can't modify the request section
  593: 		return 0;
  594: 	    }
  595: 	}
  596:     }
  597:     #can't modify
  598:     return 0;
  599: }
  600: 
  601: sub canview {
  602:     my ($sec)=@_;
  603:     if ($perm{'vgr'}) {
  604: 	if (!defined($perm{'vgr_section'})) {
  605: 	    # can modify whole class
  606: 	    return 1;
  607: 	} else {
  608: 	    if ($sec eq $perm{'vgr_section'}) {
  609: 		#can modify the requested section
  610: 		return 1;
  611: 	    } else {
  612: 		# can't modify the request section
  613: 		return 0;
  614: 	    }
  615: 	}
  616:     }
  617:     #can't modify
  618:     return 0;
  619: }
  620: 
  621: #--- Retrieve the grade status of a student for all the parts
  622: sub student_gradeStatus {
  623:     my ($symb,$udom,$uname,$partlist) = @_;
  624:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  625:     my %partstatus = ();
  626:     foreach (@$partlist) {
  627: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  628: 	$status              = 'nothing' if ($status eq '');
  629: 	$partstatus{$_}      = $status;
  630: 	my $subkey           = "resource.$_.submitted_by";
  631: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  632:     }
  633:     return %partstatus;
  634: }
  635: 
  636: # hidden form and javascript that calls the form
  637: # Use by verifyscript and viewgrades
  638: # Shows a student's view of problem and submission
  639: sub jscriptNform {
  640:     my ($symb) = @_;
  641:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  642:     my $jscript= &Apache::lonhtmlcommon::scripttag(
  643: 	'    function viewOneStudent(user,domain) {'."\n".
  644: 	'	document.onestudent.student.value = user;'."\n".
  645: 	'	document.onestudent.userdom.value = domain;'."\n".
  646: 	'	document.onestudent.submit();'."\n".
  647: 	'    }'."\n".
  648: 	"\n");
  649:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  650: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  651: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  652: 	'<input type="hidden" name="command" value="submission" />'."\n".
  653: 	'<input type="hidden" name="student" value="" />'."\n".
  654: 	'<input type="hidden" name="userdom" value="" />'."\n".
  655: 	'</form>'."\n";
  656:     return $jscript;
  657: }
  658: 
  659: 
  660: 
  661: # Given the score (as a number [0-1] and the weight) what is the final
  662: # point value? This function will round to the nearest tenth, third,
  663: # or quarter if one of those is within the tolerance of .00001.
  664: sub compute_points {
  665:     my ($score, $weight) = @_;
  666:     
  667:     my $tolerance = .00001;
  668:     my $points = $score * $weight;
  669: 
  670:     # Check for nearness to 1/x.
  671:     my $check_for_nearness = sub {
  672:         my ($factor) = @_;
  673:         my $num = ($points * $factor) + $tolerance;
  674:         my $floored_num = floor($num);
  675:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  676:             return $floored_num / $factor;
  677:         }
  678:         return $points;
  679:     };
  680: 
  681:     $points = $check_for_nearness->(10);
  682:     $points = $check_for_nearness->(3);
  683:     $points = $check_for_nearness->(4);
  684:     
  685:     return $points;
  686: }
  687: 
  688: #------------------ End of general use routines --------------------
  689: 
  690: #
  691: # Find most similar essay
  692: #
  693: 
  694: sub most_similar {
  695:     my ($uname,$udom,$symb,$uessay)=@_;
  696: 
  697:     unless ($symb) { return ''; }
  698: 
  699:     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
  700: 
  701: # ignore spaces and punctuation
  702: 
  703:     $uessay=~s/\W+/ /gs;
  704: 
  705: # ignore empty submissions (occuring when only files are sent)
  706: 
  707:     unless ($uessay=~/\w+/s) { return ''; }
  708: 
  709: # these will be returned. Do not care if not at least 50 percent similar
  710:     my $limit=0.6;
  711:     my $sname='';
  712:     my $sdom='';
  713:     my $scrsid='';
  714:     my $sessay='';
  715: # go through all essays ...
  716:     foreach my $tkey (keys(%{$old_essays{$symb}})) {
  717: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  718: # ... except the same student
  719:         next if (($tname eq $uname) && ($tdom eq $udom));
  720: 	my $tessay=$old_essays{$symb}{$tkey};
  721: 	$tessay=~s/\W+/ /gs;
  722: # String similarity gives up if not even limit
  723: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  724: # Found one
  725: 	if ($tsimilar>$limit) {
  726: 	    $limit=$tsimilar;
  727: 	    $sname=$tname;
  728: 	    $sdom=$tdom;
  729: 	    $scrsid=$tcrsid;
  730: 	    $sessay=$old_essays{$symb}{$tkey};
  731: 	}
  732:     }
  733:     if ($limit>0.6) {
  734:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  735:     } else {
  736:        return ('','','','',0);
  737:     }
  738: }
  739: 
  740: #-------------------------------------------------------------------
  741: 
  742: #------------------------------------ Receipt Verification Routines
  743: #
  744: 
  745: sub initialverifyreceipt {
  746:    my ($request,$symb) = @_;
  747:    &commonJSfunctions($request);
  748:    return '<form name="gradingMenu" action=""><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
  749:         &Apache::lonnet::recprefix($env{'request.course.id'}).
  750:         '-<input type="text" name="receipt" size="4" />'.
  751:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  752:         '<input type="hidden" name="command" value="verify" />'.
  753:         "</form>\n";
  754: }
  755: 
  756: #--- Check whether a receipt number is valid.---
  757: sub verifyreceipt {
  758:     my ($request,$symb)  = @_;
  759: 
  760:     my $courseid = $env{'request.course.id'};
  761:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  762: 	$env{'form.receipt'};
  763:     $receipt     =~ s/[^\-\d]//g;
  764: 
  765:     my $title.=
  766: 	'<h3><span class="LC_info">'.
  767: 	&mt('Verifying Receipt Number [_1]',$receipt).
  768: 	'</span></h3>'."\n";
  769: 
  770:     my ($string,$contents,$matches) = ('','',0);
  771:     my (undef,undef,$fullname) = &getclasslist('all','0');
  772:     
  773:     my $receiptparts=0;
  774:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  775: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  776:     my $parts=['0'];
  777:     if ($receiptparts) {
  778:         my $res_error; 
  779:         ($parts)=&response_type($symb,\$res_error);
  780:         if ($res_error) {
  781:             return &navmap_errormsg();
  782:         } 
  783:     }
  784:     
  785:     my $header = 
  786: 	&Apache::loncommon::start_data_table().
  787: 	&Apache::loncommon::start_data_table_header_row().
  788: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  789: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  790: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  791:     if ($receiptparts) {
  792: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  793:     }
  794:     $header.=
  795: 	&Apache::loncommon::end_data_table_header_row();
  796: 
  797:     foreach (sort 
  798: 	     {
  799: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  800: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  801: 		 }
  802: 		 return $a cmp $b;
  803: 	     } (keys(%$fullname))) {
  804: 	my ($uname,$udom)=split(/\:/);
  805: 	foreach my $part (@$parts) {
  806: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  807: 		$contents.=
  808: 		    &Apache::loncommon::start_data_table_row().
  809: 		    '<td>&nbsp;'."\n".
  810: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  811: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  812: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  813: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  814: 		if ($receiptparts) {
  815: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  816: 		}
  817: 		$contents.= 
  818: 		    &Apache::loncommon::end_data_table_row()."\n";
  819: 		
  820: 		$matches++;
  821: 	    }
  822: 	}
  823:     }
  824:     if ($matches == 0) {
  825:         $string = $title
  826:                  .'<p class="LC_warning">'
  827:                  .&mt('No match found for the above receipt number.')
  828:                  .'</p>';
  829:     } else {
  830: 	$string = &jscriptNform($symb).$title.
  831: 	    '<p>'.
  832: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
  833: 	    '</p>'.
  834: 	    $header.
  835: 	    $contents.
  836: 	    &Apache::loncommon::end_data_table()."\n";
  837:     }
  838:     return $string;
  839: }
  840: 
  841: #--- This is called by a number of programs.
  842: #--- Called from the Grading Menu - View/Grade an individual student
  843: #--- Also called directly when one clicks on the subm button 
  844: #    on the problem page.
  845: sub listStudents {
  846:     my ($request,$symb,$submitonly) = @_;
  847: 
  848:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  849:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  850:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  851:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  852:     unless ($submitonly) {
  853:        $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  854:     }
  855: 
  856:     my $result='';
  857:     my $res_error;
  858:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
  859: 
  860:     my %lt = &Apache::lonlocal::texthash (
  861: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
  862: 		'single'   => 'Please select the student before clicking on the Next button.',
  863: 	     );
  864:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
  865:     function checkSelect(checkBox) {
  866: 	var ctr=0;
  867: 	var sense="";
  868: 	if (checkBox.length > 1) {
  869: 	    for (var i=0; i<checkBox.length; i++) {
  870: 		if (checkBox[i].checked) {
  871: 		    ctr++;
  872: 		}
  873: 	    }
  874: 	    sense = '$lt{'multiple'}';
  875: 	} else {
  876: 	    if (checkBox.checked) {
  877: 		ctr = 1;
  878: 	    }
  879: 	    sense = '$lt{'single'}';
  880: 	}
  881: 	if (ctr == 0) {
  882: 	    alert(sense);
  883: 	    return false;
  884: 	}
  885: 	document.gradesub.submit();
  886:     }
  887: 
  888:     function reLoadList(formname) {
  889: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  890: 	formname.command.value = 'submission';
  891: 	formname.submit();
  892:     }
  893: LISTJAVASCRIPT
  894: 
  895:     &commonJSfunctions($request);
  896:     $request->print($result);
  897: 
  898:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  899: 	"\n";
  900: 	
  901:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
  902:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
  903:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
  904:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
  905:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
  906:                   .&Apache::lonhtmlcommon::row_closure();
  907:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
  908:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
  909:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
  910:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
  911:                   .&Apache::lonhtmlcommon::row_closure();
  912: 
  913:     my $submission_options;
  914:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  915:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  916:     $env{'form.Status'} = $saveStatus;
  917:     $submission_options.=
  918:         '<span class="LC_nobreak">'.
  919:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
  920:         &mt('last submission').' </label></span>'."\n".
  921:         '<span class="LC_nobreak">'.
  922:         '<label><input type="radio" name="lastSub" value="last" /> '.
  923:         &mt('last submission with details').' </label></span>'."\n".
  924:         '<span class="LC_nobreak">'.
  925:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
  926:         &mt('all submissions').'</label></span>'."\n".
  927:         '<span class="LC_nobreak">'.
  928:         '<label><input type="radio" name="lastSub" value="all" /> '.
  929:         &mt('all submissions with details').'</label></span>';
  930:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
  931:                   .$submission_options
  932:                   .&Apache::lonhtmlcommon::row_closure();
  933: 
  934:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
  935:                   .'<select name="increment">'
  936:                   .'<option value="1">'.&mt('Whole Points').'</option>'
  937:                   .'<option value=".5">'.&mt('Half Points').'</option>'
  938:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
  939:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
  940:                   .'</select>'
  941:                   .&Apache::lonhtmlcommon::row_closure();
  942: 
  943:     $gradeTable .= 
  944:         &build_section_inputs().
  945: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
  946: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  947: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
  948: 
  949:     if (exists($env{'form.Status'})) {
  950: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
  951:     } else {
  952:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
  953:                       .&Apache::lonhtmlcommon::StatusOptions(
  954:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
  955:                       .&Apache::lonhtmlcommon::row_closure();
  956:     }
  957: 
  958:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
  959:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
  960:                   .&Apache::lonhtmlcommon::row_closure(1)
  961:                   .&Apache::lonhtmlcommon::end_pick_box();
  962: 
  963:     $gradeTable .= '<p>'
  964:                   .&mt("To view/grade/regrade a submission or a group of submissions, click on the check box(es) next to the student's name(s). Then click on the Next button.")."\n"
  965:                   .'<input type="hidden" name="command" value="processGroup" />'
  966:                   .'</p>';
  967: 
  968: # checkall buttons
  969:     $gradeTable.=&check_script('gradesub', 'stuinfo');
  970:     $gradeTable.='<input type="button" '."\n".
  971:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
  972:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
  973:     $gradeTable.=&check_buttons();
  974:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
  975:     $gradeTable.= &Apache::loncommon::start_data_table().
  976: 	&Apache::loncommon::start_data_table_header_row();
  977:     my $loop = 0;
  978:     while ($loop < 2) {
  979: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
  980: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
  981: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
  982: 	    foreach my $part (sort(@$partlist)) {
  983: 		my $display_part=
  984: 		    &get_display_part((split(/_/,$part))[0],$symb);
  985: 		$gradeTable.=
  986: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
  987: 	    }
  988: 	} elsif ($submitonly eq 'queued') {
  989: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
  990: 	}
  991: 	$loop++;
  992: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
  993:     }
  994:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
  995: 
  996:     my $ctr = 0;
  997:     foreach my $student (sort 
  998: 			 {
  999: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 1000: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 1001: 			     }
 1002: 			     return $a cmp $b;
 1003: 			 }
 1004: 			 (keys(%$fullname))) {
 1005: 	my ($uname,$udom) = split(/:/,$student);
 1006: 
 1007: 	my %status = ();
 1008: 
 1009: 	if ($submitonly eq 'queued') {
 1010: 	    my %queue_status = 
 1011: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 1012: 							$udom,$uname);
 1013: 	    next if (!defined($queue_status{'gradingqueue'}));
 1014: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
 1015: 	}
 1016: 
 1017: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1018: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
 1019: 	    my $submitted = 0;
 1020: 	    my $graded = 0;
 1021: 	    my $incorrect = 0;
 1022: 	    foreach (keys(%status)) {
 1023: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1024: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1025: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1026: 		
 1027: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1028: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1029: 		    $submitted = 0;
 1030: 		    my ($part)=split(/\./,$partid);
 1031: 		    $gradeTable.='<input type="hidden" name="'.
 1032: 			$student.':'.$part.':submitted_by" value="'.
 1033: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1034: 		}
 1035: 	    }
 1036: 	    
 1037: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1038: 				     $submitonly eq 'incorrect' ||
 1039: 				     $submitonly eq 'graded'));
 1040: 	    next if (!$graded && ($submitonly eq 'graded'));
 1041: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1042: 	}
 1043: 
 1044: 	$ctr++;
 1045: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1046:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1047: 	if ( $perm{'vgr'} eq 'F' ) {
 1048: 	    if ($ctr%2 ==1) {
 1049: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1050: 	    }
 1051: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1052:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1053:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1054: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1055: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1056: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1057: 
 1058: 	    if ($submitonly ne 'all') {
 1059: 		foreach (sort(keys(%status))) {
 1060: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1061: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1062: 		}
 1063: 	    }
 1064: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1065: 	    if ($ctr%2 ==0) {
 1066: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1067: 	    }
 1068: 	}
 1069:     }
 1070:     if ($ctr%2 ==1) {
 1071: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1072: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1073: 		foreach (@$partlist) {
 1074: 		    $gradeTable.='<td>&nbsp;</td>';
 1075: 		}
 1076: 	    } elsif ($submitonly eq 'queued') {
 1077: 		$gradeTable.='<td>&nbsp;</td>';
 1078: 	    }
 1079: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1080:     }
 1081: 
 1082:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1083:         '<input type="button" '.
 1084:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
 1085:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1086:     if ($ctr == 0) {
 1087: 	my $num_students=(scalar(keys(%$fullname)));
 1088: 	if ($num_students eq 0) {
 1089: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1090: 	} else {
 1091: 	    my $submissions='submissions';
 1092: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1093: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1094: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1095: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1096: 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
 1097: 		    $num_students).
 1098: 		'</span><br />';
 1099: 	}
 1100:     } elsif ($ctr == 1) {
 1101: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1102:     }
 1103:     $request->print($gradeTable);
 1104:     return '';
 1105: }
 1106: 
 1107: #---- Called from the listStudents routine
 1108: 
 1109: sub check_script {
 1110:     my ($form, $type)=@_;
 1111:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
 1112:     function checkall() {
 1113:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1114:             ele = document.forms.'.$form.'.elements[i];
 1115:             if (ele.name == "'.$type.'") {
 1116:             document.forms.'.$form.'.elements[i].checked=true;
 1117:                                        }
 1118:         }
 1119:     }
 1120: 
 1121:     function checksec() {
 1122:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1123:             ele = document.forms.'.$form.'.elements[i];
 1124:            string = document.forms.'.$form.'.chksec.value;
 1125:            if
 1126:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1127:               document.forms.'.$form.'.elements[i].checked=true;
 1128:             }
 1129:         }
 1130:     }
 1131: 
 1132: 
 1133:     function uncheckall() {
 1134:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1135:             ele = document.forms.'.$form.'.elements[i];
 1136:             if (ele.name == "'.$type.'") {
 1137:             document.forms.'.$form.'.elements[i].checked=false;
 1138:                                        }
 1139:         }
 1140:     }
 1141: 
 1142: '."\n");
 1143:     return $chkallscript;
 1144: }
 1145: 
 1146: sub check_buttons {
 1147:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1148:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1149:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1150:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1151:     return $buttons;
 1152: }
 1153: 
 1154: #     Displays the submissions for one student or a group of students
 1155: sub processGroup {
 1156:     my ($request,$symb)  = @_;
 1157:     my $ctr        = 0;
 1158:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1159:     my $total      = scalar(@stuchecked)-1;
 1160: 
 1161:     foreach my $student (@stuchecked) {
 1162: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1163: 	$env{'form.student'}        = $uname;
 1164: 	$env{'form.userdom'}        = $udom;
 1165: 	$env{'form.fullname'}       = $fullname;
 1166: 	&submission($request,$ctr,$total,$symb);
 1167: 	$ctr++;
 1168:     }
 1169:     return '';
 1170: }
 1171: 
 1172: #------------------------------------------------------------------------------------
 1173: #
 1174: #-------------------------- Next few routines handles grading by student, essentially
 1175: #                           handles essay response type problem/part
 1176: #
 1177: #--- Javascript to handle the submission page functionality ---
 1178: sub sub_page_js {
 1179:     my $request = shift;
 1180: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1181:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1182:     function updateRadio(formname,id,weight) {
 1183: 	var gradeBox = formname["GD_BOX"+id];
 1184: 	var radioButton = formname["RADVAL"+id];
 1185: 	var oldpts = formname["oldpts"+id].value;
 1186: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1187: 	gradeBox.value = pts;
 1188: 	var resetbox = false;
 1189: 	if (isNaN(pts) || pts < 0) {
 1190: 	    alert("$alertmsg"+pts);
 1191: 	    for (var i=0; i<radioButton.length; i++) {
 1192: 		if (radioButton[i].checked) {
 1193: 		    gradeBox.value = i;
 1194: 		    resetbox = true;
 1195: 		}
 1196: 	    }
 1197: 	    if (!resetbox) {
 1198: 		formtextbox.value = "";
 1199: 	    }
 1200: 	    return;
 1201: 	}
 1202: 
 1203: 	if (pts > weight) {
 1204: 	    var resp = confirm("You entered a value ("+pts+
 1205: 			       ") greater than the weight for the part. Accept?");
 1206: 	    if (resp == false) {
 1207: 		gradeBox.value = oldpts;
 1208: 		return;
 1209: 	    }
 1210: 	}
 1211: 
 1212: 	for (var i=0; i<radioButton.length; i++) {
 1213: 	    radioButton[i].checked=false;
 1214: 	    if (pts == i && pts != "") {
 1215: 		radioButton[i].checked=true;
 1216: 	    }
 1217: 	}
 1218: 	updateSelect(formname,id);
 1219: 	formname["stores"+id].value = "0";
 1220:     }
 1221: 
 1222:     function writeBox(formname,id,pts) {
 1223: 	var gradeBox = formname["GD_BOX"+id];
 1224: 	if (checkSolved(formname,id) == 'update') {
 1225: 	    gradeBox.value = pts;
 1226: 	} else {
 1227: 	    var oldpts = formname["oldpts"+id].value;
 1228: 	    gradeBox.value = oldpts;
 1229: 	    var radioButton = formname["RADVAL"+id];
 1230: 	    for (var i=0; i<radioButton.length; i++) {
 1231: 		radioButton[i].checked=false;
 1232: 		if (i == oldpts) {
 1233: 		    radioButton[i].checked=true;
 1234: 		}
 1235: 	    }
 1236: 	}
 1237: 	formname["stores"+id].value = "0";
 1238: 	updateSelect(formname,id);
 1239: 	return;
 1240:     }
 1241: 
 1242:     function clearRadBox(formname,id) {
 1243: 	if (checkSolved(formname,id) == 'noupdate') {
 1244: 	    updateSelect(formname,id);
 1245: 	    return;
 1246: 	}
 1247: 	gradeSelect = formname["GD_SEL"+id];
 1248: 	for (var i=0; i<gradeSelect.length; i++) {
 1249: 	    if (gradeSelect[i].selected) {
 1250: 		var selectx=i;
 1251: 	    }
 1252: 	}
 1253: 	var stores = formname["stores"+id];
 1254: 	if (selectx == stores.value) { return };
 1255: 	var gradeBox = formname["GD_BOX"+id];
 1256: 	gradeBox.value = "";
 1257: 	var radioButton = formname["RADVAL"+id];
 1258: 	for (var i=0; i<radioButton.length; i++) {
 1259: 	    radioButton[i].checked=false;
 1260: 	}
 1261: 	stores.value = selectx;
 1262:     }
 1263: 
 1264:     function checkSolved(formname,id) {
 1265: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1266: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1267: 	    if (!reply) {return "noupdate";}
 1268: 	    formname.overRideScore.value = 'yes';
 1269: 	}
 1270: 	return "update";
 1271:     }
 1272: 
 1273:     function updateSelect(formname,id) {
 1274: 	formname["GD_SEL"+id][0].selected = true;
 1275: 	return;
 1276:     }
 1277: 
 1278: //=========== Check that a point is assigned for all the parts  ============
 1279:     function checksubmit(formname,val,total,parttot) {
 1280: 	formname.gradeOpt.value = val;
 1281: 	if (val == "Save & Next") {
 1282: 	    for (i=0;i<=total;i++) {
 1283: 		for (j=0;j<parttot;j++) {
 1284: 		    var partid = formname["partid"+i+"_"+j].value;
 1285: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1286: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1287: 			if (points == "") {
 1288: 			    var name = formname["name"+i].value;
 1289: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1290: 			    var resp = confirm("You did not assign a score for "+studentID+
 1291: 					       ", part "+partid+". Continue?");
 1292: 			    if (resp == false) {
 1293: 				formname["GD_BOX"+i+"_"+partid].focus();
 1294: 				return false;
 1295: 			    }
 1296: 			}
 1297: 		    }
 1298: 		}
 1299: 	    }
 1300: 	}
 1301: 	formname.submit();
 1302:     }
 1303: 
 1304: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1305:     function checkSubmitPage(formname,total) {
 1306: 	noscore = new Array(100);
 1307: 	var ptr = 0;
 1308: 	for (i=1;i<total;i++) {
 1309: 	    var partid = formname["q_"+i].value;
 1310: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1311: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1312: 		var status = formname["solved"+i+"_"+partid].value;
 1313: 		if (points == "" && status != "correct_by_student") {
 1314: 		    noscore[ptr] = i;
 1315: 		    ptr++;
 1316: 		}
 1317: 	    }
 1318: 	}
 1319: 	if (ptr != 0) {
 1320: 	    var sense = ptr == 1 ? ": " : "s: ";
 1321: 	    var prolist = "";
 1322: 	    if (ptr == 1) {
 1323: 		prolist = noscore[0];
 1324: 	    } else {
 1325: 		var i = 0;
 1326: 		while (i < ptr-1) {
 1327: 		    prolist += noscore[i]+", ";
 1328: 		    i++;
 1329: 		}
 1330: 		prolist += "and "+noscore[i];
 1331: 	    }
 1332: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1333: 	    if (resp == false) {
 1334: 		return false;
 1335: 	    }
 1336: 	}
 1337: 
 1338: 	formname.submit();
 1339:     }
 1340: SUBJAVASCRIPT
 1341: }
 1342: 
 1343: #--- javascript for essay type problem --
 1344: sub sub_page_kw_js {
 1345:     my $request = shift;
 1346:     my $iconpath = $request->dir_config('lonIconsURL');
 1347:     &commonJSfunctions($request);
 1348: 
 1349:     my $inner_js_msg_central= (<<INNERJS);
 1350: <script type="text/javascript">
 1351:     function checkInput() {
 1352:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1353:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1354:       var usrctr = document.msgcenter.usrctr.value;
 1355:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1356:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1357: 
 1358:       var msgchk = "";
 1359:       if (document.msgcenter.subchk.checked) {
 1360:          msgchk = "msgsub,";
 1361:       }
 1362:       var includemsg = 0;
 1363:       for (var i=1; i<=nmsg; i++) {
 1364:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1365:           var frmmsg = document.msgcenter["msg"+i];
 1366:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1367:           var showflg = opener.document.SCORE["shownOnce"+i];
 1368:           showflg.value = "1";
 1369:           var chkbox = document.msgcenter["msgn"+i];
 1370:           if (chkbox.checked) {
 1371:              msgchk += "savemsg"+i+",";
 1372:              includemsg = 1;
 1373:           }
 1374:       }
 1375:       if (document.msgcenter.newmsgchk.checked) {
 1376:          msgchk += "newmsg"+usrctr;
 1377:          includemsg = 1;
 1378:       }
 1379:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1380:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1381:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1382:       includemsg.value = msgchk;
 1383: 
 1384:       self.close()
 1385: 
 1386:     }
 1387: </script>
 1388: INNERJS
 1389: 
 1390:     my $inner_js_highlight_central= (<<INNERJS);
 1391: <script type="text/javascript">
 1392:     function updateChoice(flag) {
 1393:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1394:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1395:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1396:       opener.document.SCORE.refresh.value = "on";
 1397:       if (opener.document.SCORE.keywords.value!=""){
 1398:          opener.document.SCORE.submit();
 1399:       }
 1400:       self.close()
 1401:     }
 1402: </script>
 1403: INNERJS
 1404: 
 1405:     my $start_page_msg_central = 
 1406:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1407: 				       {'js_ready'  => 1,
 1408: 					'only_body' => 1,
 1409: 					'bgcolor'   =>'#FFFFFF',});
 1410:     my $end_page_msg_central = 
 1411: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1412: 
 1413: 
 1414:     my $start_page_highlight_central = 
 1415:         &Apache::loncommon::start_page('Highlight Central',
 1416: 				       $inner_js_highlight_central,
 1417: 				       {'js_ready'  => 1,
 1418: 					'only_body' => 1,
 1419: 					'bgcolor'   =>'#FFFFFF',});
 1420:     my $end_page_highlight_central = 
 1421: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1422: 
 1423:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1424:     $docopen=~s/^document\.//;
 1425:     my %lt = &Apache::lonlocal::texthash(
 1426:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
 1427:                 plse => 'Please select a word or group of words from document and then click this link.',
 1428:                 adds => 'Add selection to keyword list? Edit if desired.',
 1429:                 comp => 'Compose Message for: ',
 1430:                 incl => 'Include',
 1431:                 type => 'Type',
 1432:                 subj => 'Subject',
 1433:                 mesa => 'Message',
 1434:                 new  => 'New',
 1435:                 save => 'Save',
 1436:                 canc => 'Cancel',
 1437:                 kehi => 'Keyword Highlight Options',
 1438:                 txtc => 'Text Color',
 1439:                 font => 'Font Size',
 1440:                 fnst => 'Font Style',
 1441:                 col1 => 'red',
 1442:                 col2 => 'green',
 1443:                 col3 => 'blue',
 1444:                 siz1 => 'normal',
 1445:                 siz2 => '+1',
 1446:                 siz3 => '+2',
 1447:                 sty1 => 'normal',
 1448:                 sty2 => 'italic',
 1449:                 sty3 => 'bold',
 1450:              );
 1451:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1452: 
 1453: //===================== Show list of keywords ====================
 1454:   function keywords(formname) {
 1455:     var nret = prompt("$lt{'keyw'}",formname.keywords.value);
 1456:     if (nret==null) return;
 1457:     formname.keywords.value = nret;
 1458: 
 1459:     if (formname.keywords.value != "") {
 1460: 	formname.refresh.value = "on";
 1461: 	formname.submit();
 1462:     }
 1463:     return;
 1464:   }
 1465: 
 1466: //===================== Script to view submitted by ==================
 1467:   function viewSubmitter(submitter) {
 1468:     document.SCORE.refresh.value = "on";
 1469:     document.SCORE.NCT.value = "1";
 1470:     document.SCORE.unamedom0.value = submitter;
 1471:     document.SCORE.submit();
 1472:     return;
 1473:   }
 1474: 
 1475: //===================== Script to add keyword(s) ==================
 1476:   function getSel() {
 1477:     if (document.getSelection) txt = document.getSelection();
 1478:     else if (document.selection) txt = document.selection.createRange().text;
 1479:     else return;
 1480:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1481:     if (cleantxt=="") {
 1482: 	alert("$lt{'plse'}");
 1483: 	return;
 1484:     }
 1485:     var nret = prompt("$lt{'adds'}",cleantxt);
 1486:     if (nret==null) return;
 1487:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1488:     if (document.SCORE.keywords.value != "") {
 1489: 	document.SCORE.refresh.value = "on";
 1490: 	document.SCORE.submit();
 1491:     }
 1492:     return;
 1493:   }
 1494: 
 1495: //====================== Script for composing message ==============
 1496:    // preload images
 1497:    img1 = new Image();
 1498:    img1.src = "$iconpath/mailbkgrd.gif";
 1499:    img2 = new Image();
 1500:    img2.src = "$iconpath/mailto.gif";
 1501: 
 1502:   function msgCenter(msgform,usrctr,fullname) {
 1503:     var Nmsg  = msgform.savemsgN.value;
 1504:     savedMsgHeader(Nmsg,usrctr,fullname);
 1505:     var subject = msgform.msgsub.value;
 1506:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1507:     re = /msgsub/;
 1508:     var shwsel = "";
 1509:     if (re.test(msgchk)) { shwsel = "checked" }
 1510:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1511:     displaySubject(checkEntities(subject),shwsel);
 1512:     for (var i=1; i<=Nmsg; i++) {
 1513: 	var testmsg = "savemsg"+i+",";
 1514: 	re = new RegExp(testmsg,"g");
 1515: 	shwsel = "";
 1516: 	if (re.test(msgchk)) { shwsel = "checked" }
 1517: 	var message = document.SCORE["savemsg"+i].value;
 1518: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1519: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1520: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1521:     }
 1522:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1523:     shwsel = "";
 1524:     re = /newmsg/;
 1525:     if (re.test(msgchk)) { shwsel = "checked" }
 1526:     newMsg(newmsg,shwsel);
 1527:     msgTail(); 
 1528:     return;
 1529:   }
 1530: 
 1531:   function checkEntities(strx) {
 1532:     if (strx.length == 0) return strx;
 1533:     var orgStr = ["&", "<", ">", '"']; 
 1534:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1535:     var counter = 0;
 1536:     while (counter < 4) {
 1537: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1538: 	counter++;
 1539:     }
 1540:     return strx;
 1541:   }
 1542: 
 1543:   function strReplace(strx, orgStr, newStr) {
 1544:     return strx.split(orgStr).join(newStr);
 1545:   }
 1546: 
 1547:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1548:     var height = 70*Nmsg+250;
 1549:     if (height > 600) {
 1550: 	height = 600;
 1551:     }
 1552:     var xpos = (screen.width-600)/2;
 1553:     xpos = (xpos < 0) ? '0' : xpos;
 1554:     var ypos = (screen.height-height)/2-30;
 1555:     ypos = (ypos < 0) ? '0' : ypos;
 1556: 
 1557:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
 1558:     pWin.focus();
 1559:     pDoc = pWin.document;
 1560:     pDoc.$docopen;
 1561:     pDoc.write('$start_page_msg_central');
 1562: 
 1563:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1564:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1565:     pDoc.write("<h1>&nbsp;$lt{'comp'}\"+fullname+\"<\\/h1>");
 1566: 
 1567:     pDoc.write('<table style="border:1px solid black;"><tr>');
 1568:     pDoc.write("<td><b>$lt{'incl'}<\\/b><\\/td><td><b>$lt{'type'}<\\/b><\\/td><td><b>$lt{'mesa'}<\\/td><\\/tr>");
 1569: }
 1570:     function displaySubject(msg,shwsel) {
 1571:     pDoc = pWin.document;
 1572:     pDoc.write("<tr>");
 1573:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1574:     pDoc.write("<td>$lt{'subj'}<\\/td>");
 1575:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1576: }
 1577: 
 1578:   function displaySavedMsg(ctr,msg,shwsel) {
 1579:     pDoc = pWin.document;
 1580:     pDoc.write("<tr>");
 1581:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1582:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1583:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1584: }
 1585: 
 1586:   function newMsg(newmsg,shwsel) {
 1587:     pDoc = pWin.document;
 1588:     pDoc.write("<tr>");
 1589:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1590:     pDoc.write("<td align=\\"center\\">$lt{'new'}<\\/td>");
 1591:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1592: }
 1593: 
 1594:   function msgTail() {
 1595:     pDoc = pWin.document;
 1596:     //pDoc.write("<\\/table>");
 1597:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1598:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1599:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
 1600:     pDoc.write("<\\/form>");
 1601:     pDoc.write('$end_page_msg_central');
 1602:     pDoc.close();
 1603: }
 1604: 
 1605: //====================== Script for keyword highlight options ==============
 1606:   function kwhighlight() {
 1607:     var kwclr    = document.SCORE.kwclr.value;
 1608:     var kwsize   = document.SCORE.kwsize.value;
 1609:     var kwstyle  = document.SCORE.kwstyle.value;
 1610:     var redsel = "";
 1611:     var grnsel = "";
 1612:     var blusel = "";
 1613:     var txtcol1 = "$lt{'col1'}";
 1614:     var txtcol2 = "$lt{'col2'}";
 1615:     var txtcol3 = "$lt{'col3'}";
 1616:     var txtsiz1 = "$lt{'siz1'}";
 1617:     var txtsiz2 = "$lt{'siz2'}";
 1618:     var txtsiz3 = "$lt{'siz3'}";
 1619:     var txtsty1 = "$lt{'sty1'}";
 1620:     var txtsty2 = "$lt{'sty2'}";
 1621:     var txtsty3 = "$lt{'sty3'}";
 1622:     if (kwclr=="red")   {var redsel="checked='checked'"};
 1623:     if (kwclr=="green") {var grnsel="checked='checked'"};
 1624:     if (kwclr=="blue")  {var blusel="checked='checked'"};
 1625:     var sznsel = "";
 1626:     var sz1sel = "";
 1627:     var sz2sel = "";
 1628:     if (kwsize=="0")  {var sznsel="checked='checked'"};
 1629:     if (kwsize=="+1") {var sz1sel="checked='checked'"};
 1630:     if (kwsize=="+2") {var sz2sel="checked='checked'"};
 1631:     var synsel = "";
 1632:     var syisel = "";
 1633:     var sybsel = "";
 1634:     if (kwstyle=="")    {var synsel="checked='checked'"};
 1635:     if (kwstyle=="<i>") {var syisel="checked='checked'"};
 1636:     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
 1637:     highlightCentral();
 1638:     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
 1639:     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
 1640:     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
 1641:     highlightend();
 1642:     return;
 1643:   }
 1644: 
 1645:   function highlightCentral() {
 1646: //    if (window.hwdWin) window.hwdWin.close();
 1647:     var xpos = (screen.width-400)/2;
 1648:     xpos = (xpos < 0) ? '0' : xpos;
 1649:     var ypos = (screen.height-330)/2-30;
 1650:     ypos = (ypos < 0) ? '0' : ypos;
 1651: 
 1652:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1653:     hwdWin.focus();
 1654:     var hDoc = hwdWin.document;
 1655:     hDoc.$docopen;
 1656:     hDoc.write('$start_page_highlight_central');
 1657:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1658:     hDoc.write("<h1>$lt{'kehi'}<\\/h1>");
 1659: 
 1660:     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
 1661:     hDoc.write("<th>$lt{'txtc'}<\\/th><th>$lt{'font'}<\\/th><th>$lt{'fnst'}<\\/th><\\/tr>");
 1662:   }
 1663: 
 1664:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1665:     var hDoc = hwdWin.document;
 1666:     hDoc.write("<tr>");
 1667:     hDoc.write("<td align=\\"left\\">");
 1668:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
 1669:     hDoc.write("<td align=\\"left\\">");
 1670:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
 1671:     hDoc.write("<td align=\\"left\\">");
 1672:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
 1673:     hDoc.write("<\\/tr>");
 1674:   }
 1675: 
 1676:   function highlightend() { 
 1677:     var hDoc = hwdWin.document;
 1678:     hDoc.write("<\\/table><br \\/>");
 1679:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
 1680:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
 1681:     hDoc.write("<\\/form>");
 1682:     hDoc.write('$end_page_highlight_central');
 1683:     hDoc.close();
 1684:   }
 1685: 
 1686: SUBJAVASCRIPT
 1687: }
 1688: 
 1689: sub get_increment {
 1690:     my $increment = $env{'form.increment'};
 1691:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1692:         $increment != .1) {
 1693:         $increment = 1;
 1694:     }
 1695:     return $increment;
 1696: }
 1697: 
 1698: sub gradeBox_start {
 1699:     return (
 1700:         &Apache::loncommon::start_data_table()
 1701:        .&Apache::loncommon::start_data_table_header_row()
 1702:        .'<th>'.&mt('Part').'</th>'
 1703:        .'<th>'.&mt('Points').'</th>'
 1704:        .'<th>&nbsp;</th>'
 1705:        .'<th>'.&mt('Assign Grade').'</th>'
 1706:        .'<th>'.&mt('Weight').'</th>'
 1707:        .'<th>'.&mt('Grade Status').'</th>'
 1708:        .&Apache::loncommon::end_data_table_header_row()
 1709:     );
 1710: }
 1711: 
 1712: sub gradeBox_end {
 1713:     return (
 1714:         &Apache::loncommon::end_data_table()
 1715:     );
 1716: }
 1717: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1718: sub gradeBox {
 1719:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1720:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1721: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1722:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1723:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1724:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1725:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1726:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1727: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1728:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1729:     my $display_part= &get_display_part($partid,$symb);
 1730:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1731: 				       [$partid]);
 1732:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1733:     if ($last_resets{$partid}) {
 1734:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1735:     }
 1736:     my $result=&Apache::loncommon::start_data_table_row();
 1737:     my $ctr = 0;
 1738:     my $thisweight = 0;
 1739:     my $increment = &get_increment();
 1740: 
 1741:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1742:     while ($thisweight<=$wgt) {
 1743: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1744:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1745: 	    $thisweight.')" value="'.$thisweight.'" '.
 1746: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1747: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1748:         $thisweight += $increment;
 1749: 	$ctr++;
 1750:     }
 1751:     $radio.='</tr></table>';
 1752: 
 1753:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1754: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1755: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1756: 	$wgt.')" /></td>'."\n";
 1757:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1758: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1759: 	' </td>'."\n";
 1760:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1761: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1762:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1763: 	$line.='<option></option>'.
 1764: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1765:     } else {
 1766: 	$line.='<option selected="selected"></option>'.
 1767: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1768:     }
 1769:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1770: 
 1771: 
 1772:     $result .= 
 1773: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 1774:     $result.=&Apache::loncommon::end_data_table_row();
 1775:     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
 1776:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1777: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1778: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1779: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1780:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1781:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1782:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1783:         $aggtries.'" />'."\n";
 1784:     my $res_error;
 1785:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 1786:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
 1787:     if ($res_error) {
 1788:         return &navmap_errormsg();
 1789:     }
 1790:     return $result;
 1791: }
 1792: 
 1793: sub handback_box {
 1794:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
 1795:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
 1796:     my (@respids);
 1797:     my @part_response_id = &flatten_responseType($responseType);
 1798:     foreach my $part_response_id (@part_response_id) {
 1799:     	my ($part,$resp) = @{ $part_response_id };
 1800:         if ($part eq $partid) {
 1801:             push(@respids,$resp);
 1802:         }
 1803:     }
 1804:     my $result;
 1805:     foreach my $respid (@respids) {
 1806: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1807: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1808: 	next if (!@$files);
 1809: 	my $file_counter = 0;
 1810: 	foreach my $file (@$files) {
 1811: 	    if ($file =~ /\/portfolio\//) {
 1812:                 $file_counter++;
 1813:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1814:     	        my ($name,$version,$ext) = &Apache::lonnet::file_name_version_ext($file_disp);
 1815:     	        $file_disp = "$name.$ext";
 1816:     	        $file = $file_path.$file_disp;
 1817:     	        $result.=&mt('Return commented version of [_1] to student.',
 1818:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1819:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1820:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
 1821: 	    }
 1822: 	}
 1823:         if ($file_counter) {
 1824:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
 1825:                        '<span class="LC_info">'.
 1826:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
 1827:         }
 1828:     }
 1829:     return $result;    
 1830: }
 1831: 
 1832: sub show_problem {
 1833:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1834:     my $rendered;
 1835:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1836:     &Apache::lonxml::remember_problem_counter();
 1837:     if ($mode eq 'both' or $mode eq 'text') {
 1838: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1839: 						       $env{'request.course.id'},
 1840: 						       undef,\%form);
 1841:     }
 1842:     if ($removeform) {
 1843: 	$rendered=~s|<form(.*?)>||g;
 1844: 	$rendered=~s|</form>||g;
 1845: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1846:     }
 1847:     my $companswer;
 1848:     if ($mode eq 'both' or $mode eq 'answer') {
 1849: 	&Apache::lonxml::restore_problem_counter();
 1850: 	$companswer=
 1851: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1852: 						    $env{'request.course.id'},
 1853: 						    %form);
 1854:     }
 1855:     if ($removeform) {
 1856: 	$companswer=~s|<form(.*?)>||g;
 1857: 	$companswer=~s|</form>||g;
 1858: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1859:     }
 1860:     my $renderheading = &mt('View of the problem');
 1861:     my $answerheading = &mt('Correct answer');
 1862:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 1863:         my $stu_fullname = $env{'form.fullname'};
 1864:         if ($stu_fullname eq '') {
 1865:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
 1866:         }
 1867:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
 1868:         if ($forwhom ne '') {
 1869:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
 1870:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
 1871:         }
 1872:     }
 1873:     $rendered=
 1874:         '<div class="LC_Box">'
 1875:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
 1876:        .$rendered
 1877:        .'</div>';
 1878:     $companswer=
 1879:         '<div class="LC_Box">'
 1880:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
 1881:        .$companswer
 1882:        .'</div>';
 1883:     my $result;
 1884:     if ($mode eq 'both') {
 1885:         $result=$rendered.$companswer;
 1886:     } elsif ($mode eq 'text') {
 1887:         $result=$rendered;
 1888:     } elsif ($mode eq 'answer') {
 1889:         $result=$companswer;
 1890:     }
 1891:     return $result;
 1892: }
 1893: 
 1894: sub files_exist {
 1895:     my ($r, $symb) = @_;
 1896:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1897: 
 1898:     foreach my $student (@students) {
 1899:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1900:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1901: 					      $udom,$uname);
 1902:         my ($string,$timestamp)= &get_last_submission(\%record);
 1903:         foreach my $submission (@$string) {
 1904:             my ($partid,$respid) =
 1905: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1906:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1907: 					   \%record);
 1908:             return 1 if (@$files);
 1909:         }
 1910:     }
 1911:     return 0;
 1912: }
 1913: 
 1914: sub download_all_link {
 1915:     my ($r,$symb) = @_;
 1916:     unless (&files_exist($r, $symb)) {
 1917:        $r->print(&mt('There are currently no submitted documents.'));
 1918:        return;
 1919:     }
 1920: 
 1921:     my $all_students = 
 1922: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1923: 
 1924:     my $parts =
 1925: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1926: 
 1927:     my $identifier = &Apache::loncommon::get_cgi_id();
 1928:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 1929:                              'cgi.'.$identifier.'.symb' => $symb,
 1930:                              'cgi.'.$identifier.'.parts' => $parts,});
 1931:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1932: 	      &mt('Download All Submitted Documents').'</a>');
 1933:     return;
 1934: }
 1935: 
 1936: sub submit_download_link {
 1937:     my ($request,$symb) = @_;
 1938:     if (!$symb) { return ''; }
 1939: #FIXME: Figure out which type of problem this is and provide appropriate download
 1940:     &download_all_link($request,$symb);
 1941: }
 1942: 
 1943: sub build_section_inputs {
 1944:     my $section_inputs;
 1945:     if ($env{'form.section'} eq '') {
 1946:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 1947:     } else {
 1948:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 1949:         foreach my $section (@sections) {
 1950:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 1951:         }
 1952:     }
 1953:     return $section_inputs;
 1954: }
 1955: 
 1956: # --------------------------- show submissions of a student, option to grade 
 1957: sub submission {
 1958:     my ($request,$counter,$total,$symb) = @_;
 1959:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 1960:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 1961:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 1962:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 1963: 
 1964:     my $probtitle=&Apache::lonnet::gettitle($symb); 
 1965:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 1966: 
 1967:     if (!&canview($usec)) {
 1968:         $request->print(
 1969:             '<span class="LC_warning">'.
 1970:             &mt('Unable to view requested student.').
 1971:             ' '.&mt('([_1] in section [_2] in course id [_3])',
 1972:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
 1973:             '</span>');
 1974: 	return;
 1975:     }
 1976: 
 1977:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 1978:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 1979:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 1980:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 1981:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1982: 	'" src="'.$request->dir_config('lonIconsURL').
 1983: 	'/check.gif" height="16" border="0" />';
 1984: 
 1985:     # header info
 1986:     if ($counter == 0) {
 1987: 	&sub_page_js($request);
 1988: 	&sub_page_kw_js($request);
 1989: 
 1990: 	# option to display problem, only once else it cause problems 
 1991:         # with the form later since the problem has a form.
 1992: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 1993: 	    my $mode;
 1994: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 1995: 		$mode='both';
 1996: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 1997: 		$mode='text';
 1998: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 1999: 		$mode='answer';
 2000: 	    }
 2001: 	    &Apache::lonxml::clear_problem_counter();
 2002: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 2003: 	}
 2004: 
 2005: 	# kwclr is the only variable that is guaranteed not to be blank 
 2006:         # if this subroutine has been called once.
 2007: 	my %keyhash = ();
 2008: #	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 2009:         if (1) {
 2010: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 2011: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 2012: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 2013: 
 2014: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2015: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 2016: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 2017: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 2018: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 2019: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 2020: 		$keyhash{$symb.'_subject'} : $probtitle;
 2021: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 2022: 	}
 2023: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 2024: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 2025: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 2026: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 2027: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 2028: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 2029: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 2030: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 2031: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 2032: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 2033: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 2034: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 2035: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 2036: 			&build_section_inputs().
 2037: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 2038: 			'<input type="hidden" name="NCT"'.
 2039: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 2040: #	if ($env{'form.handgrade'} eq 'yes') {
 2041:         if (1) {
 2042: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 2043: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 2044: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 2045: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 2046: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2047: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2048: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2049: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 2050: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 2051: 	    }
 2052: 	}
 2053: 	
 2054: 	my ($cts,$prnmsg) = (1,'');
 2055: 	while ($cts <= $env{'form.savemsgN'}) {
 2056: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2057: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2058: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2059: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2060: 		'" />'."\n".
 2061: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2062: 	    $cts++;
 2063: 	}
 2064: 	$request->print($prnmsg);
 2065: 
 2066: #	if ($env{'form.handgrade'} eq 'yes') {
 2067:         if (1) {
 2068: 
 2069:             my %lt = &Apache::lonlocal::texthash(
 2070:                           keyh => 'Keyword Highlighting for Essays',
 2071:                           keyw => 'Keyword Options',
 2072:                           list => 'List',
 2073:                           past => 'Paste Selection to List',
 2074:                           high => 'Highlight Attribute',
 2075:                      );    
 2076: #
 2077: # Print out the keyword options line
 2078: #
 2079: 	    $request->print(
 2080:                 '<div class="LC_columnSection">'
 2081:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
 2082:                .&Apache::lonhtmlcommon::funclist_from_array(
 2083:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
 2084:                      '<a href="#" onmousedown="javascript:getSel(); return false"
 2085:  class="page">'.$lt{'past'}.'</a>',
 2086:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
 2087:                     {legend => $lt{'keyw'}})
 2088:                .'</fieldset></div>'
 2089:             );
 2090: 
 2091: #
 2092: # Load the other essays for similarity check
 2093: #
 2094:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2095: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2096: 	    $apath=&escape($apath);
 2097: 	    $apath=~s/\W/\_/gs;
 2098:             &init_old_essays($symb,$apath,$adom,$aname);
 2099:         }
 2100:     }
 2101: 
 2102: # This is where output for one specific student would start
 2103:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2104:     $request->print(
 2105:         "\n\n"
 2106:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2107:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2108:        ."\n"
 2109:     );
 2110: 
 2111:     # Show additional functions if allowed
 2112:     if ($perm{'vgr'}) {
 2113:         $request->print(
 2114:             &Apache::loncommon::track_student_link(
 2115:                 'View recent activity',
 2116:                 $uname,$udom,'check')
 2117:            .' '
 2118:         );
 2119:     }
 2120:     if ($perm{'opa'}) {
 2121:         $request->print(
 2122:             &Apache::loncommon::pprmlink(
 2123:                 &mt('Set/Change parameters'),
 2124:                 $uname,$udom,$symb,'check'));
 2125:     }
 2126: 
 2127:     # Show Problem
 2128:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2129: 	my $mode;
 2130: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2131: 	    $mode='both';
 2132: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2133: 	    $mode='text';
 2134: 	} elsif ($env{'form.vAns'} eq 'all') {
 2135: 	    $mode='answer';
 2136: 	}
 2137: 	&Apache::lonxml::clear_problem_counter();
 2138: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2139:     }
 2140: 
 2141:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2142:     my $res_error;
 2143:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2144:     if ($res_error) {
 2145:         $request->print(&navmap_errormsg());
 2146:         return;
 2147:     }
 2148: 
 2149:     # Display student info
 2150:     $request->print(($counter == 0 ? '' : '<br />'));
 2151: 
 2152:     my $result='<div class="LC_Box">'
 2153:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
 2154:     $result.='<input type="hidden" name="name'.$counter.
 2155:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2156: #    if ($env{'form.handgrade'} eq 'no') {
 2157:     if (1) {
 2158:         $result.='<p class="LC_info">'
 2159:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2160:                 ."</p>\n";
 2161:     }
 2162: 
 2163:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2164:     my $fullname;
 2165:     my $col_fullnames = [];
 2166: #    if ($env{'form.handgrade'} eq 'yes') {
 2167:     if (1) {
 2168: 	(my $sub_result,$fullname,$col_fullnames)=
 2169: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2170: 				 $counter);
 2171: 	$result.=$sub_result;
 2172:     }
 2173:     $request->print($result."\n");
 2174:     
 2175:     # print student answer/submission
 2176:     # Options are (1) Handgraded submission only
 2177:     #             (2) Last submission, includes submission that is not handgraded 
 2178:     #                  (for multi-response type part)
 2179:     #             (3) Last submission plus the parts info
 2180:     #             (4) The whole record for this student
 2181:     
 2182:     my ($string,$timestamp)= &get_last_submission(\%record);
 2183: 	
 2184:     my $lastsubonly;
 2185: 
 2186:     if ($$timestamp eq '') {
 2187:         $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2188:     } else {
 2189:         $lastsubonly =
 2190:             '<div class="LC_grade_submissions_body">'
 2191:            .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
 2192: 
 2193: 	my %seenparts;
 2194: 	my @part_response_id = &flatten_responseType($responseType);
 2195: 	foreach my $part (@part_response_id) {
 2196: 	    next if ($env{'form.lastSub'} eq 'hdgrade' 
 2197: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2198: 
 2199: 	    my ($partid,$respid) = @{ $part };
 2200: 	    my $display_part=&get_display_part($partid,$symb);
 2201: 	    if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2202: 		if (exists($seenparts{$partid})) { next; }
 2203: 		$seenparts{$partid}=1;
 2204:                 $request->print(
 2205:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2206:                     ' <b>'.&mt('Collaborative submission by: [_1]',
 2207:                                '<a href="javascript:viewSubmitter(\''.
 2208:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
 2209:                                '\');" target="_self">'.
 2210:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
 2211:                     '<br />');
 2212: 		next;
 2213: 		}
 2214: 	    my $responsetype = $responseType->{$partid}->{$respid};
 2215: 	    if (!exists($record{"resource.$partid.$respid.submission"})) {
 2216:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2217:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2218:                     ' <span class="LC_internal_info">'.
 2219:                     '('.&mt('Response ID: [_1]',$respid).')'.
 2220:                     '</span>&nbsp; &nbsp;'.
 2221: 	       	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2222: 		next;
 2223: 	    }
 2224: 	    foreach my $submission (@$string) {
 2225: 		my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2226: 		if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2227: 		my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
 2228: 		# Similarity check
 2229:                 my $similar='';
 2230:                 my ($type,$trial,$rndseed);
 2231:                 if ($hide eq 'rand') {
 2232:                     $type = 'randomizetry';
 2233:                     $trial = $record{"resource.$partid.tries"};
 2234:                     if (exists($record{"resource.$partid.rawrndseed"})) {
 2235:                         $rndseed = $record{"resource.$partid.rawrndseed"};
 2236:                     } else {
 2237:                         $rndseed = $record{"resource.$partid.rndseed"};
 2238:                     }
 2239:                 }
 2240: 	        if ($env{'form.checkPlag'}) {
 2241:     		    my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2242: 		        &most_similar($uname,$udom,$symb,$subval);
 2243: 		    if ($osim) {
 2244: 			$osim=int($osim*100.0);
 2245: 			my %old_course_desc = 
 2246: 			    &Apache::lonnet::coursedescription($ocrsid,
 2247: 							{'one_time' => 1});
 2248: 
 2249:                         if ($hide eq 'anon') {
 2250:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2251:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2252:                         } else {
 2253: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
 2254: 				&mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2255: 				    $osim,
 2256: 				    &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2257: 				        $old_course_desc{'description'},
 2258: 				        $old_course_desc{'num'},
 2259: 				        $old_course_desc{'domain'}).
 2260: 				    '</span></h3><blockquote><i>'.
 2261: 				    &keywords_highlight($oessay).
 2262: 				    '</i></blockquote><hr />';
 2263:                         }
 2264: 	            }
 2265: 		}
 2266: 		my $order=&get_order($partid,$respid,$symb,$uname,$udom,
 2267:                                      undef,$type,$trial,$rndseed);
 2268:                 if ($env{'form.lastSub'} eq 'lastonly' || $env{'form.lastSub'} eq 'datesub' || $env{'form.lastSub'} =~ /^(last|all)$/ || ($env{'form.lastSub'} eq 'hdgrade' && 
 2269: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2270: 		    my $display_part=&get_display_part($partid,$symb);
 2271:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
 2272:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2273:                         ' <span class="LC_internal_info">'.
 2274:                         '('.&mt('Response ID: [_1]',$respid).')'.
 2275:                         '</span>&nbsp; &nbsp;';
 2276: 		    my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2277:                         
 2278: 		    if (@$files) {
 2279:                         if ($hide eq 'anon') {
 2280:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2281:                         } else {
 2282:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
 2283:                                         .'<br /><span class="LC_warning">';
 2284:                             if(@$files == 1) {
 2285:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
 2286:                             } else {
 2287:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
 2288:                             }
 2289:                             $lastsubonly .= '</span>';                         
 2290:                             foreach my $file (@$files) {
 2291:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2292:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
 2293:                             }
 2294:                         }
 2295: 			$lastsubonly.='<br />';
 2296:                     }
 2297:                     if ($hide eq 'anon') {
 2298:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
 2299:                     } else {
 2300:              	        $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
 2301:                         if ($draft) {
 2302:                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
 2303:                         }
 2304:                         $subval =
 2305: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
 2306: 					 $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
 2307:                         if ($responsetype eq 'essay') {
 2308:                             $subval =~ s{\n}{<br />}g;
 2309:                         }
 2310:                         $lastsubonly.=$subval."\n";
 2311:                     }
 2312: 	            if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2313: 		    $lastsubonly.='</div>';
 2314: 		}
 2315:             }
 2316: 	}
 2317: 	$lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2318:     }
 2319:     $request->print($lastsubonly);
 2320:     if ($env{'form.lastSub'} eq 'datesub') {
 2321:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2322: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2323:   
 2324:     } 
 2325:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2326:         my $identifier = (&canmodify($usec)? $counter : '');
 2327:         $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2328: 								 $env{'request.course.id'},
 2329: 								 $last,'.submission',
 2330: 								 'Apache::grades::keywords_highlight',
 2331:                                                                  $usec,$identifier));
 2332:     }
 2333:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2334: 	.$udom.'" />'."\n");
 2335:     # return if view submission with no grading option
 2336:     if (!&canmodify($usec)) {
 2337: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
 2338: 	return;
 2339:     } else {
 2340: 	$request->print('</div>'."\n");
 2341:     }
 2342: 
 2343:     # essay grading message center
 2344: #    if ($env{'form.handgrade'} eq 'yes') {
 2345:     if (1) {
 2346: 	my $result='<div class="LC_grade_message_center">';
 2347:     
 2348: 	$result.='<div class="LC_grade_message_center_header">'.
 2349: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2350: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2351: 	my $msgfor = $givenn.' '.$lastname;
 2352: 	if (scalar(@$col_fullnames) > 0) {
 2353: 	    my $lastone = pop(@$col_fullnames);
 2354: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2355: 	}
 2356: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2357: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2358: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2359: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2360: 	    ',\''.$msgfor.'\');" target="_self">'.
 2361: 	    &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
 2362: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2363: 	    ' <img src="'.$request->dir_config('lonIconsURL').
 2364: 	    '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
 2365: 	    '<br />&nbsp;('.
 2366: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2367: 	$result.='</div></div>';
 2368: 	$request->print($result);
 2369:     }
 2370: 
 2371:     my %seen = ();
 2372:     my @partlist;
 2373:     my @gradePartRespid;
 2374:     my @part_response_id = &flatten_responseType($responseType);
 2375:     $request->print(
 2376:         '<div class="LC_Box">'
 2377:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2378:     );
 2379:     $request->print(&gradeBox_start());
 2380:     foreach my $part_response_id (@part_response_id) {
 2381:     	my ($partid,$respid) = @{ $part_response_id };
 2382: 	my $part_resp = join('_',@{ $part_response_id });
 2383: 	next if ($seen{$partid} > 0);
 2384: 	$seen{$partid}++;
 2385: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2386: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2387: 	push(@partlist,$partid);
 2388: 	push(@gradePartRespid,$partid.'.'.$respid);
 2389: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2390:     }
 2391:     $request->print(&gradeBox_end()); # </div>
 2392:     $request->print('</div>');
 2393: 
 2394:     $request->print('<div class="LC_grade_info_links">');
 2395:     $request->print('</div>');
 2396: 
 2397:     $result='<input type="hidden" name="partlist'.$counter.
 2398: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2399:     $result.='<input type="hidden" name="gradePartRespid'.
 2400: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2401:     my $ctr = 0;
 2402:     while ($ctr < scalar(@partlist)) {
 2403: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2404: 	    $partlist[$ctr].'" />'."\n";
 2405: 	$ctr++;
 2406:     }
 2407:     $request->print($result.''."\n");
 2408: 
 2409: # Done with printing info for one student
 2410: 
 2411:     $request->print('</div>');#LC_grade_show_user
 2412: 
 2413: 
 2414:     # print end of form
 2415:     if ($counter == $total) {
 2416:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2417: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2418: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2419: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2420: 	my $ntstu ='<select name="NTSTU">'.
 2421: 	    '<option>1</option><option>2</option>'.
 2422: 	    '<option>3</option><option>5</option>'.
 2423: 	    '<option>7</option><option>10</option></select>'."\n";
 2424: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2425: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2426:         $endform.=&mt('[_1]student(s)',$ntstu);
 2427: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2428: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2429: 	    '<input type="button" value="'.&mt('Next').'" '.
 2430: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2431:         $endform.='<span class="LC_warning">'.
 2432:                   &mt('(Next and Previous (student) do not save the scores.)').
 2433:                   '</span>'."\n" ;
 2434:         $endform.="<input type='hidden' value='".&get_increment().
 2435:             "' name='increment' />";
 2436: 	$endform.='</td></tr></table></form>';
 2437: 	$request->print($endform);
 2438:     }
 2439:     return '';
 2440: }
 2441: 
 2442: sub check_collaborators {
 2443:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2444:     my ($result,@col_fullnames);
 2445:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2446:     foreach my $part (keys(%$handgrade)) {
 2447: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2448: 					'.maxcollaborators',
 2449: 					$symb,$udom,$uname);
 2450: 	next if ($ncol <= 0);
 2451: 	$part =~ s/\_/\./g;
 2452: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2453: 	my (@good_collaborators, @bad_collaborators);
 2454: 	foreach my $possible_collaborator
 2455: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2456: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2457: 	    next if ($possible_collaborator eq '');
 2458: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
 2459: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2460: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2461: 	    # Doing this grep allows 'fuzzy' specification
 2462: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2463: 			       keys(%$classlist));
 2464: 	    if (! scalar(@matches)) {
 2465: 		push(@bad_collaborators, $possible_collaborator);
 2466: 	    } else {
 2467: 		push(@good_collaborators, @matches);
 2468: 	    }
 2469: 	}
 2470: 	if (scalar(@good_collaborators) != 0) {
 2471: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
 2472: 	    foreach my $name (@good_collaborators) {
 2473: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2474: 		push(@col_fullnames, $givenn.' '.$lastname);
 2475: 		$result.='<li>'.$fullname->{$name}.'</li>';
 2476: 	    }
 2477: 	    $result.='</ol><br />'."\n";
 2478: 	    my ($part)=split(/\./,$part);
 2479: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2480: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2481: 		"\n";
 2482: 	}
 2483: 	if (scalar(@bad_collaborators) > 0) {
 2484: 	    $result.='<div class="LC_warning">';
 2485: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2486: 	    $result .= '</div>';
 2487: 	}         
 2488: 	if (scalar(@bad_collaborators > $ncol)) {
 2489: 	    $result .= '<div class="LC_warning">';
 2490: 	    $result .= &mt('This student has submitted too many '.
 2491: 		'collaborators.  Maximum is [_1].',$ncol);
 2492: 	    $result .= '</div>';
 2493: 	}
 2494:     }
 2495:     return ($result,$fullname,\@col_fullnames);
 2496: }
 2497: 
 2498: #--- Retrieve the last submission for all the parts
 2499: sub get_last_submission {
 2500:     my ($returnhash)=@_;
 2501:     my (@string,$timestamp,%lasthidden);
 2502:     if ($$returnhash{'version'}) {
 2503: 	my %lasthash=();
 2504: 	my ($version);
 2505: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2506: 	    foreach my $key (sort(split(/\:/,
 2507: 					$$returnhash{$version.':keys'}))) {
 2508: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2509: 		$timestamp = 
 2510: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2511: 	    }
 2512: 	}
 2513:         my (%typeparts,%randombytry);
 2514:         my $showsurv = 
 2515:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2516:         foreach my $key (sort(keys(%lasthash))) {
 2517:             if ($key =~ /\.type$/) {
 2518:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2519:                     ($lasthash{$key} eq 'anonsurveycred') ||
 2520:                     ($lasthash{$key} eq 'randomizetry')) {
 2521:                     my ($ign,@parts) = split(/\./,$key);
 2522:                     pop(@parts);
 2523:                     my $id = join('.',@parts);
 2524:                     if ($lasthash{$key} eq 'randomizetry') {
 2525:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
 2526:                     } else {
 2527:                         unless ($showsurv) {
 2528:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2529:                         }
 2530:                     }
 2531:                     delete($lasthash{$key});
 2532:                 }
 2533:             }
 2534:         }
 2535:         my @hidden = keys(%typeparts);
 2536:         my @randomize = keys(%randombytry);
 2537: 	foreach my $key (keys(%lasthash)) {
 2538: 	    next if ($key !~ /\.submission$/);
 2539:             my $hide;
 2540:             if (@hidden) {
 2541:                 foreach my $id (@hidden) {
 2542:                     if ($key =~ /^\Q$id\E/) {
 2543:                         $hide = 'anon';
 2544:                         last;
 2545:                     }
 2546:                 }
 2547:             }
 2548:             unless ($hide) {
 2549:                 if (@randomize) {
 2550:                     foreach my $id (@randomize) {
 2551:                         if ($key =~ /^\Q$id\E/) {
 2552:                             $hide = 'rand';
 2553:                             last;
 2554:                         }
 2555:                     }
 2556:                 }
 2557:             }
 2558: 	    my ($partid,$foo) = split(/submission$/,$key);
 2559: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
 2560:             push(@string, join(':', $key, $hide, $draft, (
 2561:                 ref($lasthash{$key}) eq 'ARRAY' ?
 2562:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
 2563: 	}
 2564:     }
 2565:     if (!@string) {
 2566: 	$string[0] =
 2567: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2568:     }
 2569:     return (\@string,\$timestamp);
 2570: }
 2571: 
 2572: #--- High light keywords, with style choosen by user.
 2573: sub keywords_highlight {
 2574:     my $string    = shift;
 2575:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2576:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2577:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2578:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2579:     foreach my $keyword (@keylist) {
 2580: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2581:     }
 2582:     return $string;
 2583: }
 2584: 
 2585: # For Tasks provide a mechanism to display previous version for one specific student
 2586: 
 2587: sub show_previous_task_version {
 2588:     my ($request,$symb) = @_;
 2589:     if ($symb eq '') {
 2590:         $request->print(
 2591:             '<span class="LC_error">'.
 2592:             &mt('Unable to handle ambiguous references.').
 2593:             '</span>');
 2594:         return '';
 2595:     }
 2596:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
 2597:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2598:     if (!&canview($usec)) {
 2599:         $request->print(
 2600:             '<span class="LC_warning">'.
 2601:             &mt('Unable to view previous version for requested student.').
 2602:             ' '.&mt('([_1] in section [_2] in course id [_3])',
 2603:                     $uname.':'.$udom,$usec,$env{'request.course.id'}).
 2604:             '</span>');
 2605:         return;
 2606:     }
 2607:     my $mode = 'both';
 2608:     my $isTask = ($symb =~/\.task$/);
 2609:     if ($isTask) {
 2610:         if ($env{'form.previousversion'} =~ /^\d+$/) {
 2611:             if ($env{'form.fullname'} eq '') {
 2612:                 $env{'form.fullname'} =
 2613:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
 2614:             }
 2615:             my $probtitle=&Apache::lonnet::gettitle($symb);
 2616:             $request->print("\n\n".
 2617:                             '<div class="LC_grade_show_user">'.
 2618:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 2619:                             '</h2>'."\n");
 2620:             &Apache::lonxml::clear_problem_counter();
 2621:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
 2622:                             {'previousversion' => $env{'form.previousversion'} }));
 2623:             $request->print("\n</div>");
 2624:         }
 2625:     }
 2626:     return;
 2627: }
 2628: 
 2629: sub choose_task_version_form {
 2630:     my ($symb,$uname,$udom,$nomenu) = @_;
 2631:     my $isTask = ($symb =~/\.task$/);
 2632:     my ($current,$version,$result,$js,$displayed,$rowtitle);
 2633:     if ($isTask) {
 2634:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 2635:                                               $udom,$uname);
 2636:         if (($record{'resource.0.version'} eq '') ||
 2637:             ($record{'resource.0.version'} < 2)) {
 2638:             return ($record{'resource.0.version'},
 2639:                     $record{'resource.0.version'},$result,$js);
 2640:         } else {
 2641:             $current = $record{'resource.0.version'};
 2642:         }
 2643:         if ($env{'form.previousversion'}) {
 2644:             $displayed = $env{'form.previousversion'};
 2645:             $rowtitle = &mt('Choose another version:')
 2646:         } else {
 2647:             $displayed = $current;
 2648:             $rowtitle = &mt('Show earlier version:');
 2649:         }
 2650:         $result = '<div class="LC_left_float">';
 2651:         my $list;
 2652:         my $numversions = 0;
 2653:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
 2654:             if ($i == $current) {
 2655:                 if (!$env{'form.previousversion'} || $nomenu) {
 2656:                     next;
 2657:                 } else {
 2658:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
 2659:                     $numversions ++;
 2660:                 }
 2661:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
 2662:                 unless ($i == $env{'form.previousversion'}) {
 2663:                     $numversions ++;
 2664:                 }
 2665:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
 2666:             }
 2667:         }
 2668:         if ($numversions) {
 2669:             $symb = &HTML::Entities::encode($symb,'<>"&');
 2670:             $result .=
 2671:                 '<form name="getprev" method="post" action=""'.
 2672:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
 2673:                 &Apache::loncommon::start_data_table().
 2674:                 &Apache::loncommon::start_data_table_row().
 2675:                 '<th align="left">'.$rowtitle.'</th>'.
 2676:                 '<td><select name="version">'.
 2677:                 '<option>'.&mt('Select').'</option>'.
 2678:                 $list.
 2679:                 '</select></td>'.
 2680:                 &Apache::loncommon::end_data_table_row();
 2681:             unless ($nomenu) {
 2682:                 $result .= &Apache::loncommon::start_data_table_row().
 2683:                 '<th align="left">'.&mt('Open in new window').'</th>'.
 2684:                 '<td><span class="LC_nobreak">'.
 2685:                 '<label><input type="radio" name="prevwin" value="1" />'.
 2686:                 &mt('Yes').'</label>'.
 2687:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
 2688:                 '</span></td>'.
 2689:                 &Apache::loncommon::end_data_table_row();
 2690:             }
 2691:             $result .=
 2692:                 &Apache::loncommon::start_data_table_row().
 2693:                 '<th align="left">&nbsp;</th>'.
 2694:                 '<td>'.
 2695:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
 2696:                 '</td>'.
 2697:                 &Apache::loncommon::end_data_table_row().
 2698:                 &Apache::loncommon::end_data_table().
 2699:                 '</form>';
 2700:             $js = &previous_display_javascript($nomenu,$current);
 2701:         } elsif ($displayed && $nomenu) {
 2702:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
 2703:         } else {
 2704:             $result .= &mt('No previous versions to show for this student');
 2705:         }
 2706:         $result .= '</div>';
 2707:     }
 2708:     return ($current,$displayed,$result,$js);
 2709: }
 2710: 
 2711: sub previous_display_javascript {
 2712:     my ($nomenu,$current) = @_;
 2713:     my $js = <<"JSONE";
 2714: <script type="text/javascript">
 2715: // <![CDATA[
 2716: function previousVersion(uname,udom,symb) {
 2717:     var current = '$current';
 2718:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
 2719:     var prevstr = new RegExp("^\\\\d+\$");
 2720:     if (!prevstr.test(version)) {
 2721:         return false;
 2722:     }
 2723:     var url = '';
 2724:     if (version == current) {
 2725:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
 2726:     } else {
 2727:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
 2728:     }
 2729: JSONE
 2730:     if ($nomenu) {
 2731:         $js .= <<"JSTWO";
 2732:     document.location.href = url;
 2733: JSTWO
 2734:     } else {
 2735:         $js .= <<"JSTHREE";
 2736:     var newwin = 0;
 2737:     for (var i=0; i<document.getprev.prevwin.length; i++) {
 2738:         if (document.getprev.prevwin[i].checked == true) {
 2739:             newwin = document.getprev.prevwin[i].value;
 2740:         }
 2741:     }
 2742:     if (newwin == 1) {
 2743:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
 2744:         url = url+'&inhibitmenu=yes';
 2745:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
 2746:             previousWin = window.open(url,'',options,1);
 2747:         } else {
 2748:             previousWin.location.href = url;
 2749:         }
 2750:         previousWin.focus();
 2751:         return false;
 2752:     } else {
 2753:         document.location.href = url;
 2754:         return false;
 2755:     }
 2756: JSTHREE
 2757:     }
 2758:     $js .= <<"ENDJS";
 2759:     return false;
 2760: }
 2761: // ]]>
 2762: </script>
 2763: ENDJS
 2764: 
 2765: }
 2766: 
 2767: #--- Called from submission routine
 2768: sub processHandGrade {
 2769:     my ($request,$symb) = @_;
 2770:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2771:     my $button = $env{'form.gradeOpt'};
 2772:     my $ngrade = $env{'form.NCT'};
 2773:     my $ntstu  = $env{'form.NTSTU'};
 2774:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2775:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2776: 
 2777:     if ($button eq 'Save & Next') {
 2778: 	my $ctr = 0;
 2779: 	while ($ctr < $ngrade) {
 2780: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2781: 	    my ($errorflag,$pts,$wgt,$numhidden) = 
 2782:                 &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2783: 	    if ($errorflag eq 'no_score') {
 2784: 		$ctr++;
 2785: 		next;
 2786: 	    }
 2787: 	    if ($errorflag eq 'not_allowed') {
 2788: 		$request->print(
 2789:                     '<span class="LC_error">'
 2790:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
 2791:                    .'</span>');
 2792: 		$ctr++;
 2793: 		next;
 2794: 	    }
 2795:             if ($numhidden) {
 2796:                 $request->print(
 2797:                     '<span class="LC_info">'
 2798:                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
 2799:                    .'</span><br />');
 2800:             }
 2801: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2802: 	    my ($subject,$message,$msgstatus) = ('','','');
 2803: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2804:             my ($feedurl,$showsymb) =
 2805: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2806: 	    my $messagetail;
 2807: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2808: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2809: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2810: 		$subject.=' ['.$restitle.']';
 2811: 		my (@msgnum) = split(/,/,$includemsg);
 2812: 		foreach (@msgnum) {
 2813: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2814: 		}
 2815: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2816: 		if ($env{'form.withgrades'.$ctr}) {
 2817: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2818: 		    $messagetail = " for <a href=\"".
 2819: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
 2820: 		}
 2821: 		$msgstatus = 
 2822:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2823: 						     $message.$messagetail,
 2824:                                                      undef,$feedurl,undef,
 2825:                                                      undef,undef,$showsymb,
 2826:                                                      $restitle);
 2827: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 2828: 				$msgstatus.'<br />');
 2829: 	    }
 2830: 	    if ($env{'form.collaborator'.$ctr}) {
 2831: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2832: 		foreach my $collabstr (@collabstrs) {
 2833: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2834: 		    foreach my $collaborator (@collaborators) {
 2835: 			my ($errorflag,$pts,$wgt) = 
 2836: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2837: 					   $env{'form.unamedom'.$ctr},$part);
 2838: 			if ($errorflag eq 'not_allowed') {
 2839: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2840: 			    next;
 2841: 			} elsif ($message ne '') {
 2842: 			    my ($baseurl,$showsymb) = 
 2843: 				&get_feedurl_and_symb($symb,$collaborator,
 2844: 						      $udom);
 2845: 			    if ($env{'form.withgrades'.$ctr}) {
 2846: 				$messagetail = " for <a href=\"".
 2847:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
 2848: 			    }
 2849: 			    $msgstatus = 
 2850: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2851: 			}
 2852: 		    }
 2853: 		}
 2854: 	    }
 2855: 	    $ctr++;
 2856: 	}
 2857:     }
 2858: 
 2859: #    if ($env{'form.handgrade'} eq 'yes') {
 2860:     if (1) {
 2861: 	# Keywords sorted in alphabatical order
 2862: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2863: 	my %keyhash = ();
 2864: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2865: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2866: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2867: 	$env{'form.keywords'} = join(' ',@keywords);
 2868: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2869: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2870: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2871: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2872: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2873: 
 2874: 	# message center - Order of message gets changed. Blank line is eliminated.
 2875: 	# New messages are saved in env for the next student.
 2876: 	# All messages are saved in nohist_handgrade.db
 2877: 	my ($ctr,$idx) = (1,1);
 2878: 	while ($ctr <= $env{'form.savemsgN'}) {
 2879: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2880: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2881: 		$idx++;
 2882: 	    }
 2883: 	    $ctr++;
 2884: 	}
 2885: 	$ctr = 0;
 2886: 	while ($ctr < $ngrade) {
 2887: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2888: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2889: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2890: 		$idx++;
 2891: 	    }
 2892: 	    $ctr++;
 2893: 	}
 2894: 	$env{'form.savemsgN'} = --$idx;
 2895: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2896: 	my $putresult = &Apache::lonnet::put
 2897: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2898:     }
 2899:     # Called by Save & Refresh from Highlight Attribute Window
 2900:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2901:     if ($env{'form.refresh'} eq 'on') {
 2902: 	my ($ctr,$total) = (0,0);
 2903: 	while ($ctr < $ngrade) {
 2904: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2905: 	    $ctr++;
 2906: 	}
 2907: 	$env{'form.NTSTU'}=$ngrade;
 2908: 	$ctr = 0;
 2909: 	while ($ctr < $total) {
 2910: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2911: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2912: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2913: 	    &submission($request,$ctr,$total-1,$symb);
 2914: 	    $ctr++;
 2915: 	}
 2916: 	return '';
 2917:     }
 2918: 
 2919:     # Get the next/previous one or group of students
 2920:     my $firststu = $env{'form.unamedom0'};
 2921:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2922:     my $ctr = 2;
 2923:     while ($laststu eq '') {
 2924: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2925: 	$ctr++;
 2926: 	$laststu = $firststu if ($ctr > $ngrade);
 2927:     }
 2928: 
 2929:     my (@parsedlist,@nextlist);
 2930:     my ($nextflg) = 0;
 2931:     foreach my $item (sort 
 2932: 	     {
 2933: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2934: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2935: 		 }
 2936: 		 return $a cmp $b;
 2937: 	     } (keys(%$fullname))) {
 2938: # FIXME: this is fishy, looks like the button label
 2939: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2940: 	    push(@parsedlist,$item);
 2941: 	}
 2942: 	$nextflg = 1 if ($item eq $laststu);
 2943: 	if ($button eq 'Previous') {
 2944: 	    last if ($item eq $firststu);
 2945: 	    push(@parsedlist,$item);
 2946: 	}
 2947:     }
 2948:     $ctr = 0;
 2949: # FIXME: this is fishy, looks like the button label
 2950:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2951:     my $res_error;
 2952:     my ($partlist) = &response_type($symb,\$res_error);
 2953:     if ($res_error) {
 2954:         $request->print(&navmap_errormsg());
 2955:         return;
 2956:     }
 2957:     foreach my $student (@parsedlist) {
 2958: 	my $submitonly=$env{'form.submitonly'};
 2959: 	my ($uname,$udom) = split(/:/,$student);
 2960: 	
 2961: 	if ($submitonly eq 'queued') {
 2962: 	    my %queue_status = 
 2963: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2964: 							$udom,$uname);
 2965: 	    next if (!defined($queue_status{'gradingqueue'}));
 2966: 	}
 2967: 
 2968: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2969: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2970: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2971: 	    my $submitted = 0;
 2972: 	    my $ungraded = 0;
 2973: 	    my $incorrect = 0;
 2974: 	    foreach my $item (keys(%status)) {
 2975: 		$submitted = 1 if ($status{$item} ne 'nothing');
 2976: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 2977: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 2978: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 2979: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2980: 		    $submitted = 0;
 2981: 		}
 2982: 	    }
 2983: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2984: 				     $submitonly eq 'incorrect' ||
 2985: 				     $submitonly eq 'graded'));
 2986: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2987: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2988: 	}
 2989: 	push(@nextlist,$student) if ($ctr < $ntstu);
 2990: 	last if ($ctr == $ntstu);
 2991: 	$ctr++;
 2992:     }
 2993: 
 2994:     $ctr = 0;
 2995:     my $total = scalar(@nextlist)-1;
 2996: 
 2997:     foreach (sort(@nextlist)) {
 2998: 	my ($uname,$udom,$submitter) = split(/:/);
 2999: 	$env{'form.student'}  = $uname;
 3000: 	$env{'form.userdom'}  = $udom;
 3001: 	$env{'form.fullname'} = $$fullname{$_};
 3002: 	&submission($request,$ctr,$total,$symb);
 3003: 	$ctr++;
 3004:     }
 3005:     if ($total < 0) {
 3006: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
 3007: 	$request->print($the_end);
 3008:     }
 3009:     return '';
 3010: }
 3011: 
 3012: #---- Save the score and award for each student, if changed
 3013: sub saveHandGrade {
 3014:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 3015:     my @version_parts;
 3016:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 3017: 					   $env{'request.course.id'});
 3018:     if (!&canmodify($usec)) { return('not_allowed'); }
 3019:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 3020:     my @parts_graded;
 3021:     my %newrecord  = ();
 3022:     my ($pts,$wgt,$totchg) = ('','',0);
 3023:     my %aggregate = ();
 3024:     my $aggregateflag = 0;
 3025:     if ($env{'form.HIDE'.$newflg}) {
 3026:         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
 3027:         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
 3028:         $totchg += $numchgs;
 3029:     }
 3030:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 3031:     foreach my $new_part (@parts) {
 3032: 	#collaborator ($submi may vary for different parts
 3033: 	if ($submitter && $new_part ne $part) { next; }
 3034: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 3035: 	if ($dropMenu eq 'excused') {
 3036: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 3037: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 3038: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 3039: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 3040: 		}
 3041: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3042: 	    }
 3043: 	} elsif ($dropMenu eq 'reset status'
 3044: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 3045: 	    foreach my $key (keys(%record)) {
 3046: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 3047: 	    }
 3048: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3049: 		"$env{'user.name'}:$env{'user.domain'}";
 3050:             my $totaltries = $record{'resource.'.$part.'.tries'};
 3051: 
 3052:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 3053: 					       [$new_part]);
 3054:             my $aggtries =$totaltries;
 3055:             if ($last_resets{$new_part}) {
 3056:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 3057: 					   $new_part);
 3058:             }
 3059: 
 3060:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 3061:             if ($aggtries > 0) {
 3062:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3063:                 $aggregateflag = 1;
 3064:             }
 3065: 	} elsif ($dropMenu eq '') {
 3066: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 3067: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 3068: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 3069: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 3070: 		next;
 3071: 	    }
 3072: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 3073: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 3074: 	    my $partial= $pts/$wgt;
 3075: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 3076: 		#do not update score for part if not changed.
 3077:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 3078: 		next;
 3079: 	    } else {
 3080: 	        push(@parts_graded,$new_part);
 3081: 	    }
 3082: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 3083: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 3084: 	    }
 3085: 	    my $reckey = 'resource.'.$new_part.'.solved';
 3086: 	    if ($partial == 0) {
 3087: 		if ($record{$reckey} ne 'incorrect_by_override') {
 3088: 		    $newrecord{$reckey} = 'incorrect_by_override';
 3089: 		}
 3090: 	    } else {
 3091: 		if ($record{$reckey} ne 'correct_by_override') {
 3092: 		    $newrecord{$reckey} = 'correct_by_override';
 3093: 		}
 3094: 	    }	    
 3095: 	    if ($submitter && 
 3096: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 3097: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 3098: 	    }
 3099: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3100: 		"$env{'user.name'}:$env{'user.domain'}";
 3101: 	}
 3102: 	# unless problem has been graded, set flag to version the submitted files
 3103: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 3104: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 3105: 	        $dropMenu eq 'reset status')
 3106: 	   {
 3107: 	    push(@version_parts,$new_part);
 3108: 	}
 3109:     }
 3110:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3111:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3112: 
 3113:     if (%newrecord) {
 3114:         if (@version_parts) {
 3115:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 3116:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 3117: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 3118: 	    foreach my $new_part (@version_parts) {
 3119: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 3120: 				$new_part,\%newrecord);
 3121: 	    }
 3122:         }
 3123: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 3124: 				$env{'request.course.id'},$domain,$stuname);
 3125: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 3126: 				     $cdom,$cnum,$domain,$stuname);
 3127:     }
 3128:     if ($aggregateflag) {
 3129:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3130: 			      $cdom,$cnum);
 3131:     }
 3132:     return ('',$pts,$wgt,$totchg);
 3133: }
 3134: 
 3135: sub makehidden {
 3136:     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
 3137:     return unless (ref($record) eq 'HASH');
 3138:     my %modified;
 3139:     my $numchanged = 0;
 3140:     if (exists($record->{$version.':keys'})) {
 3141:         my $partsregexp = $parts;
 3142:         $partsregexp =~ s/,/|/g;
 3143:         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
 3144:             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
 3145:                  my $item = $1;
 3146:                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
 3147:                      $modified{$key} = $record->{$version.':'.$key};
 3148:                  }
 3149:             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
 3150:                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
 3151:             } elsif ($key =~ /^(ip|timestamp|host)$/) {
 3152:                 $modified{$key} = $record->{$version.':'.$key};
 3153:             }
 3154:         }
 3155:         if (keys(%modified)) {
 3156:             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
 3157:                                           $domain,$stuname,$tolog) eq 'ok') {
 3158:                 $numchanged ++;
 3159:             }
 3160:         }
 3161:     }
 3162:     return $numchanged;
 3163: }
 3164: 
 3165: sub check_and_remove_from_queue {
 3166:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 3167:     my @ungraded_parts;
 3168:     foreach my $part (@{$parts}) {
 3169: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 3170: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 3171: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 3172: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 3173: 		) {
 3174: 	    push(@ungraded_parts, $part);
 3175: 	}
 3176:     }
 3177:     if ( !@ungraded_parts ) {
 3178: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 3179: 					       $cnum,$domain,$stuname);
 3180:     }
 3181: }
 3182: 
 3183: sub handback_files {
 3184:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 3185:     my $portfolio_root = '/userfiles/portfolio';
 3186:     my $res_error;
 3187:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3188:     if ($res_error) {
 3189:         $request->print('<br />'.&navmap_errormsg().'<br />');
 3190:         return;
 3191:     }
 3192:     my @handedback;
 3193:     my $file_msg;
 3194:     my @part_response_id = &flatten_responseType($responseType);
 3195:     foreach my $part_response_id (@part_response_id) {
 3196:     	my ($part_id,$resp_id) = @{ $part_response_id };
 3197: 	my $part_resp = join('_',@{ $part_response_id });
 3198:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
 3199:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
 3200:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
 3201:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
 3202:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
 3203:                     my ($directory,$answer_file) = 
 3204:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
 3205:                     my ($answer_name,$answer_ver,$answer_ext) =
 3206: 		        &Apache::lonnet::file_name_version_ext($answer_file);
 3207: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 3208:                     my $getpropath = 1;
 3209:                     my ($dir_list,$listerror) = 
 3210:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
 3211:                                                  $domain,$stuname,$getpropath);
 3212: 		    my $version = &Apache::lonnet::get_next_version($answer_name,$answer_ext,$dir_list);
 3213:                     # fix filename
 3214:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 3215:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 3216:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
 3217:             	                                $save_file_name);
 3218:                     if ($result !~ m|^/uploaded/|) {
 3219:                         $request->print('<br /><span class="LC_error">'.
 3220:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 3221:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
 3222:                                         '</span>');
 3223:                     } else {
 3224:                         # mark the file as read only
 3225:                         push(@handedback,$save_file_name);
 3226: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 3227: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 3228: 			}
 3229:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 3230: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
 3231:                     }
 3232:                     $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>'));
 3233:                 }
 3234:             }
 3235:         }
 3236:     }
 3237:     if (@handedback > 0) {
 3238:         $request->print('<br />');
 3239:         my @what = ($symb,$env{'request.course.id'},'handback');
 3240:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
 3241:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
 3242:         my ($subject,$message);
 3243:         if (scalar(@handedback) == 1) {
 3244:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
 3245:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
 3246:         } else {
 3247:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
 3248:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
 3249:         }
 3250:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
 3251:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
 3252:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
 3253:         my ($feedurl,$showsymb) =
 3254:             &get_feedurl_and_symb($symb,$domain,$stuname);
 3255:         my $restitle = &Apache::lonnet::gettitle($symb);
 3256:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
 3257:         my $msgstatus =
 3258:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
 3259:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
 3260:                  $restitle);
 3261:         if ($msgstatus) {
 3262:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
 3263:         }
 3264:     }
 3265:     return;
 3266: }
 3267: 
 3268: sub get_feedurl_and_symb {
 3269:     my ($symb,$uname,$udom) = @_;
 3270:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3271:     $url = &Apache::lonnet::clutter($url);
 3272:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 3273: 					$symb,$udom,$uname);
 3274:     if ($encrypturl =~ /^yes$/i) {
 3275: 	&Apache::lonenc::encrypted(\$url,1);
 3276: 	&Apache::lonenc::encrypted(\$symb,1);
 3277:     }
 3278:     return ($url,$symb);
 3279: }
 3280: 
 3281: sub get_submitted_files {
 3282:     my ($udom,$uname,$partid,$respid,$record) = @_;
 3283:     my @files;
 3284:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 3285:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 3286:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 3287:     	    push(@files,$file_url.$file);
 3288:         }
 3289:     }
 3290:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 3291:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 3292:     }
 3293:     return (\@files);
 3294: }
 3295: 
 3296: # ----------- Provides number of tries since last reset.
 3297: sub get_num_tries {
 3298:     my ($record,$last_reset,$part) = @_;
 3299:     my $timestamp = '';
 3300:     my $num_tries = 0;
 3301:     if ($$record{'version'}) {
 3302:         for (my $version=$$record{'version'};$version>=1;$version--) {
 3303:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 3304:                 $timestamp = $$record{$version.':timestamp'};
 3305:                 if ($timestamp > $last_reset) {
 3306:                     $num_tries ++;
 3307:                 } else {
 3308:                     last;
 3309:                 }
 3310:             }
 3311:         }
 3312:     }
 3313:     return $num_tries;
 3314: }
 3315: 
 3316: # ----------- Determine decrements required in aggregate totals 
 3317: sub decrement_aggs {
 3318:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 3319:     my %decrement = (
 3320:                         attempts => 0,
 3321:                         users => 0,
 3322:                         correct => 0
 3323:                     );
 3324:     $decrement{'attempts'} = $aggtries;
 3325:     if ($solvedstatus =~ /^correct/) {
 3326:         $decrement{'correct'} = 1;
 3327:     }
 3328:     if ($aggtries == $totaltries) {
 3329:         $decrement{'users'} = 1;
 3330:     }
 3331:     foreach my $type (keys(%decrement)) {
 3332:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 3333:     }
 3334:     return;
 3335: }
 3336: 
 3337: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3338: sub get_last_resets {
 3339:     my ($symb,$courseid,$partids) =@_;
 3340:     my %last_resets;
 3341:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3342:     my $cname = $env{'course.'.$courseid.'.num'};
 3343:     my @keys;
 3344:     foreach my $part (@{$partids}) {
 3345: 	push(@keys,"$symb\0$part\0resettime");
 3346:     }
 3347:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3348: 				     $cdom,$cname);
 3349:     foreach my $part (@{$partids}) {
 3350: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3351:     }
 3352:     return %last_resets;
 3353: }
 3354: 
 3355: # ----------- Handles creating versions for portfolio files as answers
 3356: sub version_portfiles {
 3357:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3358:     my $version_parts = join('|',@$v_flag);
 3359:     my @returned_keys;
 3360:     my $parts = join('|', @$parts_graded);
 3361:     foreach my $key (keys(%$record)) {
 3362:         my $new_portfiles;
 3363:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3364:             my @versioned_portfiles;
 3365:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3366:             if (@portfiles) {
 3367:                 &Apache::lonnet::portfiles_versioning($symb,$domain,$stu_name,\@portfiles,
 3368:                                                       \@versioned_portfiles);
 3369:             }
 3370:             $$record{$key} = join(',',@versioned_portfiles);
 3371:             push(@returned_keys,$key);
 3372:         }
 3373:     } 
 3374:     return (@returned_keys);   
 3375: }
 3376: 
 3377: #--------------------------------------------------------------------------------------
 3378: #
 3379: #-------------------------- Next few routines handles grading by section or whole class
 3380: #
 3381: #--- Javascript to handle grading by section or whole class
 3382: sub viewgrades_js {
 3383:     my ($request) = shift;
 3384: 
 3385:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3386:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
 3387:    function writePoint(partid,weight,point) {
 3388: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3389: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3390: 	if (point == "textval") {
 3391: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3392: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3393: 		alert("$alertmsg"+parseFloat(point));
 3394: 		var resetbox = false;
 3395: 		for (var i=0; i<radioButton.length; i++) {
 3396: 		    if (radioButton[i].checked) {
 3397: 			textbox.value = i;
 3398: 			resetbox = true;
 3399: 		    }
 3400: 		}
 3401: 		if (!resetbox) {
 3402: 		    textbox.value = "";
 3403: 		}
 3404: 		return;
 3405: 	    }
 3406: 	    if (parseFloat(point) > parseFloat(weight)) {
 3407: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3408: 				   ") greater than the weight for the part. Accept?");
 3409: 		if (resp == false) {
 3410: 		    textbox.value = "";
 3411: 		    return;
 3412: 		}
 3413: 	    }
 3414: 	    for (var i=0; i<radioButton.length; i++) {
 3415: 		radioButton[i].checked=false;
 3416: 		if (parseFloat(point) == i) {
 3417: 		    radioButton[i].checked=true;
 3418: 		}
 3419: 	    }
 3420: 
 3421: 	} else {
 3422: 	    textbox.value = parseFloat(point);
 3423: 	}
 3424: 	for (i=0;i<document.classgrade.total.value;i++) {
 3425: 	    var user = document.classgrade["ctr"+i].value;
 3426: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3427: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3428: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3429: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3430: 	    if (saveval != "correct") {
 3431: 		scorename.value = point;
 3432: 		if (selname[0].selected != true) {
 3433: 		    selname[0].selected = true;
 3434: 		}
 3435: 	    }
 3436: 	}
 3437: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3438:     }
 3439: 
 3440:     function writeRadText(partid,weight) {
 3441: 	var selval   = document.classgrade["SELVAL_"+partid];
 3442: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3443:         var override = document.classgrade["FORCE_"+partid].checked;
 3444: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3445: 	if (selval[1].selected || selval[2].selected) {
 3446: 	    for (var i=0; i<radioButton.length; i++) {
 3447: 		radioButton[i].checked=false;
 3448: 
 3449: 	    }
 3450: 	    textbox.value = "";
 3451: 
 3452: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3453: 		var user = document.classgrade["ctr"+i].value;
 3454: 		user = user.replace(new RegExp(':', 'g'),"_");
 3455: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3456: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3457: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3458: 		if ((saveval != "correct") || override) {
 3459: 		    scorename.value = "";
 3460: 		    if (selval[1].selected) {
 3461: 			selname[1].selected = true;
 3462: 		    } else {
 3463: 			selname[2].selected = true;
 3464: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3465: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3466: 		    }
 3467: 		}
 3468: 	    }
 3469: 	} else {
 3470: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3471: 		var user = document.classgrade["ctr"+i].value;
 3472: 		user = user.replace(new RegExp(':', 'g'),"_");
 3473: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3474: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3475: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3476: 		if ((saveval != "correct") || override) {
 3477: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3478: 		    selname[0].selected = true;
 3479: 		}
 3480: 	    }
 3481: 	}	    
 3482:     }
 3483: 
 3484:     function changeSelect(partid,user) {
 3485: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3486: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3487: 	var point  = textbox.value;
 3488: 	var weight = document.classgrade["weight_"+partid].value;
 3489: 
 3490: 	if (isNaN(point) || parseFloat(point) < 0) {
 3491: 	    alert("$alertmsg"+parseFloat(point));
 3492: 	    textbox.value = "";
 3493: 	    return;
 3494: 	}
 3495: 	if (parseFloat(point) > parseFloat(weight)) {
 3496: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3497: 			       ") greater than the weight of the part. Accept?");
 3498: 	    if (resp == false) {
 3499: 		textbox.value = "";
 3500: 		return;
 3501: 	    }
 3502: 	}
 3503: 	selval[0].selected = true;
 3504:     }
 3505: 
 3506:     function changeOneScore(partid,user) {
 3507: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3508: 	if (selval[1].selected || selval[2].selected) {
 3509: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3510: 	    if (selval[2].selected) {
 3511: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3512: 	    }
 3513:         }
 3514:     }
 3515: 
 3516:     function resetEntry(numpart) {
 3517: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3518: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3519: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3520: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3521: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3522: 	    for (var i=0; i<radioButton.length; i++) {
 3523: 		radioButton[i].checked=false;
 3524: 
 3525: 	    }
 3526: 	    textbox.value = "";
 3527: 	    selval[0].selected = true;
 3528: 
 3529: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3530: 		var user = document.classgrade["ctr"+i].value;
 3531: 		user = user.replace(new RegExp(':', 'g'),"_");
 3532: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3533: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3534: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3535: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3536: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3537: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3538: 		if (saveselval == "excused") {
 3539: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3540: 		} else {
 3541: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3542: 		}
 3543: 	    }
 3544: 	}
 3545:     }
 3546: 
 3547: VIEWJAVASCRIPT
 3548: }
 3549: 
 3550: #--- show scores for a section or whole class w/ option to change/update a score
 3551: sub viewgrades {
 3552:     my ($request,$symb) = @_;
 3553:     &viewgrades_js($request);
 3554: 
 3555:     #need to make sure we have the correct data for later EXT calls, 
 3556:     #thus invalidate the cache
 3557:     &Apache::lonnet::devalidatecourseresdata(
 3558:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3559:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3560:     &Apache::lonnet::clear_EXT_cache_status();
 3561: 
 3562:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3563: 
 3564:     #view individual student submission form - called using Javascript viewOneStudent
 3565:     $result.=&jscriptNform($symb);
 3566: 
 3567:     #beginning of class grading form
 3568:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3569:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3570: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3571: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3572: 	&build_section_inputs().
 3573: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3574: 
 3575:     my ($common_header,$specific_header);
 3576:     if ($env{'form.section'} eq 'all') {
 3577: 	$common_header = &mt('Assign Common Grade to Class');
 3578:         $specific_header = &mt('Assign Grade to Specific Students in Class');
 3579:     } elsif ($env{'form.section'} eq 'none') {
 3580:         $common_header = &mt('Assign Common Grade to Students in no Section');
 3581: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
 3582:     } else {
 3583:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3584:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3585: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3586:     }
 3587:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
 3588:     #radio buttons/text box for assigning points for a section or class.
 3589:     #handles different parts of a problem
 3590:     my $res_error;
 3591:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3592:     if ($res_error) {
 3593:         return &navmap_errormsg();
 3594:     }
 3595:     my %weight = ();
 3596:     my $ctsparts = 0;
 3597:     my %seen = ();
 3598:     my @part_response_id = &flatten_responseType($responseType);
 3599:     foreach my $part_response_id (@part_response_id) {
 3600:     	my ($partid,$respid) = @{ $part_response_id };
 3601: 	my $part_resp = join('_',@{ $part_response_id });
 3602: 	next if $seen{$partid};
 3603: 	$seen{$partid}++;
 3604: 	my $handgrade=$$handgrade{$part_resp};
 3605: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3606: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3607: 
 3608: 	my $display_part=&get_display_part($partid,$symb);
 3609: 	my $radio.='<table border="0"><tr>';  
 3610: 	my $ctr = 0;
 3611: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3612: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3613: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3614: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3615: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3616: 	    $ctr++;
 3617: 	}
 3618: 	$radio.='</tr></table>';
 3619: 	my $line = '<input type="text" name="TEXTVAL_'.
 3620: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 3621: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3622: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3623:         $line.= '<td><b>'.&mt('Grade Status').':</b>'.
 3624:             '<select name="SELVAL_'.$partid.'" '.
 3625:             'onchange="javascript:writeRadText(\''.$partid.'\','.
 3626:                 $weight{$partid}.')"> '.
 3627: 	    '<option selected="selected"> </option>'.
 3628: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3629: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3630: 	    '</select></td>'.
 3631:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3632: 	$line.='<input type="hidden" name="partid_'.
 3633: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3634: 	$line.='<input type="hidden" name="weight_'.
 3635: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3636: 
 3637: 	$result.=
 3638: 	    &Apache::loncommon::start_data_table_row()."\n".
 3639: 	    '<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>'.
 3640: 	    &Apache::loncommon::end_data_table_row()."\n";
 3641: 	$ctsparts++;
 3642:     }
 3643:     $result.=&Apache::loncommon::end_data_table()."\n".
 3644: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3645:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3646: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 3647: 
 3648:     #table listing all the students in a section/class
 3649:     #header of table
 3650:     $result.= '<h3>'.$specific_header.'</h3>'.
 3651:               &Apache::loncommon::start_data_table().
 3652: 	      &Apache::loncommon::start_data_table_header_row().
 3653: 	      '<th>'.&mt('No.').'</th>'.
 3654: 	      '<th>'.&nameUserString('header')."</th>\n";
 3655:     my $partserror;
 3656:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3657:     if ($partserror) {
 3658:         return &navmap_errormsg();
 3659:     }
 3660:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3661:     my @partids = ();
 3662:     foreach my $part (@parts) {
 3663: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3664:         my $narrowtext = &mt('Tries');
 3665: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3666: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3667: 	my ($partid) = &split_part_type($part);
 3668:         push(@partids,$partid);
 3669: #
 3670: # FIXME: Looks like $display looks at English text
 3671: #
 3672: 	my $display_part=&get_display_part($partid,$symb);
 3673: 	if ($display =~ /^Partial Credit Factor/) {
 3674: 	    $result.='<th>'.
 3675: 		&mt('Score Part: [_1][_2](weight = [_3])',
 3676: 		    $display_part,'<br />',$weight{$partid}).'</th>'."\n";
 3677: 	    next;
 3678: 	    
 3679: 	} else {
 3680: 	    if ($display =~ /Problem Status/) {
 3681: 		my $grade_status_mt = &mt('Grade Status');
 3682: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3683: 	    }
 3684: 	    my $part_mt = &mt('Part:');
 3685: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3686: 	}
 3687: 
 3688: 	$result.='<th>'.$display.'</th>'."\n";
 3689:     }
 3690:     $result.=&Apache::loncommon::end_data_table_header_row();
 3691: 
 3692:     my %last_resets = 
 3693: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3694: 
 3695:     #get info for each student
 3696:     #list all the students - with points and grade status
 3697:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3698:     my $ctr = 0;
 3699:     foreach (sort 
 3700: 	     {
 3701: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3702: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3703: 		 }
 3704: 		 return $a cmp $b;
 3705: 	     } (keys(%$fullname))) {
 3706: 	$ctr++;
 3707: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3708: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3709:     }
 3710:     $result.=&Apache::loncommon::end_data_table();
 3711:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3712:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3713: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 3714:     if (scalar(%$fullname) eq 0) {
 3715: 	my $colspan=3+scalar(@parts);
 3716: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3717:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3718: 	$result='<span class="LC_warning">'.
 3719: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3720: 	        $section_display, $stu_status).
 3721: 	    '</span>';
 3722:     }
 3723:     return $result;
 3724: }
 3725: 
 3726: #--- call by previous routine to display each student
 3727: sub viewstudentgrade {
 3728:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3729:     my ($uname,$udom) = split(/:/,$student);
 3730:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3731:     my %aggregates = (); 
 3732:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3733: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3734: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3735: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3736: 	'\');" target="_self">'.$fullname.'</a> '.
 3737: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3738:     $student=~s/:/_/; # colon doen't work in javascript for names
 3739:     foreach my $apart (@$parts) {
 3740: 	my ($part,$type) = &split_part_type($apart);
 3741: 	my $score=$record{"resource.$part.$type"};
 3742:         $result.='<td align="center">';
 3743:         my ($aggtries,$totaltries);
 3744:         unless (exists($aggregates{$part})) {
 3745: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3746: 
 3747: 	    $aggtries = $totaltries;
 3748:             if ($$last_resets{$part}) {  
 3749:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3750: 					   $part);
 3751:             }
 3752:             $result.='<input type="hidden" name="'.
 3753:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3754:             $result.='<input type="hidden" name="'.
 3755:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3756:             $aggregates{$part} = 1;
 3757:         }
 3758: 	if ($type eq 'awarded') {
 3759: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3760: 	    $result.='<input type="hidden" name="'.
 3761: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3762: 	    $result.='<input type="text" name="'.
 3763: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3764:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3765: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3766: 	} elsif ($type eq 'solved') {
 3767: 	    my ($status,$foo)=split(/_/,$score,2);
 3768: 	    $status = 'nothing' if ($status eq '');
 3769: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3770: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3771: 	    $result.='&nbsp;<select name="'.
 3772: 		'GD_'.$student.'_'.$part.'_solved" '.
 3773:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3774: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3775: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3776: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3777: 	    $result.="</select>&nbsp;</td>\n";
 3778: 	} else {
 3779: 	    $result.='<input type="hidden" name="'.
 3780: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3781: 		    "\n";
 3782: 	    $result.='<input type="text" name="'.
 3783: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3784: 		'value="'.$score.'" size="4" /></td>'."\n";
 3785: 	}
 3786:     }
 3787:     $result.=&Apache::loncommon::end_data_table_row();
 3788:     return $result;
 3789: }
 3790: 
 3791: #--- change scores for all the students in a section/class
 3792: #    record does not get update if unchanged
 3793: sub editgrades {
 3794:     my ($request,$symb) = @_;
 3795: 
 3796:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3797:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3798:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3799: 
 3800:     my $result= &Apache::loncommon::start_data_table().
 3801: 	&Apache::loncommon::start_data_table_header_row().
 3802: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3803: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3804:     my %scoreptr = (
 3805: 		    'correct'  =>'correct_by_override',
 3806: 		    'incorrect'=>'incorrect_by_override',
 3807: 		    'excused'  =>'excused',
 3808: 		    'ungraded' =>'ungraded_attempted',
 3809:                     'credited' =>'credit_attempted',
 3810: 		    'nothing'  => '',
 3811: 		    );
 3812:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3813: 
 3814:     my (@partid);
 3815:     my %weight = ();
 3816:     my %columns = ();
 3817:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3818: 
 3819:     my $partserror;
 3820:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3821:     if ($partserror) {
 3822:         return &navmap_errormsg();
 3823:     }
 3824:     my $header;
 3825:     while ($ctr < $env{'form.totalparts'}) {
 3826: 	my $partid = $env{'form.partid_'.$ctr};
 3827: 	push(@partid,$partid);
 3828: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3829: 	$ctr++;
 3830:     }
 3831:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3832:     foreach my $partid (@partid) {
 3833: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3834: 	    '<th align="center">'.&mt('New Score').'</th>';
 3835: 	$columns{$partid}=2;
 3836: 	foreach my $stores (@parts) {
 3837: 	    my ($part,$type) = &split_part_type($stores);
 3838: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3839: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3840: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3841: 	    $display =~ s/\[Part: \Q$part\E\]//;
 3842:             my $narrowtext = &mt('Tries');
 3843: 	    $display =~ s/Number of Attempts/$narrowtext/;
 3844: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 3845: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 3846: 	    $columns{$partid}+=2;
 3847: 	}
 3848:     }
 3849:     foreach my $partid (@partid) {
 3850: 	my $display_part=&get_display_part($partid,$symb);
 3851: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3852: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3853: 	    '</th>';
 3854: 
 3855:     }
 3856:     $result .= &Apache::loncommon::end_data_table_header_row().
 3857: 	&Apache::loncommon::start_data_table_header_row().
 3858: 	$header.
 3859: 	&Apache::loncommon::end_data_table_header_row();
 3860:     my @noupdate;
 3861:     my ($updateCtr,$noupdateCtr) = (1,1);
 3862:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3863: 	my $line;
 3864: 	my $user = $env{'form.ctr'.$i};
 3865: 	my ($uname,$udom)=split(/:/,$user);
 3866: 	my %newrecord;
 3867: 	my $updateflag = 0;
 3868: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3869: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3870: 	if (!&canmodify($usec)) {
 3871: 	    my $numcols=scalar(@partid)*4+2;
 3872: 	    push(@noupdate,
 3873: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 3874: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 3875: 	    next;
 3876: 	}
 3877:         my %aggregate = ();
 3878:         my $aggregateflag = 0;
 3879: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3880: 	foreach (@partid) {
 3881: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3882: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3883: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3884: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3885: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3886: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3887: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3888: 	    my $score;
 3889: 	    if ($partial eq '') {
 3890: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3891: 	    } elsif ($partial > 0) {
 3892: 		$score = 'correct_by_override';
 3893: 	    } elsif ($partial == 0) {
 3894: 		$score = 'incorrect_by_override';
 3895: 	    }
 3896: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3897: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3898: 
 3899: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3900: 		"$env{'user.name'}:$env{'user.domain'}";
 3901: 	    if ($dropMenu eq 'reset status' &&
 3902: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3903: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3904: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3905: 		$newrecord{'resource.'.$_.'.award'} = '';
 3906: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3907: 		$updateflag = 1;
 3908:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3909:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3910:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3911:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3912:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3913:                     $aggregateflag = 1;
 3914:                 }
 3915: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3916: 		$updateflag = 1;
 3917: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3918: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3919: 		$rec_update++;
 3920: 	    }
 3921: 
 3922: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3923: 		'<td align="center">'.$awarded.
 3924: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3925: 
 3926: 
 3927: 	    my $partid=$_;
 3928: 	    foreach my $stores (@parts) {
 3929: 		my ($part,$type) = &split_part_type($stores);
 3930: 		if ($part !~ m/^\Q$partid\E/) { next;}
 3931: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 3932: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 3933: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 3934: 		if ($awarded ne '' && $awarded ne $old_aw) {
 3935: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 3936: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3937: 		    $updateflag=1;
 3938: 		}
 3939: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3940: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 3941: 	    }
 3942: 	}
 3943: 	$line.="\n";
 3944: 
 3945: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3946: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3947: 
 3948: 	if ($updateflag) {
 3949: 	    $count++;
 3950: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 3951: 				    $udom,$uname);
 3952: 
 3953: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 3954: 					      $cnum,$udom,$uname)) {
 3955: 		# need to figure out if should be in queue.
 3956: 		my %record =  
 3957: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3958: 					     $udom,$uname);
 3959: 		my $all_graded = 1;
 3960: 		my $none_graded = 1;
 3961: 		foreach my $part (@parts) {
 3962: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 3963: 			$all_graded = 0;
 3964: 		    } else {
 3965: 			$none_graded = 0;
 3966: 		    }
 3967: 		}
 3968: 
 3969: 		if ($all_graded || $none_graded) {
 3970: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 3971: 							   $symb,$cdom,$cnum,
 3972: 							   $udom,$uname);
 3973: 		}
 3974: 	    }
 3975: 
 3976: 	    $result.=&Apache::loncommon::start_data_table_row().
 3977: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 3978: 		&Apache::loncommon::end_data_table_row();
 3979: 	    $updateCtr++;
 3980: 	} else {
 3981: 	    push(@noupdate,
 3982: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 3983: 	    $noupdateCtr++;
 3984: 	}
 3985:         if ($aggregateflag) {
 3986:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3987: 				  $cdom,$cnum);
 3988:         }
 3989:     }
 3990:     if (@noupdate) {
 3991: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 3992: 	my $numcols=scalar(@partid)*4+2;
 3993: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 3994: 	    '<td align="center" colspan="'.$numcols.'">'.
 3995: 	    &mt('No Changes Occurred For the Students Below').
 3996: 	    '</td>'.
 3997: 	    &Apache::loncommon::end_data_table_row();
 3998: 	foreach my $line (@noupdate) {
 3999: 	    $result.=
 4000: 		&Apache::loncommon::start_data_table_row().
 4001: 		$line.
 4002: 		&Apache::loncommon::end_data_table_row();
 4003: 	}
 4004:     }
 4005:     $result .= &Apache::loncommon::end_data_table();
 4006:     my $msg = '<p><b>'.
 4007: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 4008: 	    $rec_update,$count).'</b><br />'.
 4009: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 4010: 	'</b></p>';
 4011:     return $title.$msg.$result;
 4012: }
 4013: 
 4014: sub split_part_type {
 4015:     my ($partstr) = @_;
 4016:     my ($temp,@allparts)=split(/_/,$partstr);
 4017:     my $type=pop(@allparts);
 4018:     my $part=join('_',@allparts);
 4019:     return ($part,$type);
 4020: }
 4021: 
 4022: #------------- end of section for handling grading by section/class ---------
 4023: #
 4024: #----------------------------------------------------------------------------
 4025: 
 4026: 
 4027: #----------------------------------------------------------------------------
 4028: #
 4029: #-------------------------- Next few routines handles grading by csv upload
 4030: #
 4031: #--- Javascript to handle csv upload
 4032: sub csvupload_javascript_reverse_associate {
 4033:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4034:     my $error2=&mt('You need to specify at least one grading field');
 4035:   return(<<ENDPICK);
 4036:   function verify(vf) {
 4037:     var foundsomething=0;
 4038:     var founduname=0;
 4039:     var foundID=0;
 4040:     for (i=0;i<=vf.nfields.value;i++) {
 4041:       tw=eval('vf.f'+i+'.selectedIndex');
 4042:       if (i==0 && tw!=0) { foundID=1; }
 4043:       if (i==1 && tw!=0) { founduname=1; }
 4044:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 4045:     }
 4046:     if (founduname==0 && foundID==0) {
 4047: 	alert('$error1');
 4048: 	return;
 4049:     }
 4050:     if (foundsomething==0) {
 4051: 	alert('$error2');
 4052: 	return;
 4053:     }
 4054:     vf.submit();
 4055:   }
 4056:   function flip(vf,tf) {
 4057:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4058:     var i;
 4059:     for (i=0;i<=vf.nfields.value;i++) {
 4060:       //can not pick the same destination field for both name and domain
 4061:       if (((i ==0)||(i ==1)) && 
 4062:           ((tf==0)||(tf==1)) && 
 4063:           (i!=tf) &&
 4064:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4065:         eval('vf.f'+i+'.selectedIndex=0;')
 4066:       }
 4067:     }
 4068:   }
 4069: ENDPICK
 4070: }
 4071: 
 4072: sub csvupload_javascript_forward_associate {
 4073:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4074:     my $error2=&mt('You need to specify at least one grading field');
 4075:   return(<<ENDPICK);
 4076:   function verify(vf) {
 4077:     var foundsomething=0;
 4078:     var founduname=0;
 4079:     var foundID=0;
 4080:     for (i=0;i<=vf.nfields.value;i++) {
 4081:       tw=eval('vf.f'+i+'.selectedIndex');
 4082:       if (tw==1) { foundID=1; }
 4083:       if (tw==2) { founduname=1; }
 4084:       if (tw>3) { foundsomething=1; }
 4085:     }
 4086:     if (founduname==0 && foundID==0) {
 4087: 	alert('$error1');
 4088: 	return;
 4089:     }
 4090:     if (foundsomething==0) {
 4091: 	alert('$error2');
 4092: 	return;
 4093:     }
 4094:     vf.submit();
 4095:   }
 4096:   function flip(vf,tf) {
 4097:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4098:     var i;
 4099:     //can not pick the same destination field twice
 4100:     for (i=0;i<=vf.nfields.value;i++) {
 4101:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4102:         eval('vf.f'+i+'.selectedIndex=0;')
 4103:       }
 4104:     }
 4105:   }
 4106: ENDPICK
 4107: }
 4108: 
 4109: sub csvuploadmap_header {
 4110:     my ($request,$symb,$datatoken,$distotal)= @_;
 4111:     my $javascript;
 4112:     if ($env{'form.upfile_associate'} eq 'reverse') {
 4113: 	$javascript=&csvupload_javascript_reverse_associate();
 4114:     } else {
 4115: 	$javascript=&csvupload_javascript_forward_associate();
 4116:     }
 4117: 
 4118:     $symb = &Apache::lonenc::check_encrypt($symb);
 4119:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
 4120:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
 4121:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
 4122:     my $reverse=&mt("Reverse Association");
 4123:     $request->print(<<ENDPICK);
 4124: <br />
 4125: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 4126: <input type="hidden" name="associate"  value="" />
 4127: <input type="hidden" name="phase"      value="three" />
 4128: <input type="hidden" name="datatoken"  value="$datatoken" />
 4129: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 4130: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 4131: <input type="hidden" name="upfile_associate" 
 4132:                                        value="$env{'form.upfile_associate'}" />
 4133: <input type="hidden" name="symb"       value="$symb" />
 4134: <input type="hidden" name="command"    value="csvuploadoptions" />
 4135: <hr />
 4136: ENDPICK
 4137:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
 4138:     return '';
 4139: 
 4140: }
 4141: 
 4142: sub csvupload_fields {
 4143:     my ($symb,$errorref) = @_;
 4144:     my (@parts) = &getpartlist($symb,$errorref);
 4145:     if (ref($errorref)) {
 4146:         if ($$errorref) {
 4147:             return;
 4148:         }
 4149:     }
 4150: 
 4151:     my @fields=(['ID','Student/Employee ID'],
 4152: 		['username','Student Username'],
 4153: 		['domain','Student Domain']);
 4154:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4155:     foreach my $part (sort(@parts)) {
 4156: 	my @datum;
 4157: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 4158: 	my $name=$part;
 4159: 	if  (!$display) { $display = $name; }
 4160: 	@datum=($name,$display);
 4161: 	if ($name=~/^stores_(.*)_awarded/) {
 4162: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 4163: 	}
 4164: 	push(@fields,\@datum);
 4165:     }
 4166:     return (@fields);
 4167: }
 4168: 
 4169: sub csvuploadmap_footer {
 4170:     my ($request,$i,$keyfields) =@_;
 4171:     my $buttontext = &mt('Assign Grades');
 4172:     $request->print(<<ENDPICK);
 4173: </table>
 4174: <input type="hidden" name="nfields" value="$i" />
 4175: <input type="hidden" name="keyfields" value="$keyfields" />
 4176: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
 4177: </form>
 4178: ENDPICK
 4179: }
 4180: 
 4181: sub checkforfile_js {
 4182:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 4183:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
 4184:     function checkUpload(formname) {
 4185: 	if (formname.upfile.value == "") {
 4186: 	    alert("$alertmsg");
 4187: 	    return false;
 4188: 	}
 4189: 	formname.submit();
 4190:     }
 4191: CSVFORMJS
 4192:     return $result;
 4193: }
 4194: 
 4195: sub upcsvScores_form {
 4196:     my ($request,$symb) = @_;
 4197:     if (!$symb) {return '';}
 4198:     my $result=&checkforfile_js();
 4199:     $result.=&Apache::loncommon::start_data_table().
 4200:              &Apache::loncommon::start_data_table_header_row().
 4201:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
 4202:              &Apache::loncommon::end_data_table_header_row().
 4203:              &Apache::loncommon::start_data_table_row().'<td>';
 4204:     my $upload=&mt("Upload Scores");
 4205:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 4206:     my $ignore=&mt('Ignore First Line');
 4207:     $symb = &Apache::lonenc::check_encrypt($symb);
 4208:     $result.=<<ENDUPFORM;
 4209: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4210: <input type="hidden" name="symb" value="$symb" />
 4211: <input type="hidden" name="command" value="csvuploadmap" />
 4212: $upfile_select
 4213: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 4214: </form>
 4215: ENDUPFORM
 4216:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 4217:                            &mt("How do I create a CSV file from a spreadsheet")).
 4218:              '</td>'.
 4219:             &Apache::loncommon::end_data_table_row().
 4220:             &Apache::loncommon::end_data_table();
 4221:     return $result;
 4222: }
 4223: 
 4224: 
 4225: sub csvuploadmap {
 4226:     my ($request,$symb)= @_;
 4227:     if (!$symb) {return '';}
 4228: 
 4229:     my $datatoken;
 4230:     if (!$env{'form.datatoken'}) {
 4231: 	$datatoken=&Apache::loncommon::upfile_store($request);
 4232:     } else {
 4233: 	$datatoken=$env{'form.datatoken'};
 4234: 	&Apache::loncommon::load_tmp_file($request);
 4235:     }
 4236:     my @records=&Apache::loncommon::upfile_record_sep();
 4237:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 4238:     my ($i,$keyfields);
 4239:     if (@records) {
 4240:         my $fieldserror;
 4241: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 4242:         if ($fieldserror) {
 4243:             $request->print(&navmap_errormsg());
 4244:             return;
 4245:         }
 4246: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 4247: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 4248: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 4249: 							  \@fields);
 4250: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 4251: 	    chop($keyfields);
 4252: 	} else {
 4253: 	    unshift(@fields,['none','']);
 4254: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 4255: 							    \@fields);
 4256:             foreach my $rec (@records) {
 4257:                 my %temp = &Apache::loncommon::record_sep($rec);
 4258:                 if (%temp) {
 4259:                     $keyfields=join(',',sort(keys(%temp)));
 4260:                     last;
 4261:                 }
 4262:             }
 4263: 	}
 4264:     }
 4265:     &csvuploadmap_footer($request,$i,$keyfields);
 4266: 
 4267:     return '';
 4268: }
 4269: 
 4270: sub csvuploadoptions {
 4271:     my ($request,$symb)= @_;
 4272:     my $overwrite=&mt('Overwrite any existing score');
 4273:     $request->print(<<ENDPICK);
 4274: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4275: <input type="hidden" name="command"    value="csvuploadassign" />
 4276: <p>
 4277: <label>
 4278:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4279:    $overwrite
 4280: </label>
 4281: </p>
 4282: ENDPICK
 4283:     my %fields=&get_fields();
 4284:     if (!defined($fields{'domain'})) {
 4285: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4286: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
 4287:     }
 4288:     foreach my $key (sort(keys(%env))) {
 4289: 	if ($key !~ /^form\.(.*)$/) { next; }
 4290: 	my $cleankey=$1;
 4291: 	if ($cleankey eq 'command') { next; }
 4292: 	$request->print('<input type="hidden" name="'.$cleankey.
 4293: 			'"  value="'.$env{$key}.'" />'."\n");
 4294:     }
 4295:     # FIXME do a check for any duplicated user ids...
 4296:     # FIXME do a check for any invalid user ids?...
 4297:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
 4298: <hr /></form>'."\n");
 4299:     return '';
 4300: }
 4301: 
 4302: sub get_fields {
 4303:     my %fields;
 4304:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4305:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4306: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4307: 	    if ($env{'form.f'.$i} ne 'none') {
 4308: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4309: 	    }
 4310: 	} else {
 4311: 	    if ($env{'form.f'.$i} ne 'none') {
 4312: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4313: 	    }
 4314: 	}
 4315:     }
 4316:     return %fields;
 4317: }
 4318: 
 4319: sub csvuploadassign {
 4320:     my ($request,$symb)= @_;
 4321:     if (!$symb) {return '';}
 4322:     my $error_msg = '';
 4323:     &Apache::loncommon::load_tmp_file($request);
 4324:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4325:     my %fields=&get_fields();
 4326:     my $courseid=$env{'request.course.id'};
 4327:     my ($classlist) = &getclasslist('all',0);
 4328:     my @notallowed;
 4329:     my @skipped;
 4330:     my @warnings;
 4331:     my $countdone=0;
 4332:     foreach my $grade (@gradedata) {
 4333: 	my %entries=&Apache::loncommon::record_sep($grade);
 4334: 	my $domain;
 4335: 	if ($entries{$fields{'domain'}}) {
 4336: 	    $domain=$entries{$fields{'domain'}};
 4337: 	} else {
 4338: 	    $domain=$env{'form.default_domain'};
 4339: 	}
 4340: 	$domain=~s/\s//g;
 4341: 	my $username=$entries{$fields{'username'}};
 4342: 	$username=~s/\s//g;
 4343: 	if (!$username) {
 4344: 	    my $id=$entries{$fields{'ID'}};
 4345: 	    $id=~s/\s//g;
 4346: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4347: 	    $username=$ids{$id};
 4348: 	}
 4349: 	if (!exists($$classlist{"$username:$domain"})) {
 4350: 	    my $id=$entries{$fields{'ID'}};
 4351: 	    $id=~s/\s//g;
 4352: 	    if ($id) {
 4353: 		push(@skipped,"$id:$domain");
 4354: 	    } else {
 4355: 		push(@skipped,"$username:$domain");
 4356: 	    }
 4357: 	    next;
 4358: 	}
 4359: 	my $usec=$classlist->{"$username:$domain"}[5];
 4360: 	if (!&canmodify($usec)) {
 4361: 	    push(@notallowed,"$username:$domain");
 4362: 	    next;
 4363: 	}
 4364: 	my %points;
 4365: 	my %grades;
 4366: 	foreach my $dest (keys(%fields)) {
 4367: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4368: 		$dest eq 'domain') { next; }
 4369: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4370: 	    if ($dest=~/stores_(.*)_points/) {
 4371: 		my $part=$1;
 4372: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4373: 					      $symb,$domain,$username);
 4374:                 if ($wgt) {
 4375:                     $entries{$fields{$dest}}=~s/\s//g;
 4376:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4377:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4378:                                           : 'correct_by_override';
 4379:                     if ($pcr>1) {
 4380:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
 4381:                     }
 4382:                     $grades{"resource.$part.awarded"}=$pcr;
 4383:                     $grades{"resource.$part.solved"}=$award;
 4384:                     $points{$part}=1;
 4385:                 } else {
 4386:                     $error_msg = "<br />" .
 4387:                         &mt("Some point values were assigned"
 4388:                             ." for problems with a weight "
 4389:                             ."of zero. These values were "
 4390:                             ."ignored.");
 4391:                 }
 4392: 	    } else {
 4393: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4394: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4395: 		my $store_key=$dest;
 4396: 		$store_key=~s/^stores/resource/;
 4397: 		$store_key=~s/_/\./g;
 4398: 		$grades{$store_key}=$entries{$fields{$dest}};
 4399: 	    }
 4400: 	}
 4401: 	if (! %grades) { 
 4402:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4403:         } else {
 4404: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4405: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4406: 					   $env{'request.course.id'},
 4407: 					   $domain,$username);
 4408: 	   if ($result eq 'ok') {
 4409: # Successfully stored
 4410: 	      $request->print('.');
 4411: # Remove from grading queue
 4412:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
 4413:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
 4414:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
 4415:                                              $domain,$username);
 4416:               $countdone++;
 4417:            } else {
 4418: 	      $request->print("<p><span class=\"LC_error\">".
 4419:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4420:                                   "$username:$domain",$result)."</span></p>");
 4421: 	   }
 4422: 	   $request->rflush();
 4423:         }
 4424:     }
 4425:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 4426:     if (@warnings) {
 4427:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
 4428:         $request->print(join(', ',@warnings));
 4429:     }
 4430:     if (@skipped) {
 4431: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 4432:         $request->print(join(', ',@skipped));
 4433:     }
 4434:     if (@notallowed) {
 4435: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 4436: 	$request->print(join(', ',@notallowed));
 4437:     }
 4438:     $request->print("<br />\n");
 4439:     return $error_msg;
 4440: }
 4441: #------------- end of section for handling csv file upload ---------
 4442: #
 4443: #-------------------------------------------------------------------
 4444: #
 4445: #-------------- Next few routines handle grading by page/sequence
 4446: #
 4447: #--- Select a page/sequence and a student to grade
 4448: sub pickStudentPage {
 4449:     my ($request,$symb) = @_;
 4450: 
 4451:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4452:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
 4453: 
 4454: function checkPickOne(formname) {
 4455:     if (radioSelection(formname.student) == null) {
 4456: 	alert("$alertmsg");
 4457: 	return;
 4458:     }
 4459:     ptr = pullDownSelection(formname.selectpage);
 4460:     formname.page.value = formname["page"+ptr].value;
 4461:     formname.title.value = formname["title"+ptr].value;
 4462:     formname.submit();
 4463: }
 4464: 
 4465: LISTJAVASCRIPT
 4466:     &commonJSfunctions($request);
 4467: 
 4468:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4469:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4470:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4471: 
 4472:     my $result='<h3><span class="LC_info">&nbsp;'.
 4473: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4474: 
 4475:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4476:     my $map_error;
 4477:     my ($titles,$symbx) = &getSymbMap($map_error);
 4478:     if ($map_error) {
 4479:         $request->print(&navmap_errormsg());
 4480:         return; 
 4481:     }
 4482:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4483: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4484: #    my $type=($curpage =~ /\.(page|sequence)/);
 4485: 
 4486:     # Collection of hidden fields
 4487:     my $ctr=0;
 4488:     foreach (@$titles) {
 4489:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4490:         $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4491:         $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4492:         $ctr++;
 4493:     }
 4494:     $result.='<input type="hidden" name="page" />'."\n".
 4495:         '<input type="hidden" name="title" />'."\n";
 4496: 
 4497:     $result.=&build_section_inputs();
 4498:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4499:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4500: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4501: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 4502: 
 4503:     # Show grading options
 4504:     $result.=&Apache::lonhtmlcommon::start_pick_box();
 4505:     my $select = '<select name="selectpage">'."\n";
 4506:     $ctr=0;
 4507:     foreach (@$titles) {
 4508: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4509: 	$select.='<option value="'.$ctr.'"'.
 4510: 	    ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
 4511: 	    '>'.$showtitle.'</option>'."\n";
 4512: 	$ctr++;
 4513:     }
 4514:     $select.= '</select>';
 4515: 
 4516:     $result.=
 4517:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
 4518:        .$select
 4519:        .&Apache::lonhtmlcommon::row_closure();
 4520: 
 4521:     $result.=
 4522:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
 4523:        .'<label><input type="radio" name="vProb" value="no"'
 4524:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
 4525:        .'<label><input type="radio" name="vProb" value="yes" />'
 4526:            .&mt('yes').'</label>'."\n"
 4527:        .&Apache::lonhtmlcommon::row_closure();
 4528: 
 4529:     $result.=
 4530:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
 4531:        .'<label><input type="radio" name="lastSub" value="none" /> '
 4532:            .&mt('none').' </label>'."\n"
 4533:        .'<label><input type="radio" name="lastSub" value="datesub"'
 4534:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
 4535:        .'<label><input type="radio" name="lastSub" value="all" /> '
 4536:            .&mt('all submissions with details').' </label>'
 4537:        .&Apache::lonhtmlcommon::row_closure();
 4538:     
 4539:     $result.=
 4540:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
 4541:        .'<input type="text" name="CODE" value="" />'
 4542:        .&Apache::lonhtmlcommon::row_closure(1)
 4543:        .&Apache::lonhtmlcommon::end_pick_box();
 4544: 
 4545:     # Show list of students to select for grading
 4546:     $result.='<br /><input type="button" '.
 4547:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4548: 
 4549:     $request->print($result);
 4550: 
 4551:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4552: 	&Apache::loncommon::start_data_table().
 4553: 	&Apache::loncommon::start_data_table_header_row().
 4554: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4555: 	'<th>'.&nameUserString('header').'</th>'.
 4556: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4557: 	'<th>'.&nameUserString('header').'</th>'.
 4558: 	&Apache::loncommon::end_data_table_header_row();
 4559:  
 4560:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4561:     my $ptr = 1;
 4562:     foreach my $student (sort 
 4563: 			 {
 4564: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4565: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4566: 			     }
 4567: 			     return $a cmp $b;
 4568: 			 } (keys(%$fullname))) {
 4569: 	my ($uname,$udom) = split(/:/,$student);
 4570: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4571:                                   : '</td>');
 4572: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4573: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4574: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4575: 	$studentTable.=
 4576: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4577:                          : '');
 4578: 	$ptr++;
 4579:     }
 4580:     if ($ptr%2 == 0) {
 4581: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4582: 	    &Apache::loncommon::end_data_table_row();
 4583:     }
 4584:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4585:     $studentTable.='<input type="button" '.
 4586:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4587: 
 4588:     $request->print($studentTable);
 4589: 
 4590:     return '';
 4591: }
 4592: 
 4593: sub getSymbMap {
 4594:     my ($map_error) = @_;
 4595:     my $navmap = Apache::lonnavmaps::navmap->new();
 4596:     unless (ref($navmap)) {
 4597:         if (ref($map_error)) {
 4598:             $$map_error = 'navmap';
 4599:         }
 4600:         return;
 4601:     }
 4602:     my %symbx = ();
 4603:     my @titles = ();
 4604:     my $minder = 0;
 4605: 
 4606:     # Gather every sequence that has problems.
 4607:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4608: 					       1,0,1);
 4609:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4610: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4611: 	    my $title = $minder.'.'.
 4612: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4613: 	    push(@titles, $title); # minder in case two titles are identical
 4614: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4615: 	    $minder++;
 4616: 	}
 4617:     }
 4618:     return \@titles,\%symbx;
 4619: }
 4620: 
 4621: #
 4622: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4623: sub displayPage {
 4624:     my ($request,$symb) = @_;
 4625:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4626:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4627:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4628:     my $pageTitle = $env{'form.page'};
 4629:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4630:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4631:     my $usec=$classlist->{$env{'form.student'}}[5];
 4632: 
 4633:     #need to make sure we have the correct data for later EXT calls, 
 4634:     #thus invalidate the cache
 4635:     &Apache::lonnet::devalidatecourseresdata(
 4636:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4637:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4638:     &Apache::lonnet::clear_EXT_cache_status();
 4639: 
 4640:     if (!&canview($usec)) {
 4641:         $request->print(
 4642:             '<span class="LC_warning">'.
 4643:             &mt('Unable to view requested student. ([_1])',
 4644:                     $env{'form.student'}).
 4645:             '</span>');
 4646:         return;
 4647:     }
 4648:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4649:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4650: 	'</h3>'."\n";
 4651:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4652:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4653: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4654:     } else {
 4655: 	delete($env{'form.CODE'});
 4656:     }
 4657:     &sub_page_js($request);
 4658:     $request->print($result);
 4659: 
 4660:     my $navmap = Apache::lonnavmaps::navmap->new();
 4661:     unless (ref($navmap)) {
 4662:         $request->print(&navmap_errormsg());
 4663:         return;
 4664:     }
 4665:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4666:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4667:     if (!$map) {
 4668: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4669: 	return; 
 4670:     }
 4671:     my $iterator = $navmap->getIterator($map->map_start(),
 4672: 					$map->map_finish());
 4673: 
 4674:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4675: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4676: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4677: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4678: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4679: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4680: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4681: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
 4682: 
 4683:     if (defined($env{'form.CODE'})) {
 4684: 	$studentTable.=
 4685: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4686:     }
 4687:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4688: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4689: 
 4690:     $studentTable.='&nbsp;<span class="LC_info">'.
 4691:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 4692:         '</span>'."\n".
 4693: 	&Apache::loncommon::start_data_table().
 4694: 	&Apache::loncommon::start_data_table_header_row().
 4695: 	'<th>'.&mt('Prob.').'</th>'.
 4696: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4697: 	&Apache::loncommon::end_data_table_header_row();
 4698: 
 4699:     &Apache::lonxml::clear_problem_counter();
 4700:     my ($depth,$question,$prob) = (1,1,1);
 4701:     $iterator->next(); # skip the first BEGIN_MAP
 4702:     my $curRes = $iterator->next(); # for "current resource"
 4703:     while ($depth > 0) {
 4704:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4705:         if($curRes == $iterator->END_MAP) { $depth--; }
 4706: 
 4707:         if (ref($curRes) && $curRes->is_problem()) {
 4708: 	    my $parts = $curRes->parts();
 4709:             my $title = $curRes->compTitle();
 4710: 	    my $symbx = $curRes->symb();
 4711: 	    $studentTable.=
 4712: 		&Apache::loncommon::start_data_table_row().
 4713: 		'<td align="center" valign="top" >'.$prob.
 4714: 		(scalar(@{$parts}) == 1 ? '' 
 4715: 		                        : '<br />('.&mt('[_1]parts',
 4716: 							scalar(@{$parts}).'&nbsp;').')'
 4717: 		 ).
 4718: 		 '</td>';
 4719: 	    $studentTable.='<td valign="top">';
 4720: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4721: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4722: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4723: 					     undef,'both',\%form);
 4724: 	    } else {
 4725: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4726: 		$companswer =~ s|<form(.*?)>||g;
 4727: 		$companswer =~ s|</form>||g;
 4728: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4729: #		    $companswer =~ s/$1/ /ms;
 4730: #		    $request->print('match='.$1."<br />\n");
 4731: #		}
 4732: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4733: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 4734: 	    }
 4735: 
 4736: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4737: 
 4738: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4739: 		if ($record{'version'} eq '') {
 4740: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4741: 		} else {
 4742: 		    my %responseType = ();
 4743: 		    foreach my $partid (@{$parts}) {
 4744: 			my @responseIds =$curRes->responseIds($partid);
 4745: 			my @responseType =$curRes->responseType($partid);
 4746: 			my %responseIds;
 4747: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4748: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4749: 			}
 4750: 			$responseType{$partid} = \%responseIds;
 4751: 		    }
 4752: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4753: 
 4754: 		}
 4755: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4756: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4757:                 my $identifier = (&canmodify($usec)? $prob : ''); 
 4758: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4759: 									$env{'request.course.id'},
 4760: 									'','.submission',undef,
 4761:                                                                         $usec,$identifier);
 4762:  
 4763: 	    }
 4764: 	    if (&canmodify($usec)) {
 4765:             $studentTable.=&gradeBox_start();
 4766: 		foreach my $partid (@{$parts}) {
 4767: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4768: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4769: 		    $question++;
 4770: 		}
 4771:             $studentTable.=&gradeBox_end();
 4772: 		$prob++;
 4773: 	    }
 4774: 	    $studentTable.='</td></tr>';
 4775: 
 4776: 	}
 4777:         $curRes = $iterator->next();
 4778:     }
 4779: 
 4780:     $studentTable.=
 4781:         '</table>'."\n".
 4782:         '<input type="button" value="'.&mt('Save').'" '.
 4783:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4784:         '</form>'."\n";
 4785:     $request->print($studentTable);
 4786: 
 4787:     return '';
 4788: }
 4789: 
 4790: sub displaySubByDates {
 4791:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4792:     my $isCODE=0;
 4793:     my $isTask = ($symb =~/\.task$/);
 4794:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4795:     my $studentTable=&Apache::loncommon::start_data_table().
 4796: 	&Apache::loncommon::start_data_table_header_row().
 4797: 	'<th>'.&mt('Date/Time').'</th>'.
 4798: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4799:         ($isTask?'<th>'.&mt('Version').'</th>':'').
 4800: 	'<th>'.&mt('Submission').'</th>'.
 4801: 	'<th>'.&mt('Status').'</th>'.
 4802: 	&Apache::loncommon::end_data_table_header_row();
 4803:     my ($version);
 4804:     my %mark;
 4805:     my %orders;
 4806:     $mark{'correct_by_student'} = $checkIcon;
 4807:     if (!exists($$record{'1:timestamp'})) {
 4808: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 4809:     }
 4810: 
 4811:     my $interaction;
 4812:     my $no_increment = 1;
 4813:     my %lastrndseed;
 4814:     for ($version=1;$version<=$$record{'version'};$version++) {
 4815: 	my $timestamp = 
 4816: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4817: 	if (exists($$record{$version.':resource.0.version'})) {
 4818: 	    $interaction = $$record{$version.':resource.0.version'};
 4819: 	}
 4820:         if ($isTask && $env{'form.previousversion'}) {
 4821:             next unless ($interaction == $env{'form.previousversion'});
 4822:         }
 4823: 	my $where = ($isTask ? "$version:resource.$interaction"
 4824: 		             : "$version:resource");
 4825: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4826: 	    '<td>'.$timestamp.'</td>';
 4827: 	if ($isCODE) {
 4828: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4829: 	}
 4830:         if ($isTask) {
 4831:             $studentTable.='<td>'.$interaction.'</td>';
 4832:         }
 4833: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4834: 	my @displaySub = ();
 4835: 	foreach my $partid (@{$parts}) {
 4836:             my ($hidden,$type);
 4837:             $type = $$record{$version.':resource.'.$partid.'.type'};
 4838:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
 4839:                 $hidden = 1;
 4840:             }
 4841: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4842: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4843: 	    
 4844: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4845: 	    my $display_part=&get_display_part($partid,$symb);
 4846: 	    foreach my $matchKey (@matchKey) {
 4847: 		if (exists($$record{$version.':'.$matchKey}) &&
 4848: 		    $$record{$version.':'.$matchKey} ne '') {
 4849:                     
 4850: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4851: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4852:                     $displaySub[0].='<span class="LC_nobreak">';
 4853:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 4854:                                    .' <span class="LC_internal_info">'
 4855:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
 4856:                                    .'</span>'
 4857:                                    .' <b>';
 4858:                     if ($hidden) {
 4859:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
 4860:                     } else {
 4861:                         my ($trial,$rndseed,$newvariation);
 4862:                         if ($type eq 'randomizetry') {
 4863:                             $trial = $$record{"$where.$partid.tries"};
 4864:                             if (exists($$record{"$where.$partid.rawrndseed"})) {
 4865:                                 $rndseed = $$record{"$where.$partid.rawrndseed"};
 4866:                             } else {
 4867:                                 $rndseed = $$record{"$where.$partid.rndseed"};
 4868:                             }
 4869:                         }
 4870: 		        if ($$record{"$where.$partid.tries"} eq '') {
 4871: 			    $displaySub[0].=&mt('Trial not counted');
 4872: 		        } else {
 4873: 			    $displaySub[0].=&mt('Trial: [_1]',
 4874: 					    $$record{"$where.$partid.tries"});
 4875:                             if ($rndseed || $lastrndseed{$partid}) {
 4876:                                 if ($rndseed ne $lastrndseed{$partid}) {
 4877:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
 4878:                                 }
 4879:                             }
 4880:                             $lastrndseed{$partid} = $rndseed;
 4881: 		        }
 4882: 		        my $responseType=($isTask ? 'Task'
 4883:                                               : $responseType->{$partid}->{$responseId});
 4884: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4885: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
 4886: 			    $orders{$partid}->{$responseId}=
 4887: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
 4888:                                            $no_increment,$type,$trial,$rndseed);
 4889: 		        }
 4890: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
 4891: 		        $displaySub[0].='&nbsp; '.
 4892: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
 4893:                     }
 4894: 		}
 4895: 	    }
 4896: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4897: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 4898: 				    $$record{"$where.$partid.checkedin"},
 4899: 				    $$record{"$where.$partid.checkedin.slot"}).
 4900: 					'<br />';
 4901: 	    }
 4902: 	    if (exists $$record{"$where.$partid.award"}) {
 4903: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 4904: 		    lc($$record{"$where.$partid.award"}).' '.
 4905: 		    $mark{$$record{"$where.$partid.solved"}}.
 4906: 		    '<br />';
 4907: 	    }
 4908: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4909: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4910: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4911: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4912: 		$displaySub[2].=
 4913: 		    $$record{"$version:resource.$partid.regrader"}.
 4914: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4915: 	    }
 4916: 	}
 4917: 	# needed because old essay regrader has not parts info
 4918: 	if (exists $$record{"$version:resource.regrader"}) {
 4919: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 4920: 	}
 4921: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 4922: 	if ($displaySub[2]) {
 4923: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 4924: 	}
 4925: 	$studentTable.='&nbsp;</td>'.
 4926: 	    &Apache::loncommon::end_data_table_row();
 4927:     }
 4928:     $studentTable.=&Apache::loncommon::end_data_table();
 4929:     return $studentTable;
 4930: }
 4931: 
 4932: sub updateGradeByPage {
 4933:     my ($request,$symb) = @_;
 4934: 
 4935:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4936:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4937:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4938:     my $pageTitle = $env{'form.page'};
 4939:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4940:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4941:     my $usec=$classlist->{$env{'form.student'}}[5];
 4942:     if (!&canmodify($usec)) {
 4943: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 4944: 	return;
 4945:     }
 4946:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4947:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 4948: 	'</h3>'."\n";
 4949: 
 4950:     $request->print($result);
 4951: 
 4952: 
 4953:     my $navmap = Apache::lonnavmaps::navmap->new();
 4954:     unless (ref($navmap)) {
 4955:         $request->print(&navmap_errormsg());
 4956:         return;
 4957:     }
 4958:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 4959:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4960:     if (!$map) {
 4961: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 4962: 	return; 
 4963:     }
 4964:     my $iterator = $navmap->getIterator($map->map_start(),
 4965: 					$map->map_finish());
 4966: 
 4967:     my $studentTable=
 4968: 	&Apache::loncommon::start_data_table().
 4969: 	&Apache::loncommon::start_data_table_header_row().
 4970: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 4971: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 4972: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 4973: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 4974: 	&Apache::loncommon::end_data_table_header_row();
 4975: 
 4976:     $iterator->next(); # skip the first BEGIN_MAP
 4977:     my $curRes = $iterator->next(); # for "current resource"
 4978:     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
 4979:     while ($depth > 0) {
 4980:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4981:         if($curRes == $iterator->END_MAP) { $depth--; }
 4982: 
 4983:         if (ref($curRes) && $curRes->is_problem()) {
 4984: 	    my $parts = $curRes->parts();
 4985:             my $title = $curRes->compTitle();
 4986: 	    my $symbx = $curRes->symb();
 4987: 	    $studentTable.=
 4988: 		&Apache::loncommon::start_data_table_row().
 4989: 		'<td align="center" valign="top" >'.$prob.
 4990: 		(scalar(@{$parts}) == 1 ? '' 
 4991:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
 4992: 		.')').'</td>';
 4993: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 4994: 
 4995: 	    my %newrecord=();
 4996: 	    my @displayPts=();
 4997:             my %aggregate = ();
 4998:             my $aggregateflag = 0;
 4999:             if ($env{'form.HIDE'.$prob}) {
 5000:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 5001:                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
 5002:                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
 5003:                 $hideflag += $numchgs;
 5004:             }
 5005: 	    foreach my $partid (@{$parts}) {
 5006: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 5007: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 5008: 
 5009: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 5010: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 5011: 		my $partial = $newpts/$wgt;
 5012: 		my $score;
 5013: 		if ($partial > 0) {
 5014: 		    $score = 'correct_by_override';
 5015: 		} elsif ($newpts ne '') { #empty is taken as 0
 5016: 		    $score = 'incorrect_by_override';
 5017: 		}
 5018: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 5019: 		if ($dropMenu eq 'excused') {
 5020: 		    $partial = '';
 5021: 		    $score = 'excused';
 5022: 		} elsif ($dropMenu eq 'reset status'
 5023: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 5024: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 5025: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 5026: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 5027: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 5028: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 5029: 		    $changeflag++;
 5030: 		    $newpts = '';
 5031:                     
 5032:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 5033:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 5034:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 5035:                     if ($aggtries > 0) {
 5036:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 5037:                         $aggregateflag = 1;
 5038:                     }
 5039: 		}
 5040: 		my $display_part=&get_display_part($partid,$curRes->symb());
 5041: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 5042: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5043: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 5044: 		    '&nbsp;<br />';
 5045: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5046: 		     (($score eq 'excused') ? 'excused' : $newpts).
 5047: 		    '&nbsp;<br />';
 5048: 		$question++;
 5049: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 5050: 
 5051: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 5052: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 5053: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 5054: 		    if (scalar(keys(%newrecord)) > 0);
 5055: 
 5056: 		$changeflag++;
 5057: 	    }
 5058: 	    if (scalar(keys(%newrecord)) > 0) {
 5059: 		my %record = 
 5060: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 5061: 					     $udom,$uname);
 5062: 
 5063: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 5064: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 5065: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 5066: 		    $newrecord{'resource.CODE'} = '';
 5067: 		}
 5068: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 5069: 					$udom,$uname);
 5070: 		%record = &Apache::lonnet::restore($symbx,
 5071: 						   $env{'request.course.id'},
 5072: 						   $udom,$uname);
 5073: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 5074: 					     $cdom,$cnum,$udom,$uname);
 5075: 	    }
 5076: 	    
 5077:             if ($aggregateflag) {
 5078:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 5079:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 5080:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 5081:             }
 5082: 
 5083: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 5084: 		'<td valign="top">'.$displayPts[1].'</td>'.
 5085: 		&Apache::loncommon::end_data_table_row();
 5086: 
 5087: 	    $prob++;
 5088: 	}
 5089:         $curRes = $iterator->next();
 5090:     }
 5091: 
 5092:     $studentTable.=&Apache::loncommon::end_data_table();
 5093:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 5094: 		  &mt('The scores were changed for [quant,_1,problem].',
 5095: 		  $changeflag).'<br />');
 5096:     my $hidemsg=($hideflag == 0 ? '' :
 5097:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
 5098:                      $hideflag).'<br />');
 5099:     $request->print($hidemsg.$grademsg.$studentTable);
 5100: 
 5101:     return '';
 5102: }
 5103: 
 5104: #-------- end of section for handling grading by page/sequence ---------
 5105: #
 5106: #-------------------------------------------------------------------
 5107: 
 5108: #-------------------- Bubblesheet (Scantron) Grading -------------------
 5109: #
 5110: #------ start of section for handling grading by page/sequence ---------
 5111: 
 5112: =pod
 5113: 
 5114: =head1 Bubble sheet grading routines
 5115: 
 5116:   For this documentation:
 5117: 
 5118:    'scanline' refers to the full line of characters
 5119:    from the file that we are parsing that represents one entire sheet
 5120: 
 5121:    'bubble line' refers to the data
 5122:    representing the line of bubbles that are on the physical bubblesheet
 5123: 
 5124: 
 5125: The overall process is that a scanned in bubblesheet data is uploaded
 5126: into a course. When a user wants to grade, they select a
 5127: sequence/folder of resources, a file of bubblesheet info, and pick
 5128: one of the predefined configurations for what each scanline looks
 5129: like.
 5130: 
 5131: Next each scanline is checked for any errors of either 'missing
 5132: bubbles' (it's an error because it may have been mis-scanned
 5133: because too light bubbling), 'double bubble' (each bubble line should
 5134: have no more than one letter picked), invalid or duplicated CODE,
 5135: invalid student/employee ID
 5136: 
 5137: If the CODE option is used that determines the randomization of the
 5138: homework problems, either way the student/employee ID is looked up into a
 5139: username:domain.
 5140: 
 5141: During the validation phase the instructor can choose to skip scanlines. 
 5142: 
 5143: After the validation phase, there are now 3 bubblesheet files
 5144: 
 5145:   scantron_original_filename (unmodified original file)
 5146:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 5147:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 5148: 
 5149: Also there is a separate hash nohist_scantrondata that contains extra
 5150: correction information that isn't representable in the bubblesheet
 5151: file (see &scantron_getfile() for more information)
 5152: 
 5153: After all scanlines are either valid, marked as valid or skipped, then
 5154: foreach line foreach problem in the picked sequence, an ssi request is
 5155: made that simulates a user submitting their selected letter(s) against
 5156: the homework problem.
 5157: 
 5158: =over 4
 5159: 
 5160: 
 5161: 
 5162: =item defaultFormData
 5163: 
 5164:   Returns html hidden inputs used to hold context/default values.
 5165: 
 5166:  Arguments:
 5167:   $symb - $symb of the current resource 
 5168: 
 5169: =cut
 5170: 
 5171: sub defaultFormData {
 5172:     my ($symb)=@_;
 5173:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
 5174: }
 5175: 
 5176: 
 5177: =pod 
 5178: 
 5179: =item getSequenceDropDown
 5180: 
 5181:    Return html dropdown of possible sequences to grade
 5182:  
 5183:  Arguments:
 5184:    $symb - $symb of the current resource
 5185:    $map_error - ref to scalar which will container error if
 5186:                 $navmap object is unavailable in &getSymbMap().
 5187: 
 5188: =cut
 5189: 
 5190: sub getSequenceDropDown {
 5191:     my ($symb,$map_error)=@_;
 5192:     my $result='<select name="selectpage">'."\n";
 5193:     my ($titles,$symbx) = &getSymbMap($map_error);
 5194:     if (ref($map_error)) {
 5195:         return if ($$map_error);
 5196:     }
 5197:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 5198:     my $ctr=0;
 5199:     foreach (@$titles) {
 5200: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5201: 	$result.='<option value="'.$$symbx{$_}.'" '.
 5202: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 5203: 	    '>'.$showtitle.'</option>'."\n";
 5204: 	$ctr++;
 5205:     }
 5206:     $result.= '</select>';
 5207:     return $result;
 5208: }
 5209: 
 5210: my %bubble_lines_per_response;     # no. bubble lines for each response.
 5211:                                    # key is zero-based index - 0, 1, 2 ...
 5212: 
 5213: my %first_bubble_line;             # First bubble line no. for each bubble.
 5214: 
 5215: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 5216:                                    # matchresponse or rankresponse, where 
 5217:                                    # an individual response can have multiple 
 5218:                                    # lines
 5219: 
 5220: my %responsetype_per_response;     # responsetype for each response
 5221: 
 5222: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
 5223:                                    # numbered response. Needed when randomorder
 5224:                                    # or randompick are in use. Key is ID, value 
 5225:                                    # is response number.
 5226: 
 5227: # Save and restore the bubble lines array to the form env.
 5228: 
 5229: 
 5230: sub save_bubble_lines {
 5231:     foreach my $line (keys(%bubble_lines_per_response)) {
 5232: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 5233: 	$env{"form.scantron.first_bubble_line.$line"} =
 5234: 	    $first_bubble_line{$line};
 5235:         $env{"form.scantron.sub_bubblelines.$line"} = 
 5236:             $subdivided_bubble_lines{$line};
 5237:         $env{"form.scantron.responsetype.$line"} =
 5238:             $responsetype_per_response{$line};
 5239:     }
 5240:     foreach my $resid (keys(%masterseq_id_responsenum)) {
 5241:         my $line = $masterseq_id_responsenum{$resid};
 5242:         $env{"form.scantron.residpart.$line"} = $resid;
 5243:     }
 5244: }
 5245: 
 5246: 
 5247: sub restore_bubble_lines {
 5248:     my $line = 0;
 5249:     %bubble_lines_per_response = ();
 5250:     %masterseq_id_responsenum = ();
 5251:     while ($env{"form.scantron.bubblelines.$line"}) {
 5252: 	my $value = $env{"form.scantron.bubblelines.$line"};
 5253: 	$bubble_lines_per_response{$line} = $value;
 5254: 	$first_bubble_line{$line}  =
 5255: 	    $env{"form.scantron.first_bubble_line.$line"};
 5256:         $subdivided_bubble_lines{$line} =
 5257:             $env{"form.scantron.sub_bubblelines.$line"};
 5258:         $responsetype_per_response{$line} =
 5259:             $env{"form.scantron.responsetype.$line"};
 5260:         my $id = $env{"form.scantron.residpart.$line"};
 5261:         $masterseq_id_responsenum{$id} = $line;
 5262: 	$line++;
 5263:     }
 5264: }
 5265: 
 5266: =pod 
 5267: 
 5268: =item scantron_filenames
 5269: 
 5270:    Returns a list of the scantron files in the current course 
 5271: 
 5272: =cut
 5273: 
 5274: sub scantron_filenames {
 5275:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5276:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5277:     my $getpropath = 1;
 5278:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
 5279:                                                         $cname,$getpropath);
 5280:     my @possiblenames;
 5281:     if (ref($dirlist) eq 'ARRAY') {
 5282:         foreach my $filename (sort(@{$dirlist})) {
 5283: 	    ($filename)=split(/&/,$filename);
 5284: 	    if ($filename!~/^scantron_orig_/) { next ; }
 5285: 	    $filename=~s/^scantron_orig_//;
 5286: 	    push(@possiblenames,$filename);
 5287:         }
 5288:     }
 5289:     return @possiblenames;
 5290: }
 5291: 
 5292: =pod 
 5293: 
 5294: =item scantron_uploads
 5295: 
 5296:    Returns  html drop-down list of scantron files in current course.
 5297: 
 5298:  Arguments:
 5299:    $file2grade - filename to set as selected in the dropdown
 5300: 
 5301: =cut
 5302: 
 5303: sub scantron_uploads {
 5304:     my ($file2grade) = @_;
 5305:     my $result=	'<select name="scantron_selectfile">';
 5306:     $result.="<option></option>";
 5307:     foreach my $filename (sort(&scantron_filenames())) {
 5308: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 5309:     }
 5310:     $result.="</select>";
 5311:     return $result;
 5312: }
 5313: 
 5314: =pod 
 5315: 
 5316: =item scantron_scantab
 5317: 
 5318:   Returns html drop down of the scantron formats in the scantronformat.tab
 5319:   file.
 5320: 
 5321: =cut
 5322: 
 5323: sub scantron_scantab {
 5324:     my $result='<select name="scantron_format">'."\n";
 5325:     $result.='<option></option>'."\n";
 5326:     my @lines = &get_scantronformat_file();
 5327:     if (@lines > 0) {
 5328:         foreach my $line (@lines) {
 5329:             next if (($line =~ /^\#/) || ($line eq ''));
 5330: 	    my ($name,$descrip)=split(/:/,$line);
 5331: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 5332:         }
 5333:     }
 5334:     $result.='</select>'."\n";
 5335:     return $result;
 5336: }
 5337: 
 5338: =pod
 5339: 
 5340: =item get_scantronformat_file
 5341: 
 5342:   Returns an array containing lines from the scantron format file for
 5343:   the domain of the course.
 5344: 
 5345:   If a url for a custom.tab file is listed in domain's configuration.db, 
 5346:   lines are from this file.
 5347: 
 5348:   Otherwise, if a default.tab has been published in RES space by the 
 5349:   domainconfig user, lines are from this file.
 5350: 
 5351:   Otherwise, fall back to getting lines from the legacy file on the
 5352:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 5353: 
 5354: =cut
 5355: 
 5356: sub get_scantronformat_file {
 5357:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5358:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 5359:     my $gottab = 0;
 5360:     my @lines;
 5361:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5362:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5363:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5364:             if ($formatfile ne '-1') {
 5365:                 @lines = split("\n",$formatfile,-1);
 5366:                 $gottab = 1;
 5367:             }
 5368:         }
 5369:     }
 5370:     if (!$gottab) {
 5371:         my $confname = $cdom.'-domainconfig';
 5372:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5373:         my $formatfile =  &Apache::lonnet::getfile($default);
 5374:         if ($formatfile ne '-1') {
 5375:             @lines = split("\n",$formatfile,-1);
 5376:             $gottab = 1;
 5377:         }
 5378:     }
 5379:     if (!$gottab) {
 5380:         my @domains = &Apache::lonnet::current_machine_domains();
 5381:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5382:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5383:             @lines = <$fh>;
 5384:             close($fh);
 5385:         } else {
 5386:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 5387:             @lines = <$fh>;
 5388:             close($fh);
 5389:         }
 5390:     }
 5391:     return @lines;
 5392: }
 5393: 
 5394: =pod 
 5395: 
 5396: =item scantron_CODElist
 5397: 
 5398:   Returns html drop down of the saved CODE lists from current course,
 5399:   generated from earlier printings.
 5400: 
 5401: =cut
 5402: 
 5403: sub scantron_CODElist {
 5404:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5405:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5406:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5407:     my $namechoice='<option></option>';
 5408:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5409: 	if ($name =~ /^error: 2 /) { next; }
 5410: 	if ($name =~ /^type\0/) { next; }
 5411: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5412:     }
 5413:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5414:     return $namechoice;
 5415: }
 5416: 
 5417: =pod 
 5418: 
 5419: =item scantron_CODEunique
 5420: 
 5421:   Returns the html for "Each CODE to be used once" radio.
 5422: 
 5423: =cut
 5424: 
 5425: sub scantron_CODEunique {
 5426:     my $result='<span class="LC_nobreak">
 5427:                  <label><input type="radio" name="scantron_CODEunique"
 5428:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5429:                 </span>
 5430:                 <span class="LC_nobreak">
 5431:                  <label><input type="radio" name="scantron_CODEunique"
 5432:                         value="no" />'.&mt('No').' </label>
 5433:                 </span>';
 5434:     return $result;
 5435: }
 5436: 
 5437: =pod 
 5438: 
 5439: =item scantron_selectphase
 5440: 
 5441:   Generates the initial screen to start the bubblesheet process.
 5442:   Allows for - starting a grading run.
 5443:              - downloading existing scan data (original, corrected
 5444:                                                 or skipped info)
 5445: 
 5446:              - uploading new scan data
 5447: 
 5448:  Arguments:
 5449:   $r          - The Apache request object
 5450:   $file2grade - name of the file that contain the scanned data to score
 5451: 
 5452: =cut
 5453: 
 5454: sub scantron_selectphase {
 5455:     my ($r,$file2grade,$symb) = @_;
 5456:     if (!$symb) {return '';}
 5457:     my $map_error;
 5458:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 5459:     if ($map_error) {
 5460:         $r->print('<br />'.&navmap_errormsg().'<br />');
 5461:         return;
 5462:     }
 5463:     my $default_form_data=&defaultFormData($symb);
 5464:     my $file_selector=&scantron_uploads($file2grade);
 5465:     my $format_selector=&scantron_scantab();
 5466:     my $CODE_selector=&scantron_CODElist();
 5467:     my $CODE_unique=&scantron_CODEunique();
 5468:     my $result;
 5469: 
 5470:     $ssi_error = 0;
 5471: 
 5472:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5473:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5474: 
 5475: 	# Chunk of form to prompt for a scantron file upload.
 5476: 
 5477:         $r->print('
 5478:     <br />
 5479:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5480:        '.&Apache::loncommon::start_data_table_header_row().'
 5481:             <th>
 5482:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 5483:             </th>
 5484:        '.&Apache::loncommon::end_data_table_header_row().'
 5485:        '.&Apache::loncommon::start_data_table_row().'
 5486:             <td>
 5487: ');
 5488:     my $default_form_data=&defaultFormData($symb);
 5489:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5490:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5491:     $r->print(&Apache::lonhtmlcommon::scripttag('
 5492:     function checkUpload(formname) {
 5493: 	if (formname.upfile.value == "") {
 5494: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 5495: 	    return false;
 5496: 	}
 5497: 	formname.submit();
 5498:     }'));
 5499:     $r->print('
 5500:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5501:                 '.$default_form_data.'
 5502:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5503:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5504:                 <input name="command" value="scantronupload_save" type="hidden" />
 5505:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5506:                 <br />
 5507:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 5508:               </form>
 5509: ');
 5510: 
 5511:         $r->print('
 5512:             </td>
 5513:        '.&Apache::loncommon::end_data_table_row().'
 5514:        '.&Apache::loncommon::end_data_table().'
 5515: ');
 5516:     }
 5517: 
 5518:     # Chunk of form to prompt for a file to grade and how:
 5519: 
 5520:     $result.= '
 5521:     <br />
 5522:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5523:     <input type="hidden" name="command" value="scantron_warning" />
 5524:     '.$default_form_data.'
 5525:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5526:        '.&Apache::loncommon::start_data_table_header_row().'
 5527:             <th colspan="2">
 5528:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5529:             </th>
 5530:        '.&Apache::loncommon::end_data_table_header_row().'
 5531:        '.&Apache::loncommon::start_data_table_row().'
 5532:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5533:        '.&Apache::loncommon::end_data_table_row().'
 5534:        '.&Apache::loncommon::start_data_table_row().'
 5535:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 5536:        '.&Apache::loncommon::end_data_table_row().'
 5537:        '.&Apache::loncommon::start_data_table_row().'
 5538:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 5539:        '.&Apache::loncommon::end_data_table_row().'
 5540:        '.&Apache::loncommon::start_data_table_row().'
 5541:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5542:        '.&Apache::loncommon::end_data_table_row().'
 5543:        '.&Apache::loncommon::start_data_table_row().'
 5544:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5545:        '.&Apache::loncommon::end_data_table_row().'
 5546:        '.&Apache::loncommon::start_data_table_row().'
 5547: 	    <td> '.&mt('Options:').' </td>
 5548:             <td>
 5549: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5550:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5551:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5552: 	    </td>
 5553:        '.&Apache::loncommon::end_data_table_row().'
 5554:        '.&Apache::loncommon::start_data_table_row().'
 5555:             <td colspan="2">
 5556:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 5557:             </td>
 5558:        '.&Apache::loncommon::end_data_table_row().'
 5559:     '.&Apache::loncommon::end_data_table().'
 5560:     </form>
 5561: ';
 5562:    
 5563:     $r->print($result);
 5564: 
 5565: 
 5566: 
 5567:     # Chunk of the form that prompts to view a scoring office file,
 5568:     # corrected file, skipped records in a file.
 5569: 
 5570:     $r->print('
 5571:    <br />
 5572:    <form action="/adm/grades" name="scantron_download">
 5573:      '.$default_form_data.'
 5574:      <input type="hidden" name="command" value="scantron_download" />
 5575:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5576:        '.&Apache::loncommon::start_data_table_header_row().'
 5577:               <th>
 5578:                 &nbsp;'.&mt('Download a scoring office file').'
 5579:               </th>
 5580:        '.&Apache::loncommon::end_data_table_header_row().'
 5581:        '.&Apache::loncommon::start_data_table_row().'
 5582:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5583:                 <br />
 5584:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5585:        '.&Apache::loncommon::end_data_table_row().'
 5586:      '.&Apache::loncommon::end_data_table().'
 5587:    </form>
 5588:    <br />
 5589: ');
 5590: 
 5591:     &Apache::lonpickcode::code_list($r,2);
 5592: 
 5593:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
 5594:              $default_form_data."\n".
 5595:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5596:              &Apache::loncommon::start_data_table_header_row()."\n".
 5597:              '<th colspan="2">
 5598:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 5599:              '</th>'."\n".
 5600:               &Apache::loncommon::end_data_table_header_row()."\n".
 5601:               &Apache::loncommon::start_data_table_row()."\n".
 5602:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5603:               '<td> '.$sequence_selector.' </td>'.
 5604:               &Apache::loncommon::end_data_table_row()."\n".
 5605:               &Apache::loncommon::start_data_table_row()."\n".
 5606:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5607:               '<td> '.$file_selector.' </td>'."\n".
 5608:               &Apache::loncommon::end_data_table_row()."\n".
 5609:               &Apache::loncommon::start_data_table_row()."\n".
 5610:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5611:               '<td> '.$format_selector.' </td>'."\n".
 5612:               &Apache::loncommon::end_data_table_row()."\n".
 5613:               &Apache::loncommon::start_data_table_row()."\n".
 5614:               '<td> '.&mt('Options').' </td>'."\n".
 5615:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 5616:               &Apache::loncommon::end_data_table_row()."\n".
 5617:               &Apache::loncommon::start_data_table_row()."\n".
 5618:               '<td colspan="2">'."\n".
 5619:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5620:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 5621:               '</td>'."\n".
 5622:               &Apache::loncommon::end_data_table_row()."\n".
 5623:               &Apache::loncommon::end_data_table()."\n".
 5624:               '</form><br />');
 5625:     return;
 5626: }
 5627: 
 5628: =pod
 5629: 
 5630: =item get_scantron_config
 5631: 
 5632:    Parse and return the bubblesheet configuration line selected as a
 5633:    hash of configuration file fields.
 5634: 
 5635:  Arguments:
 5636:     which - the name of the configuration to parse from the file.
 5637: 
 5638: 
 5639:  Returns:
 5640:             If the named configuration is not in the file, an empty
 5641:             hash is returned.
 5642:     a hash with the fields
 5643:       name         - internal name for the this configuration setup
 5644:       description  - text to display to operator that describes this config
 5645:       CODElocation - if 0 or the string 'none'
 5646:                           - no CODE exists for this config
 5647:                      if -1 || the string 'letter'
 5648:                           - a CODE exists for this config and is
 5649:                             a string of letters
 5650:                      Unsupported value (but planned for future support)
 5651:                           if a positive integer
 5652:                                - The CODE exists as the first n items from
 5653:                                  the question section of the form
 5654:                           if the string 'number'
 5655:                                - The CODE exists for this config and is
 5656:                                  a string of numbers
 5657:       CODEstart   - (only matter if a CODE exists) column in the line where
 5658:                      the CODE starts
 5659:       CODElength  - length of the CODE
 5660:       IDstart     - column where the student/employee ID starts
 5661:       IDlength    - length of the student/employee ID info
 5662:       Qstart      - column where the information from the bubbled
 5663:                     'questions' start
 5664:       Qlength     - number of columns comprising a single bubble line from
 5665:                     the sheet. (usually either 1 or 10)
 5666:       Qon         - either a single character representing the character used
 5667:                     to signal a bubble was chosen in the positional setup, or
 5668:                     the string 'letter' if the letter of the chosen bubble is
 5669:                     in the final, or 'number' if a number representing the
 5670:                     chosen bubble is in the file (1->A 0->J)
 5671:       Qoff        - the character used to represent that a bubble was
 5672:                     left blank
 5673:       PaperID     - if the scanning process generates a unique number for each
 5674:                     sheet scanned the column that this ID number starts in
 5675:       PaperIDlength - number of columns that comprise the unique ID number
 5676:                       for the sheet of paper
 5677:       FirstName   - column that the first name starts in
 5678:       FirstNameLength - number of columns that the first name spans
 5679:  
 5680:       LastName    - column that the last name starts in
 5681:       LastNameLength - number of columns that the last name spans
 5682:       BubblesPerRow - number of bubbles available in each row used to 
 5683:                       bubble an answer. (If not specified, 10 assumed).
 5684: 
 5685: =cut
 5686: 
 5687: sub get_scantron_config {
 5688:     my ($which) = @_;
 5689:     my @lines = &get_scantronformat_file();
 5690:     my %config;
 5691:     #FIXME probably should move to XML it has already gotten a bit much now
 5692:     foreach my $line (@lines) {
 5693: 	my ($name,$descrip)=split(/:/,$line);
 5694: 	if ($name ne $which ) { next; }
 5695: 	chomp($line);
 5696: 	my @config=split(/:/,$line);
 5697: 	$config{'name'}=$config[0];
 5698: 	$config{'description'}=$config[1];
 5699: 	$config{'CODElocation'}=$config[2];
 5700: 	$config{'CODEstart'}=$config[3];
 5701: 	$config{'CODElength'}=$config[4];
 5702: 	$config{'IDstart'}=$config[5];
 5703: 	$config{'IDlength'}=$config[6];
 5704: 	$config{'Qstart'}=$config[7];
 5705:  	$config{'Qlength'}=$config[8];
 5706: 	$config{'Qoff'}=$config[9];
 5707: 	$config{'Qon'}=$config[10];
 5708: 	$config{'PaperID'}=$config[11];
 5709: 	$config{'PaperIDlength'}=$config[12];
 5710: 	$config{'FirstName'}=$config[13];
 5711: 	$config{'FirstNamelength'}=$config[14];
 5712: 	$config{'LastName'}=$config[15];
 5713: 	$config{'LastNamelength'}=$config[16];
 5714:         $config{'BubblesPerRow'}=$config[17];
 5715: 	last;
 5716:     }
 5717:     return %config;
 5718: }
 5719: 
 5720: =pod 
 5721: 
 5722: =item username_to_idmap
 5723: 
 5724:     creates a hash keyed by student/employee ID with values of the corresponding
 5725:     student username:domain. If a single ID occurs for more than one student,
 5726:     the status of the student is checked, and if Active, the value in the hash
 5727:     will be set to the Active student.
 5728: 
 5729:   Arguments:
 5730: 
 5731:     $classlist - reference to the class list hash. This is a hash
 5732:                  keyed by student name:domain  whose elements are references
 5733:                  to arrays containing various chunks of information
 5734:                  about the student. (See loncoursedata for more info).
 5735: 
 5736:   Returns
 5737:     %idmap - the constructed hash
 5738: 
 5739: =cut
 5740: 
 5741: sub username_to_idmap {
 5742:     my ($classlist)= @_;
 5743:     my %idmap;
 5744:     foreach my $student (keys(%$classlist)) {
 5745:         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
 5746:         unless ($id eq '') {
 5747:             if (!exists($idmap{$id})) {
 5748:                 $idmap{$id} = $student;
 5749:             } else {
 5750:                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
 5751:                 if ($status eq 'Active') {
 5752:                     $idmap{$id} = $student;
 5753:                 }
 5754:             }
 5755:         }
 5756:     }
 5757:     return %idmap;
 5758: }
 5759: 
 5760: =pod
 5761: 
 5762: =item scantron_fixup_scanline
 5763: 
 5764:    Process a requested correction to a scanline.
 5765: 
 5766:   Arguments:
 5767:     $scantron_config   - hash from &get_scantron_config()
 5768:     $scan_data         - hash of correction information 
 5769:                           (see &scantron_getfile())
 5770:     $line              - existing scanline
 5771:     $whichline         - line number of the passed in scanline
 5772:     $field             - type of change to process 
 5773:                          (either 
 5774:                           'ID'     -> correct the student/employee ID
 5775:                           'CODE'   -> correct the CODE
 5776:                           'answer' -> fixup the submitted answers)
 5777:     
 5778:    $args               - hash of additional info,
 5779:                           - 'ID' 
 5780:                                'newid' -> studentID to use in replacement
 5781:                                           of existing one
 5782:                           - 'CODE' 
 5783:                                'CODE_ignore_dup' - set to true if duplicates
 5784:                                                    should be ignored.
 5785: 	                       'CODE' - is new code or 'use_unfound'
 5786:                                         if the existing unfound code should
 5787:                                         be used as is
 5788:                           - 'answer'
 5789:                                'response' - new answer or 'none' if blank
 5790:                                'question' - the bubble line to change
 5791:                                'questionnum' - the question identifier,
 5792:                                                may include subquestion. 
 5793: 
 5794:   Returns:
 5795:     $line - the modified scanline
 5796: 
 5797:   Side effects: 
 5798:     $scan_data - may be updated
 5799: 
 5800: =cut
 5801: 
 5802: 
 5803: sub scantron_fixup_scanline {
 5804:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5805:     if ($field eq 'ID') {
 5806: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5807: 	    return ($line,1,'New value too large');
 5808: 	}
 5809: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5810: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5811: 				     $args->{'newid'});
 5812: 	}
 5813: 	substr($line,$$scantron_config{'IDstart'}-1,
 5814: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5815: 	if ($args->{'newid'}=~/^\s*$/) {
 5816: 	    &scan_data($scan_data,"$whichline.user",
 5817: 		       $args->{'username'}.':'.$args->{'domain'});
 5818: 	}
 5819:     } elsif ($field eq 'CODE') {
 5820: 	if ($args->{'CODE_ignore_dup'}) {
 5821: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5822: 	}
 5823: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5824: 	if ($args->{'CODE'} ne 'use_unfound') {
 5825: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5826: 		return ($line,1,'New CODE value too large');
 5827: 	    }
 5828: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5829: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5830: 	    }
 5831: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5832: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5833: 	}
 5834:     } elsif ($field eq 'answer') {
 5835: 	my $length=$scantron_config->{'Qlength'};
 5836: 	my $off=$scantron_config->{'Qoff'};
 5837: 	my $on=$scantron_config->{'Qon'};
 5838: 	my $answer=${off}x$length;
 5839: 	if ($args->{'response'} eq 'none') {
 5840: 	    &scan_data($scan_data,
 5841: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5842: 	} else {
 5843: 	    if ($on eq 'letter') {
 5844: 		my @alphabet=('A'..'Z');
 5845: 		$answer=$alphabet[$args->{'response'}];
 5846: 	    } elsif ($on eq 'number') {
 5847: 		$answer=$args->{'response'}+1;
 5848: 		if ($answer == 10) { $answer = '0'; }
 5849: 	    } else {
 5850: 		substr($answer,$args->{'response'},1)=$on;
 5851: 	    }
 5852: 	    &scan_data($scan_data,
 5853: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5854: 	}
 5855: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5856: 	substr($line,$where-1,$length)=$answer;
 5857:     }
 5858:     return $line;
 5859: }
 5860: 
 5861: =pod
 5862: 
 5863: =item scan_data
 5864: 
 5865:     Edit or look up  an item in the scan_data hash.
 5866: 
 5867:   Arguments:
 5868:     $scan_data  - The hash (see scantron_getfile)
 5869:     $key        - shorthand of the key to edit (actual key is
 5870:                   scantronfilename_key).
 5871:     $data        - New value of the hash entry.
 5872:     $delete      - If true, the entry is removed from the hash.
 5873: 
 5874:   Returns:
 5875:     The new value of the hash table field (undefined if deleted).
 5876: 
 5877: =cut
 5878: 
 5879: 
 5880: sub scan_data {
 5881:     my ($scan_data,$key,$value,$delete)=@_;
 5882:     my $filename=$env{'form.scantron_selectfile'};
 5883:     if (defined($value)) {
 5884: 	$scan_data->{$filename.'_'.$key} = $value;
 5885:     }
 5886:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5887:     return $scan_data->{$filename.'_'.$key};
 5888: }
 5889: 
 5890: # ----- These first few routines are general use routines.----
 5891: 
 5892: # Return the number of occurences of a pattern in a string.
 5893: 
 5894: sub occurence_count {
 5895:     my ($string, $pattern) = @_;
 5896: 
 5897:     my @matches = ($string =~ /$pattern/g);
 5898: 
 5899:     return scalar(@matches);
 5900: }
 5901: 
 5902: 
 5903: # Take a string known to have digits and convert all the
 5904: # digits into letters in the range J,A..I.
 5905: 
 5906: sub digits_to_letters {
 5907:     my ($input) = @_;
 5908: 
 5909:     my @alphabet = ('J', 'A'..'I');
 5910: 
 5911:     my @input    = split(//, $input);
 5912:     my $output ='';
 5913:     for (my $i = 0; $i < scalar(@input); $i++) {
 5914: 	if ($input[$i] =~ /\d/) {
 5915: 	    $output .= $alphabet[$input[$i]];
 5916: 	} else {
 5917: 	    $output .= $input[$i];
 5918: 	}
 5919:     }
 5920:     return $output;
 5921: }
 5922: 
 5923: =pod 
 5924: 
 5925: =item scantron_parse_scanline
 5926: 
 5927:   Decodes a scanline from the selected bubblesheet file
 5928: 
 5929:  Arguments:
 5930:     line             - The text of the bubblesheet file line to process
 5931:     whichline        - Line number
 5932:     scantron_config  - Hash describing the format of the bubblesheet lines.
 5933:     scan_data        - Hash of extra information about the scanline
 5934:                        (see scantron_getfile for more information)
 5935:     just_header      - True if should not process question answers but only
 5936:                        the stuff to the left of the answers.
 5937:     randomorder      - True if randomorder in use
 5938:     randompick       - True if randompick in use
 5939:     sequence         - Exam folder URL
 5940:     master_seq       - Ref to array containing symbs in exam folder
 5941:     symb_to_resource - Ref to hash of symbs for resources in exam folder
 5942:                        (corresponding values are resource objects)
 5943:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
 5944:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
 5945:                        are refs to an array of resource objects, ordered
 5946:                        according to order used for CODE, when randomorder
 5947:                        and or randompick are in use.
 5948:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
 5949:                        for current line to question number used for same question
 5950:                         in "Master Sequence" (as seen by Course Coordinator).
 5951:     startline        - Ref to hash where key is question number (0 is first)
 5952:                        and value is number of first bubble line for current 
 5953:                        student or code-based randompick and/or randomorder.
 5954:     totalref         - Ref of scalar used to score total number of bubble
 5955:                        lines needed for responses in a scan line (used when
 5956:                        randompick in use. 
 5957:     
 5958:  Returns:
 5959:    Hash containing the result of parsing the scanline
 5960: 
 5961:    Keys are all proceeded by the string 'scantron.'
 5962: 
 5963:        CODE    - the CODE in use for this scanline
 5964:        useCODE - 1 if the CODE is invalid but it usage has been forced
 5965:                  by the operator
 5966:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 5967:                             CODEs were selected, but the usage has been
 5968:                             forced by the operator
 5969:        ID  - student/employee ID
 5970:        PaperID - if used, the ID number printed on the sheet when the 
 5971:                  paper was scanned
 5972:        FirstName - first name from the sheet
 5973:        LastName  - last name from the sheet
 5974: 
 5975:      if just_header was not true these key may also exist
 5976: 
 5977:        missingerror - a list of bubble ranges that are considered to be answers
 5978:                       to a single question that don't have any bubbles filled in.
 5979:                       Of the form questionnumber:firstbubblenumber:count.
 5980:        doubleerror  - a list of bubble ranges that are considered to be answers
 5981:                       to a single question that have more than one bubble filled in.
 5982:                       Of the form questionnumber::firstbubblenumber:count
 5983:    
 5984:                 In the above, count is the number of bubble responses in the
 5985:                 input line needed to represent the possible answers to the question.
 5986:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 5987:                 per line would have count = 2.
 5988: 
 5989:        maxquest     - the number of the last bubble line that was parsed
 5990: 
 5991:        (<number> starts at 1)
 5992:        <number>.answer - zero or more letters representing the selected
 5993:                          letters from the scanline for the bubble line 
 5994:                          <number>.
 5995:                          if blank there was either no bubble or there where
 5996:                          multiple bubbles, (consult the keys missingerror and
 5997:                          doubleerror if this is an error condition)
 5998: 
 5999: =cut
 6000: 
 6001: sub scantron_parse_scanline {
 6002:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
 6003:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
 6004:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
 6005: 
 6006:     my %record;
 6007:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
 6008:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 6009: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 6010: 	if ($$scantron_config{'CODElocation'} < 0 ||
 6011: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 6012: 	    $$scantron_config{'CODElocation'} eq 'number') {
 6013: 	    $record{'scantron.CODE'}=substr($data,
 6014: 					    $$scantron_config{'CODEstart'}-1,
 6015: 					    $$scantron_config{'CODElength'});
 6016: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 6017: 		$record{'scantron.useCODE'}=1;
 6018: 	    }
 6019: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 6020: 		$record{'scantron.CODE_ignore_dup'}=1;
 6021: 	    }
 6022: 	} else {
 6023: 	    #FIXME interpret first N questions
 6024: 	}
 6025:     }
 6026:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 6027: 				  $$scantron_config{'IDlength'});
 6028:     $record{'scantron.PaperID'}=
 6029: 	substr($data,$$scantron_config{'PaperID'}-1,
 6030: 	       $$scantron_config{'PaperIDlength'});
 6031:     $record{'scantron.FirstName'}=
 6032: 	substr($data,$$scantron_config{'FirstName'}-1,
 6033: 	       $$scantron_config{'FirstNamelength'});
 6034:     $record{'scantron.LastName'}=
 6035: 	substr($data,$$scantron_config{'LastName'}-1,
 6036: 	       $$scantron_config{'LastNamelength'});
 6037:     if ($just_header) { return \%record; }
 6038: 
 6039:     my @alphabet=('A'..'Z');
 6040:     my $questnum=0;
 6041:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 6042: 
 6043:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 6044:     if ($randompick || $randomorder) {
 6045:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
 6046:                                          $master_seq,$symb_to_resource,
 6047:                                          $partids_by_symb,$orderedforcode,
 6048:                                          $respnumlookup,$startline);
 6049:         if ($total) {
 6050:             $lastpos = $total*$$scantron_config{'Qlength'}; 
 6051:         }
 6052:         if (ref($totalref)) {
 6053:             $$totalref = $total;
 6054:         }
 6055:     }
 6056:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 6057:     chomp($questions);		# Get rid of any trailing \n.
 6058:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 6059:     while (length($questions)) {
 6060:         my $answers_needed;
 6061:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6062:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
 6063:         } else {
 6064: 	    $answers_needed = $bubble_lines_per_response{$questnum};
 6065:         }
 6066:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 6067:                              || 1;
 6068:         $questnum++;
 6069:         my $quest_id = $questnum;
 6070:         my $currentquest = substr($questions,0,$answer_length);
 6071:         $questions       = substr($questions,$answer_length);
 6072:         if (length($currentquest) < $answer_length) { next; }
 6073: 
 6074:         my $subdivided;
 6075:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6076:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
 6077:         } else {
 6078:             $subdivided = $subdivided_bubble_lines{$questnum-1};
 6079:         }
 6080:         if ($subdivided =~ /,/) {
 6081:             my $subquestnum = 1;
 6082:             my $subquestions = $currentquest;
 6083:             my @subanswers_needed = split(/,/,$subdivided);
 6084:             foreach my $subans (@subanswers_needed) {
 6085:                 my $subans_length =
 6086:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 6087:                 my $currsubquest = substr($subquestions,0,$subans_length);
 6088:                 $subquestions   = substr($subquestions,$subans_length);
 6089:                 $quest_id = "$questnum.$subquestnum";
 6090:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 6091:                     ($$scantron_config{'Qon'} eq 'number')) {
 6092:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 6093:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6094:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6095:                         $randomorder,$randompick,$respnumlookup);
 6096:                 } else {
 6097:                     $ansnum = &scantron_validator_positional($ansnum,
 6098:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6099:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6100:                         $randomorder,$randompick,$respnumlookup);
 6101:                 }
 6102:                 $subquestnum ++;
 6103:             }
 6104:         } else {
 6105:             if (($$scantron_config{'Qon'} eq 'letter') ||
 6106:                 ($$scantron_config{'Qon'} eq 'number')) {
 6107:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 6108:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6109:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6110:                     $randomorder,$randompick,$respnumlookup);
 6111:             } else {
 6112:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 6113:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6114:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6115:                     $randomorder,$randompick,$respnumlookup);
 6116:             }
 6117:         }
 6118:     }
 6119:     $record{'scantron.maxquest'}=$questnum;
 6120:     return \%record;
 6121: }
 6122: 
 6123: sub get_master_seq {
 6124:     my ($resources,$master_seq,$symb_to_resource) = @_;
 6125:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') && 
 6126:                    (ref($symb_to_resource) eq 'HASH'));
 6127:     my $resource_error;
 6128:     foreach my $resource (@{$resources}) {
 6129:         my $ressymb;
 6130:         if (ref($resource)) {
 6131:             $ressymb = $resource->symb();
 6132:             push(@{$master_seq},$ressymb);
 6133:             $symb_to_resource->{$ressymb} = $resource;
 6134:         } else {
 6135:             $resource_error = 1;
 6136:             last;
 6137:         }
 6138:     }
 6139:     return $resource_error;
 6140: }
 6141: 
 6142: sub get_respnum_lookups {
 6143:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
 6144:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
 6145:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
 6146:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
 6147:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
 6148:                    (ref($startline) eq 'HASH'));
 6149:     my ($user,$scancode);
 6150:     if ((exists($record->{'scantron.CODE'})) &&
 6151:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
 6152:         $scancode = $record->{'scantron.CODE'};
 6153:     } else {
 6154:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
 6155:     }
 6156:     my @mapresources =
 6157:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
 6158:                      $orderedforcode);
 6159:     my $total = 0;
 6160:     my $count = 0;
 6161:     foreach my $resource (@mapresources) {
 6162:         my $id = $resource->id();
 6163:         my $symb = $resource->symb();
 6164:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
 6165:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
 6166:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
 6167:                 if ($respnum ne '') {
 6168:                     $respnumlookup->{$count} = $respnum;
 6169:                     $startline->{$count} = $total;
 6170:                     $total += $bubble_lines_per_response{$respnum};
 6171:                     $count ++;
 6172:                 }
 6173:             }
 6174:         }
 6175:     }
 6176:     return $total;
 6177: }
 6178: 
 6179: sub scantron_validator_lettnum {
 6180:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 6181:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
 6182:         $randompick,$respnumlookup) = @_;
 6183: 
 6184:     # Qon 'letter' implies for each slot in currquest we have:
 6185:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 6186:     #    about anything else (esp. a value of Qoff) for missing
 6187:     #    bubbles.
 6188:     #
 6189:     # Qon 'number' implies each slot gives a digit that indexes the
 6190:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 6191:     #    and * or ? for double bubbles on a single line.
 6192:     #
 6193: 
 6194:     my $matchon;
 6195:     if ($$scantron_config{'Qon'} eq 'letter') {
 6196:         $matchon = '[A-Z]';
 6197:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 6198:         $matchon = '\d';
 6199:     }
 6200:     my $occurrences = 0;
 6201:     my $responsenum = $questnum-1;
 6202:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6203:        $responsenum = $respnumlookup->{$questnum-1} 
 6204:     }
 6205:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6206:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6207:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6208:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6209:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6210:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6211:         my @singlelines = split('',$currquest);
 6212:         foreach my $entry (@singlelines) {
 6213:             $occurrences = &occurence_count($entry,$matchon);
 6214:             if ($occurrences > 1) {
 6215:                 last;
 6216:             }
 6217:         }
 6218:     } else {
 6219:         $occurrences = &occurence_count($currquest,$matchon); 
 6220:     }
 6221:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 6222:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6223:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6224:             my $bubble = substr($currquest,$ans,1);
 6225:             if ($bubble =~ /$matchon/ ) {
 6226:                 if ($$scantron_config{'Qon'} eq 'number') {
 6227:                     if ($bubble == 0) {
 6228:                         $bubble = 10; 
 6229:                     }
 6230:                     $record->{"scantron.$ansnum.answer"} = 
 6231:                         $alphabet->[$bubble-1];
 6232:                 } else {
 6233:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 6234:                 }
 6235:             } else {
 6236:                 $record->{"scantron.$ansnum.answer"}='';
 6237:             }
 6238:             $ansnum++;
 6239:         }
 6240:     } elsif (!defined($currquest)
 6241:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 6242:             || (&occurence_count($currquest,$matchon) == 0)) {
 6243:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6244:             $record->{"scantron.$ansnum.answer"}='';
 6245:             $ansnum++;
 6246:         }
 6247:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6248:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 6249:         }
 6250:     } else {
 6251:         if ($$scantron_config{'Qon'} eq 'number') {
 6252:             $currquest = &digits_to_letters($currquest);            
 6253:         }
 6254:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6255:             my $bubble = substr($currquest,$ans,1);
 6256:             $record->{"scantron.$ansnum.answer"} = $bubble;
 6257:             $ansnum++;
 6258:         }
 6259:     }
 6260:     return $ansnum;
 6261: }
 6262: 
 6263: sub scantron_validator_positional {
 6264:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 6265:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
 6266:         $randomorder,$randompick,$respnumlookup) = @_;
 6267: 
 6268:     # Otherwise there's a positional notation;
 6269:     # each bubble line requires Qlength items, and there are filled in
 6270:     # bubbles for each case where there 'Qon' characters.
 6271:     #
 6272: 
 6273:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 6274: 
 6275:     # If the split only gives us one element.. the full length of the
 6276:     # answer string, no bubbles are filled in:
 6277: 
 6278:     if ($answers_needed eq '') {
 6279:         return;
 6280:     }
 6281: 
 6282:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 6283:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6284:             $record->{"scantron.$ansnum.answer"}='';
 6285:             $ansnum++;
 6286:         }
 6287:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6288:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 6289:         }
 6290:     } elsif (scalar(@array) == 2) {
 6291:         my $location = length($array[0]);
 6292:         my $line_num = int($location / $$scantron_config{'Qlength'});
 6293:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 6294:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6295:             if ($ans eq $line_num) {
 6296:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 6297:             } else {
 6298:                 $record->{"scantron.$ansnum.answer"} = ' ';
 6299:             }
 6300:             $ansnum++;
 6301:          }
 6302:     } else {
 6303:         #  If there's more than one instance of a bubble character
 6304:         #  That's a double bubble; with positional notation we can
 6305:         #  record all the bubbles filled in as well as the
 6306:         #  fact this response consists of multiple bubbles.
 6307:         #
 6308:         my $responsenum = $questnum-1;
 6309:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6310:             $responsenum = $respnumlookup->{$questnum-1}
 6311:         }
 6312:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6313:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6314:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6315:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6316:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6317:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6318:             my $doubleerror = 0;
 6319:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 6320:                    (!$doubleerror)) {
 6321:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 6322:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 6323:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 6324:                if (length(@currarray) > 2) {
 6325:                    $doubleerror = 1;
 6326:                } 
 6327:             }
 6328:             if ($doubleerror) {
 6329:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6330:             }
 6331:         } else {
 6332:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6333:         }
 6334:         my $item = $ansnum;
 6335:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6336:             $record->{"scantron.$item.answer"} = '';
 6337:             $item ++;
 6338:         }
 6339: 
 6340:         my @ans=@array;
 6341:         my $i=0;
 6342:         my $increment = 0;
 6343:         while ($#ans) {
 6344:             $i+=length($ans[0]) + $increment;
 6345:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 6346:             my $bubble = $i%$$scantron_config{'Qlength'};
 6347:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 6348:             shift(@ans);
 6349:             $increment = 1;
 6350:         }
 6351:         $ansnum += $answers_needed;
 6352:     }
 6353:     return $ansnum;
 6354: }
 6355: 
 6356: =pod
 6357: 
 6358: =item scantron_add_delay
 6359: 
 6360:    Adds an error message that occurred during the grading phase to a
 6361:    queue of messages to be shown after grading pass is complete
 6362: 
 6363:  Arguments:
 6364:    $delayqueue  - arrary ref of hash ref of error messages
 6365:    $scanline    - the scanline that caused the error
 6366:    $errormesage - the error message
 6367:    $errorcode   - a numeric code for the error
 6368: 
 6369:  Side Effects:
 6370:    updates the $delayqueue to have a new hash ref of the error
 6371: 
 6372: =cut
 6373: 
 6374: sub scantron_add_delay {
 6375:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 6376:     push(@$delayqueue,
 6377: 	 {'line' => $scanline, 'emsg' => $errormessage,
 6378: 	  'ecode' => $errorcode }
 6379: 	 );
 6380: }
 6381: 
 6382: =pod
 6383: 
 6384: =item scantron_find_student
 6385: 
 6386:    Finds the username for the current scanline
 6387: 
 6388:   Arguments:
 6389:    $scantron_record - hash result from scantron_parse_scanline
 6390:    $scan_data       - hash of correction information 
 6391:                       (see &scantron_getfile() form more information)
 6392:    $idmap           - hash from &username_to_idmap()
 6393:    $line            - number of current scanline
 6394:  
 6395:   Returns:
 6396:    Either 'username:domain' or undef if unknown
 6397: 
 6398: =cut
 6399: 
 6400: sub scantron_find_student {
 6401:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 6402:     my $scanID=$$scantron_record{'scantron.ID'};
 6403:     if ($scanID =~ /^\s*$/) {
 6404:  	return &scan_data($scan_data,"$line.user");
 6405:     }
 6406:     foreach my $id (keys(%$idmap)) {
 6407:  	if (lc($id) eq lc($scanID)) {
 6408:  	    return $$idmap{$id};
 6409:  	}
 6410:     }
 6411:     return undef;
 6412: }
 6413: 
 6414: =pod
 6415: 
 6416: =item scantron_filter
 6417: 
 6418:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 6419:    hidden resources was selected
 6420: 
 6421: =cut
 6422: 
 6423: sub scantron_filter {
 6424:     my ($curres)=@_;
 6425: 
 6426:     if (ref($curres) && $curres->is_problem()) {
 6427: 	# if the user has asked to not have either hidden
 6428: 	# or 'randomout' controlled resources to be graded
 6429: 	# don't include them
 6430: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6431: 	    && $curres->randomout) {
 6432: 	    return 0;
 6433: 	}
 6434: 	return 1;
 6435:     }
 6436:     return 0;
 6437: }
 6438: 
 6439: =pod
 6440: 
 6441: =item scantron_process_corrections
 6442: 
 6443:    Gets correction information out of submitted form data and corrects
 6444:    the scanline
 6445: 
 6446: =cut
 6447: 
 6448: sub scantron_process_corrections {
 6449:     my ($r) = @_;
 6450:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6451:     my ($scanlines,$scan_data)=&scantron_getfile();
 6452:     my $classlist=&Apache::loncoursedata::get_classlist();
 6453:     my $which=$env{'form.scantron_line'};
 6454:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 6455:     my ($skip,$err,$errmsg);
 6456:     if ($env{'form.scantron_skip_record'}) {
 6457: 	$skip=1;
 6458:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 6459: 	my $newstudent=$env{'form.scantron_username'}.':'.
 6460: 	    $env{'form.scantron_domain'};
 6461: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 6462: 	($line,$err,$errmsg)=
 6463: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6464: 				     'ID',{'newid'=>$newid,
 6465: 				    'username'=>$env{'form.scantron_username'},
 6466: 				    'domain'=>$env{'form.scantron_domain'}});
 6467:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 6468: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 6469: 	my $newCODE;
 6470: 	my %args;
 6471: 	if      ($resolution eq 'use_unfound') {
 6472: 	    $newCODE='use_unfound';
 6473: 	} elsif ($resolution eq 'use_found') {
 6474: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6475: 	} elsif ($resolution eq 'use_typed') {
 6476: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6477: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6478: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6479: 	}
 6480: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6481: 	    $args{'CODE_ignore_dup'}=1;
 6482: 	}
 6483: 	$args{'CODE'}=$newCODE;
 6484: 	($line,$err,$errmsg)=
 6485: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6486: 				     'CODE',\%args);
 6487:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6488: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6489: 	    ($line,$err,$errmsg)=
 6490: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6491: 					 $which,'answer',
 6492: 					 { 'question'=>$question,
 6493: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6494:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6495: 	    if ($err) { last; }
 6496: 	}
 6497:     }
 6498:     if ($err) {
 6499:         $r->print(
 6500:             '<p class="LC_error">'
 6501:            .&mt('Unable to accept last correction, an error occurred: [_1]',
 6502:                 $errmsg)
 6503:            .'</p>');
 6504:     } else {
 6505: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 6506: 	&scantron_putfile($scanlines,$scan_data);
 6507:     }
 6508: }
 6509: 
 6510: =pod
 6511: 
 6512: =item reset_skipping_status
 6513: 
 6514:    Forgets the current set of remember skipped scanlines (and thus
 6515:    reverts back to considering all lines in the
 6516:    scantron_skipped_<filename> file)
 6517: 
 6518: =cut
 6519: 
 6520: sub reset_skipping_status {
 6521:     my ($scanlines,$scan_data)=&scantron_getfile();
 6522:     &scan_data($scan_data,'remember_skipping',undef,1);
 6523:     &scantron_putfile(undef,$scan_data);
 6524: }
 6525: 
 6526: =pod
 6527: 
 6528: =item start_skipping
 6529: 
 6530:    Marks a scanline to be skipped. 
 6531: 
 6532: =cut
 6533: 
 6534: sub start_skipping {
 6535:     my ($scan_data,$i)=@_;
 6536:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6537:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6538: 	$remembered{$i}=2;
 6539:     } else {
 6540: 	$remembered{$i}=1;
 6541:     }
 6542:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6543: }
 6544: 
 6545: =pod
 6546: 
 6547: =item should_be_skipped
 6548: 
 6549:    Checks whether a scanline should be skipped.
 6550: 
 6551: =cut
 6552: 
 6553: sub should_be_skipped {
 6554:     my ($scanlines,$scan_data,$i)=@_;
 6555:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6556: 	# not redoing old skips
 6557: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6558: 	return 0;
 6559:     }
 6560:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6561: 
 6562:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6563: 	return 0;
 6564:     }
 6565:     return 1;
 6566: }
 6567: 
 6568: =pod
 6569: 
 6570: =item remember_current_skipped
 6571: 
 6572:    Discovers what scanlines are in the scantron_skipped_<filename>
 6573:    file and remembers them into scan_data for later use.
 6574: 
 6575: =cut
 6576: 
 6577: sub remember_current_skipped {
 6578:     my ($scanlines,$scan_data)=&scantron_getfile();
 6579:     my %to_remember;
 6580:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6581: 	if ($scanlines->{'skipped'}[$i]) {
 6582: 	    $to_remember{$i}=1;
 6583: 	}
 6584:     }
 6585: 
 6586:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6587:     &scantron_putfile(undef,$scan_data);
 6588: }
 6589: 
 6590: =pod
 6591: 
 6592: =item check_for_error
 6593: 
 6594:     Checks if there was an error when attempting to remove a specific
 6595:     scantron_.. bubblesheet data file. Prints out an error if
 6596:     something went wrong.
 6597: 
 6598: =cut
 6599: 
 6600: sub check_for_error {
 6601:     my ($r,$result)=@_;
 6602:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6603: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6604:     }
 6605: }
 6606: 
 6607: =pod
 6608: 
 6609: =item scantron_warning_screen
 6610: 
 6611:    Interstitial screen to make sure the operator has selected the
 6612:    correct options before we start the validation phase.
 6613: 
 6614: =cut
 6615: 
 6616: sub scantron_warning_screen {
 6617:     my ($button_text,$symb)=@_;
 6618:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6619:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6620:     my $CODElist;
 6621:     if ($scantron_config{'CODElocation'} &&
 6622: 	$scantron_config{'CODEstart'} &&
 6623: 	$scantron_config{'CODElength'}) {
 6624: 	$CODElist=$env{'form.scantron_CODElist'};
 6625: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
 6626: 	$CODElist=
 6627: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6628: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6629:     }
 6630:     my $lastbubblepoints;
 6631:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 6632:         $lastbubblepoints =
 6633:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
 6634:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
 6635:     }
 6636:     return ('
 6637: <p>
 6638: <span class="LC_warning">
 6639: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
 6640: </p>
 6641: <table>
 6642: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6643: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6644: '.$CODElist.$lastbubblepoints.'
 6645: </table>
 6646: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
 6647: '.&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>
 6648: 
 6649: <br />
 6650: ');
 6651: }
 6652: 
 6653: =pod
 6654: 
 6655: =item scantron_do_warning
 6656: 
 6657:    Check if the operator has picked something for all required
 6658:    fields. Error out if something is missing.
 6659: 
 6660: =cut
 6661: 
 6662: sub scantron_do_warning {
 6663:     my ($r,$symb)=@_;
 6664:     if (!$symb) {return '';}
 6665:     my $default_form_data=&defaultFormData($symb);
 6666:     $r->print(&scantron_form_start().$default_form_data);
 6667:     if ( $env{'form.selectpage'} eq '' ||
 6668: 	 $env{'form.scantron_selectfile'} eq '' ||
 6669: 	 $env{'form.scantron_format'} eq '' ) {
 6670: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
 6671: 	if ( $env{'form.selectpage'} eq '') {
 6672: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6673: 	} 
 6674: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6675: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
 6676: 	} 
 6677: 	if ( $env{'form.scantron_format'} eq '') {
 6678: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
 6679: 	} 
 6680:     } else {
 6681: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
 6682:         my $bubbledbyhand=&hand_bubble_option();
 6683: 	$r->print('
 6684: '.$warning.$bubbledbyhand.'
 6685: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6686: <input type="hidden" name="command" value="scantron_validate" />
 6687: ');
 6688:     }
 6689:     $r->print("</form><br />");
 6690:     return '';
 6691: }
 6692: 
 6693: =pod
 6694: 
 6695: =item scantron_form_start
 6696: 
 6697:     html hidden input for remembering all selected grading options
 6698: 
 6699: =cut
 6700: 
 6701: sub scantron_form_start {
 6702:     my ($max_bubble)=@_;
 6703:     my $result= <<SCANTRONFORM;
 6704: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6705:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6706:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6707:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6708:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6709:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6710:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6711:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6712:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6713:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6714: SCANTRONFORM
 6715: 
 6716:   my $line = 0;
 6717:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6718:        my $chunk =
 6719: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6720:        $chunk .=
 6721: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6722:        $chunk .= 
 6723:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6724:        $chunk .=
 6725:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6726:        $chunk .=
 6727:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
 6728:        $result .= $chunk;
 6729:        $line++;
 6730:     }
 6731:     return $result;
 6732: }
 6733: 
 6734: =pod
 6735: 
 6736: =item scantron_validate_file
 6737: 
 6738:     Dispatch routine for doing validation of a bubblesheet data file.
 6739: 
 6740:     Also processes any necessary information resets that need to
 6741:     occur before validation begins (ignore previous corrections,
 6742:     restarting the skipped records processing)
 6743: 
 6744: =cut
 6745: 
 6746: sub scantron_validate_file {
 6747:     my ($r,$symb) = @_;
 6748:     if (!$symb) {return '';}
 6749:     my $default_form_data=&defaultFormData($symb);
 6750:     
 6751:     # do the detection of only doing skipped records first before we delete
 6752:     # them when doing the corrections reset
 6753:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6754: 	&reset_skipping_status();
 6755:     }
 6756:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6757: 	&remember_current_skipped();
 6758: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6759:     }
 6760: 
 6761:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6762: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6763: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6764: 	&check_for_error($r,&scantron_remove_scan_data());
 6765: 	$env{'form.scantron_options_ignore'}='done';
 6766:     }
 6767: 
 6768:     if ($env{'form.scantron_corrections'}) {
 6769: 	&scantron_process_corrections($r);
 6770:     }
 6771:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6772:     #get the student pick code ready
 6773:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6774:     my $nav_error;
 6775:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6776:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 6777:     if ($nav_error) {
 6778:         $r->print(&navmap_errormsg());
 6779:         return '';
 6780:     }
 6781:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6782:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 6783:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
 6784:     }
 6785:     $r->print($result);
 6786:     
 6787:     my @validate_phases=( 'sequence',
 6788: 			  'ID',
 6789: 			  'CODE',
 6790: 			  'doublebubble',
 6791: 			  'missingbubbles');
 6792:     if (!$env{'form.validatepass'}) {
 6793: 	$env{'form.validatepass'} = 0;
 6794:     }
 6795:     my $currentphase=$env{'form.validatepass'};
 6796: 
 6797: 
 6798:     my $stop=0;
 6799:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6800: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6801: 	$r->rflush();
 6802:      
 6803: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6804: 	{
 6805: 	    no strict 'refs';
 6806: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6807: 	}
 6808:     }
 6809:     if (!$stop) {
 6810: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
 6811: 	$r->print(&mt('Validation process complete.').'<br />'.
 6812:                   $warning.
 6813:                   &mt('Perform verification for each student after storage of submissions?').
 6814:                   '&nbsp;<span class="LC_nobreak"><label>'.
 6815:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 6816:                   ('&nbsp;'x3).'<label>'.
 6817:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 6818:                   '</label></span><br />'.
 6819:                   &mt('Grading will take longer if you use verification.').'<br />'.
 6820:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
 6821:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 6822:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 6823:     } else {
 6824: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6825: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6826:     }
 6827:     if ($stop) {
 6828: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6829: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 6830: 	    $r->print(' '.&mt('this error').' <br />');
 6831: 
 6832: 	    $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>');
 6833: 	} else {
 6834:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6835: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 6836:             } else {
 6837:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 6838:             }
 6839: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6840: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6841: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6842: 	}
 6843:     }
 6844:     $r->print(" </form><br />");
 6845:     return '';
 6846: }
 6847: 
 6848: 
 6849: =pod
 6850: 
 6851: =item scantron_remove_file
 6852: 
 6853:    Removes the requested bubblesheet data file, makes sure that
 6854:    scantron_original_<filename> is never removed
 6855: 
 6856: 
 6857: =cut
 6858: 
 6859: sub scantron_remove_file {
 6860:     my ($which)=@_;
 6861:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6862:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6863:     my $file='scantron_';
 6864:     if ($which eq 'corrected' || $which eq 'skipped') {
 6865: 	$file.=$which.'_';
 6866:     } else {
 6867: 	return 'refused';
 6868:     }
 6869:     $file.=$env{'form.scantron_selectfile'};
 6870:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6871: }
 6872: 
 6873: 
 6874: =pod
 6875: 
 6876: =item scantron_remove_scan_data
 6877: 
 6878:    Removes all scan_data correction for the requested bubblesheet
 6879:    data file.  (In the case that both the are doing skipped records we need
 6880:    to remember the old skipped lines for the time being so that element
 6881:    persists for a while.)
 6882: 
 6883: =cut
 6884: 
 6885: sub scantron_remove_scan_data {
 6886:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6887:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6888:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6889:     my @todelete;
 6890:     my $filename=$env{'form.scantron_selectfile'};
 6891:     foreach my $key (@keys) {
 6892: 	if ($key=~/^\Q$filename\E_/) {
 6893: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6894: 		$key=~/remember_skipping/) {
 6895: 		next;
 6896: 	    }
 6897: 	    push(@todelete,$key);
 6898: 	}
 6899:     }
 6900:     my $result;
 6901:     if (@todelete) {
 6902: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6903: 				       \@todelete,$cdom,$cname);
 6904:     } else {
 6905: 	$result = 'ok';
 6906:     }
 6907:     return $result;
 6908: }
 6909: 
 6910: 
 6911: =pod
 6912: 
 6913: =item scantron_getfile
 6914: 
 6915:     Fetches the requested bubblesheet data file (all 3 versions), and
 6916:     the scan_data hash
 6917:   
 6918:   Arguments:
 6919:     None
 6920: 
 6921:   Returns:
 6922:     2 hash references
 6923: 
 6924:      - first one has 
 6925:          orig      -
 6926:          corrected -
 6927:          skipped   -  each of which points to an array ref of the specified
 6928:                       file broken up into individual lines
 6929:          count     - number of scanlines
 6930:  
 6931:      - second is the scan_data hash possible keys are
 6932:        ($number refers to scanline numbered $number and thus the key affects
 6933:         only that scanline
 6934:         $bubline refers to the specific bubble line element and the aspects
 6935:         refers to that specific bubble line element)
 6936: 
 6937:        $number.user - username:domain to use
 6938:        $number.CODE_ignore_dup 
 6939:                     - ignore the duplicate CODE error 
 6940:        $number.useCODE
 6941:                     - use the CODE in the scanline as is
 6942:        $number.no_bubble.$bubline
 6943:                     - it is valid that there is no bubbled in bubble
 6944:                       at $number $bubline
 6945:        remember_skipping
 6946:                     - a frozen hash containing keys of $number and values
 6947:                       of either 
 6948:                         1 - we are on a 'do skipped records pass' and plan
 6949:                             on processing this line
 6950:                         2 - we are on a 'do skipped records pass' and this
 6951:                             scanline has been marked to skip yet again
 6952: 
 6953: =cut
 6954: 
 6955: sub scantron_getfile {
 6956:     #FIXME really would prefer a scantron directory
 6957:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6958:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6959:     my $lines;
 6960:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6961: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 6962:     my %scanlines;
 6963:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 6964:     my $temp=$scanlines{'orig'};
 6965:     $scanlines{'count'}=$#$temp;
 6966: 
 6967:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6968: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 6969:     if ($lines eq '-1') {
 6970: 	$scanlines{'corrected'}=[];
 6971:     } else {
 6972: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 6973:     }
 6974:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6975: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 6976:     if ($lines eq '-1') {
 6977: 	$scanlines{'skipped'}=[];
 6978:     } else {
 6979: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 6980:     }
 6981:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 6982:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 6983:     my %scan_data = @tmp;
 6984:     return (\%scanlines,\%scan_data);
 6985: }
 6986: 
 6987: =pod
 6988: 
 6989: =item lonnet_putfile
 6990: 
 6991:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 6992: 
 6993:  Arguments:
 6994:    $contents - data to store
 6995:    $filename - filename to store $contents into
 6996: 
 6997:  Returns:
 6998:    result value from &Apache::lonnet::finishuserfileupload
 6999: 
 7000: =cut
 7001: 
 7002: sub lonnet_putfile {
 7003:     my ($contents,$filename)=@_;
 7004:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7005:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7006:     $env{'form.sillywaytopassafilearound'}=$contents;
 7007:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 7008: 
 7009: }
 7010: 
 7011: =pod
 7012: 
 7013: =item scantron_putfile
 7014: 
 7015:     Stores the current version of the bubblesheet data files, and the
 7016:     scan_data hash. (Does not modify the original version only the
 7017:     corrected and skipped versions.
 7018: 
 7019:  Arguments:
 7020:     $scanlines - hash ref that looks like the first return value from
 7021:                  &scantron_getfile()
 7022:     $scan_data - hash ref that looks like the second return value from
 7023:                  &scantron_getfile()
 7024: 
 7025: =cut
 7026: 
 7027: sub scantron_putfile {
 7028:     my ($scanlines,$scan_data) = @_;
 7029:     #FIXME really would prefer a scantron directory
 7030:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7031:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7032:     if ($scanlines) {
 7033: 	my $prefix='scantron_';
 7034: # no need to update orig, shouldn't change
 7035: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 7036: #		    $env{'form.scantron_selectfile'});
 7037: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 7038: 			$prefix.'corrected_'.
 7039: 			$env{'form.scantron_selectfile'});
 7040: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 7041: 			$prefix.'skipped_'.
 7042: 			$env{'form.scantron_selectfile'});
 7043:     }
 7044:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 7045: }
 7046: 
 7047: =pod
 7048: 
 7049: =item scantron_get_line
 7050: 
 7051:    Returns the correct version of the scanline
 7052: 
 7053:  Arguments:
 7054:     $scanlines - hash ref that looks like the first return value from
 7055:                  &scantron_getfile()
 7056:     $scan_data - hash ref that looks like the second return value from
 7057:                  &scantron_getfile()
 7058:     $i         - number of the requested line (starts at 0)
 7059: 
 7060:  Returns:
 7061:    A scanline, (either the original or the corrected one if it
 7062:    exists), or undef if the requested scanline should be
 7063:    skipped. (Either because it's an skipped scanline, or it's an
 7064:    unskipped scanline and we are not doing a 'do skipped scanlines'
 7065:    pass.
 7066: 
 7067: =cut
 7068: 
 7069: sub scantron_get_line {
 7070:     my ($scanlines,$scan_data,$i)=@_;
 7071:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 7072:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 7073:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 7074:     return $scanlines->{'orig'}[$i]; 
 7075: }
 7076: 
 7077: =pod
 7078: 
 7079: =item scantron_todo_count
 7080: 
 7081:     Counts the number of scanlines that need processing.
 7082: 
 7083:  Arguments:
 7084:     $scanlines - hash ref that looks like the first return value from
 7085:                  &scantron_getfile()
 7086:     $scan_data - hash ref that looks like the second return value from
 7087:                  &scantron_getfile()
 7088: 
 7089:  Returns:
 7090:     $count - number of scanlines to process
 7091: 
 7092: =cut
 7093: 
 7094: sub get_todo_count {
 7095:     my ($scanlines,$scan_data)=@_;
 7096:     my $count=0;
 7097:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7098: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7099: 	if ($line=~/^[\s\cz]*$/) { next; }
 7100: 	$count++;
 7101:     }
 7102:     return $count;
 7103: }
 7104: 
 7105: =pod
 7106: 
 7107: =item scantron_put_line
 7108: 
 7109:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
 7110:     data file.
 7111: 
 7112:  Arguments:
 7113:     $scanlines - hash ref that looks like the first return value from
 7114:                  &scantron_getfile()
 7115:     $scan_data - hash ref that looks like the second return value from
 7116:                  &scantron_getfile()
 7117:     $i         - line number to update
 7118:     $newline   - contents of the updated scanline
 7119:     $skip      - if true make the line for skipping and update the
 7120:                  'skipped' file
 7121: 
 7122: =cut
 7123: 
 7124: sub scantron_put_line {
 7125:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 7126:     if ($skip) {
 7127: 	$scanlines->{'skipped'}[$i]=$newline;
 7128: 	&start_skipping($scan_data,$i);
 7129: 	return;
 7130:     }
 7131:     $scanlines->{'corrected'}[$i]=$newline;
 7132: }
 7133: 
 7134: =pod
 7135: 
 7136: =item scantron_clear_skip
 7137: 
 7138:    Remove a line from the 'skipped' file
 7139: 
 7140:  Arguments:
 7141:     $scanlines - hash ref that looks like the first return value from
 7142:                  &scantron_getfile()
 7143:     $scan_data - hash ref that looks like the second return value from
 7144:                  &scantron_getfile()
 7145:     $i         - line number to update
 7146: 
 7147: =cut
 7148: 
 7149: sub scantron_clear_skip {
 7150:     my ($scanlines,$scan_data,$i)=@_;
 7151:     if (exists($scanlines->{'skipped'}[$i])) {
 7152: 	undef($scanlines->{'skipped'}[$i]);
 7153: 	return 1;
 7154:     }
 7155:     return 0;
 7156: }
 7157: 
 7158: =pod
 7159: 
 7160: =item scantron_filter_not_exam
 7161: 
 7162:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 7163:    filter out resources that are not marked as 'exam' mode
 7164: 
 7165: =cut
 7166: 
 7167: sub scantron_filter_not_exam {
 7168:     my ($curres)=@_;
 7169:     
 7170:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 7171: 	# if the user has asked to not have either hidden
 7172: 	# or 'randomout' controlled resources to be graded
 7173: 	# don't include them
 7174: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 7175: 	    && $curres->randomout) {
 7176: 	    return 0;
 7177: 	}
 7178: 	return 1;
 7179:     }
 7180:     return 0;
 7181: }
 7182: 
 7183: =pod
 7184: 
 7185: =item scantron_validate_sequence
 7186: 
 7187:     Validates the selected sequence, checking for resource that are
 7188:     not set to exam mode.
 7189: 
 7190: =cut
 7191: 
 7192: sub scantron_validate_sequence {
 7193:     my ($r,$currentphase) = @_;
 7194: 
 7195:     my $navmap=Apache::lonnavmaps::navmap->new();
 7196:     unless (ref($navmap)) {
 7197:         $r->print(&navmap_errormsg());
 7198:         return (1,$currentphase);
 7199:     }
 7200:     my (undef,undef,$sequence)=
 7201: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7202: 
 7203:     my $map=$navmap->getResourceByUrl($sequence);
 7204: 
 7205:     $r->print('<input type="hidden" name="validate_sequence_exam"
 7206:                                     value="ignore" />');
 7207:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 7208: 	my @resources=
 7209: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 7210: 	if (@resources) {
 7211: 	    $r->print(
 7212:                 '<p class="LC_warning">'
 7213:                .&mt('Some resources in the sequence currently are not set to'
 7214:                    .' bubblesheet exam mode. Grading these resources currently may not'
 7215:                    .' work correctly.')
 7216:                .'</p>'
 7217:             );
 7218: 	    return (1,$currentphase);
 7219: 	}
 7220:     }
 7221: 
 7222:     return (0,$currentphase+1);
 7223: }
 7224: 
 7225: 
 7226: 
 7227: sub scantron_validate_ID {
 7228:     my ($r,$currentphase) = @_;
 7229:     
 7230:     #get student info
 7231:     my $classlist=&Apache::loncoursedata::get_classlist();
 7232:     my %idmap=&username_to_idmap($classlist);
 7233: 
 7234:     #get scantron line setup
 7235:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7236:     my ($scanlines,$scan_data)=&scantron_getfile();
 7237: 
 7238:     my $nav_error;
 7239:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
 7240:     if ($nav_error) {
 7241:         $r->print(&navmap_errormsg());
 7242:         return(1,$currentphase);
 7243:     }
 7244: 
 7245:     my %found=('ids'=>{},'usernames'=>{});
 7246:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7247: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7248: 	if ($line=~/^[\s\cz]*$/) { next; }
 7249: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7250: 						 $scan_data);
 7251: 	my $id=$$scan_record{'scantron.ID'};
 7252: 	my $found;
 7253: 	foreach my $checkid (keys(%idmap)) {
 7254: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 7255: 	}
 7256: 	if ($found) {
 7257: 	    my $username=$idmap{$found};
 7258: 	    if ($found{'ids'}{$found}) {
 7259: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7260: 					 $line,'duplicateID',$found);
 7261: 		return(1,$currentphase);
 7262: 	    } elsif ($found{'usernames'}{$username}) {
 7263: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7264: 					 $line,'duplicateID',$username);
 7265: 		return(1,$currentphase);
 7266: 	    }
 7267: 	    #FIXME store away line we previously saw the ID on to use above
 7268: 	    $found{'ids'}{$found}++;
 7269: 	    $found{'usernames'}{$username}++;
 7270: 	} else {
 7271: 	    if ($id =~ /^\s*$/) {
 7272: 		my $username=&scan_data($scan_data,"$i.user");
 7273: 		if (defined($username) && $found{'usernames'}{$username}) {
 7274: 		    &scantron_get_correction($r,$i,$scan_record,
 7275: 					     \%scantron_config,
 7276: 					     $line,'duplicateID',$username);
 7277: 		    return(1,$currentphase);
 7278: 		} elsif (!defined($username)) {
 7279: 		    &scantron_get_correction($r,$i,$scan_record,
 7280: 					     \%scantron_config,
 7281: 					     $line,'incorrectID');
 7282: 		    return(1,$currentphase);
 7283: 		}
 7284: 		$found{'usernames'}{$username}++;
 7285: 	    } else {
 7286: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7287: 					 $line,'incorrectID');
 7288: 		return(1,$currentphase);
 7289: 	    }
 7290: 	}
 7291:     }
 7292: 
 7293:     return (0,$currentphase+1);
 7294: }
 7295: 
 7296: 
 7297: sub scantron_get_correction {
 7298:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
 7299:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
 7300: #FIXME in the case of a duplicated ID the previous line, probably need
 7301: #to show both the current line and the previous one and allow skipping
 7302: #the previous one or the current one
 7303: 
 7304:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 7305:         $r->print(
 7306:             '<p class="LC_warning">'
 7307:            .&mt('An error was detected ([_1]) for PaperID [_2]',
 7308:                 "<b>$error</b>",
 7309:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
 7310:            ."</p> \n");
 7311:     } else {
 7312:         $r->print(
 7313:             '<p class="LC_warning">'
 7314:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
 7315:                 "<b>$error</b>", $i, "<pre>$line</pre>")
 7316:            ."</p> \n");
 7317:     }
 7318:     my $message =
 7319:         '<p>'
 7320:        .&mt('The ID on the form is [_1]',
 7321:             "<tt>$$scan_record{'scantron.ID'}</tt>")
 7322:        .'<br />'
 7323:        .&mt('The name on the paper is [_1], [_2]',
 7324:             $$scan_record{'scantron.LastName'},
 7325:             $$scan_record{'scantron.FirstName'})
 7326:        .'</p>';
 7327: 
 7328:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 7329:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 7330:                            # Array populated for doublebubble or
 7331:     my @lines_to_correct;  # missingbubble errors to build javascript
 7332:                            # to validate radio button checking   
 7333: 
 7334:     if ($error =~ /ID$/) {
 7335: 	if ($error eq 'incorrectID') {
 7336:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
 7337: 		      "</p>\n");
 7338: 	} elsif ($error eq 'duplicateID') {
 7339:             $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 7340: 	}
 7341: 	$r->print($message);
 7342: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 7343: 	$r->print("\n<ul><li> ");
 7344: 	#FIXME it would be nice if this sent back the user ID and
 7345: 	#could do partial userID matches
 7346: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 7347: 				       'scantron_username','scantron_domain'));
 7348: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 7349: 	$r->print("\n:\n".
 7350: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 7351: 
 7352: 	$r->print('</li>');
 7353:     } elsif ($error =~ /CODE$/) {
 7354: 	if ($error eq 'incorrectCODE') {
 7355: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 7356: 	} elsif ($error eq 'duplicateCODE') {
 7357: 	    $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");
 7358: 	}
 7359: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
 7360: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
 7361:                  ."</p>\n");
 7362: 	$r->print($message);
 7363: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
 7364: 	$r->print("\n<br /> ");
 7365: 	my $i=0;
 7366: 	if ($error eq 'incorrectCODE' 
 7367: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 7368: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 7369: 	    if ($closest > 0) {
 7370: 		foreach my $testcode (@{$closest}) {
 7371: 		    my $checked='';
 7372: 		    if (!$i) { $checked=' checked="checked"'; }
 7373: 		    $r->print("
 7374:    <label>
 7375:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 7376:        ".&mt("Use the similar CODE [_1] instead.",
 7377: 	    "<b><tt>".$testcode."</tt></b>")."
 7378:     </label>
 7379:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 7380: 		    $r->print("\n<br />");
 7381: 		    $i++;
 7382: 		}
 7383: 	    }
 7384: 	}
 7385: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 7386: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 7387: 	    $r->print("
 7388:     <label>
 7389:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 7390:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
 7391: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 7392:     </label>");
 7393: 	    $r->print("\n<br />");
 7394: 	}
 7395: 
 7396: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
 7397: function change_radio(field) {
 7398:     var slct=document.scantronupload.scantron_CODE_resolution;
 7399:     var i;
 7400:     for (i=0;i<slct.length;i++) {
 7401:         if (slct[i].value==field) { slct[i].checked=true; }
 7402:     }
 7403: }
 7404: ENDSCRIPT
 7405: 	my $href="/adm/pickcode?".
 7406: 	   "form=".&escape("scantronupload").
 7407: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 7408: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 7409: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 7410: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 7411: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 7412: 	    $r->print("
 7413:     <label>
 7414:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 7415:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 7416: 	     "<a target='_blank' href='$href'>","</a>")."
 7417:     </label> 
 7418:     ".&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\')" />'));
 7419: 	    $r->print("\n<br />");
 7420: 	}
 7421: 	$r->print("
 7422:     <label>
 7423:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 7424:        ".&mt("Use [_1] as the CODE.",
 7425: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 7426: 	$r->print("\n<br /><br />");
 7427:     } elsif ($error eq 'doublebubble') {
 7428: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 7429: 
 7430: 	# The form field scantron_questions is acutally a list of line numbers.
 7431: 	# represented by this form so:
 7432: 
 7433: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7434:                                                 $respnumlookup,$startline);
 7435: 
 7436: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7437: 		  $line_list.'" />');
 7438: 	$r->print($message);
 7439: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 7440: 	foreach my $question (@{$arg}) {
 7441: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7442:                                                    $scan_record, $error,
 7443:                                                    $randomorder,$randompick,
 7444:                                                    $respnumlookup,$startline);
 7445:             push(@lines_to_correct,@linenums);
 7446: 	}
 7447:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7448:     } elsif ($error eq 'missingbubble') {
 7449: 	$r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
 7450: 	$r->print($message);
 7451: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 7452: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 7453: 
 7454: 	# The form field scantron_questions is actually a list of line numbers not
 7455: 	# a list of question numbers. Therefore:
 7456: 	#
 7457: 
 7458: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7459:                                                 $respnumlookup,$startline);
 7460: 
 7461: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7462: 		  $line_list.'" />');
 7463: 	foreach my $question (@{$arg}) {
 7464: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7465:                                                    $scan_record, $error,
 7466:                                                    $randomorder,$randompick,
 7467:                                                    $respnumlookup,$startline);
 7468:             push(@lines_to_correct,@linenums);
 7469: 	}
 7470:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7471:     } else {
 7472: 	$r->print("\n<ul>");
 7473:     }
 7474:     $r->print("\n</li></ul>");
 7475: }
 7476: 
 7477: sub verify_bubbles_checked {
 7478:     my (@ansnums) = @_;
 7479:     my $ansnumstr = join('","',@ansnums);
 7480:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 7481:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
 7482: function verify_bubble_radio(form) {
 7483:     var ansnumArray = new Array ("$ansnumstr");
 7484:     var need_bubble_count = 0;
 7485:     for (var i=0; i<ansnumArray.length; i++) {
 7486:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 7487:             var bubble_picked = 0; 
 7488:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 7489:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 7490:                     bubble_picked = 1;
 7491:                 }
 7492:             }
 7493:             if (bubble_picked == 0) {
 7494:                 need_bubble_count ++;
 7495:             }
 7496:         }
 7497:     }
 7498:     if (need_bubble_count) {
 7499:         alert("$warning");
 7500:         return;
 7501:     }
 7502:     form.submit(); 
 7503: }
 7504: ENDSCRIPT
 7505:     return $output;
 7506: }
 7507: 
 7508: =pod
 7509: 
 7510: =item  questions_to_line_list
 7511: 
 7512: Converts a list of questions into a string of comma separated
 7513: line numbers in the answer sheet used by the questions.  This is
 7514: used to fill in the scantron_questions form field.
 7515: 
 7516:   Arguments:
 7517:      questions    - Reference to an array of questions.
 7518:      randomorder  - True if randomorder in use.
 7519:      randompick   - True if randompick in use.
 7520:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
 7521:                      for current line to question number used for same question
 7522:                      in "Master Seqence" (as seen by Course Coordinator).
 7523:      startline    - Reference to hash where key is question number (0 is first)
 7524:                     and key is number of first bubble line for current student
 7525:                     or code-based randompick and/or randomorder.
 7526: 
 7527: =cut
 7528: 
 7529: 
 7530: sub questions_to_line_list {
 7531:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
 7532:     my @lines;
 7533: 
 7534:     foreach my $item (@{$questions}) {
 7535:         my $question = $item;
 7536:         my ($first,$count,$last);
 7537:         if ($item =~ /^(\d+)\.(\d+)$/) {
 7538:             $question = $1;
 7539:             my $subquestion = $2;
 7540:             my $responsenum = $question-1;
 7541:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7542:                 $responsenum = $respnumlookup->{$question-1};
 7543:                 if (ref($startline) eq 'HASH') {
 7544:                     $first = $startline->{$question-1} + 1;
 7545:                 }
 7546:             } else {
 7547:                 $first = $first_bubble_line{$responsenum} + 1;
 7548:             }
 7549:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 7550:             my $subcount = 1;
 7551:             while ($subcount<$subquestion) {
 7552:                 $first += $subans[$subcount-1];
 7553:                 $subcount ++;
 7554:             }
 7555:             $count = $subans[$subquestion-1];
 7556:         } else {
 7557:             my $responsenum = $question-1;
 7558:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7559:                 $responsenum = $respnumlookup->{$question-1};
 7560:                 if (ref($startline) eq 'HASH') {
 7561:                     $first = $startline->{$question-1} + 1;
 7562:                 }
 7563:             } else {
 7564:                 $first = $first_bubble_line{$responsenum} + 1;
 7565:             }
 7566: 	    $count   = $bubble_lines_per_response{$responsenum};
 7567:         }
 7568:         $last = $first+$count-1;
 7569:         push(@lines, ($first..$last));
 7570:     }
 7571:     return join(',', @lines);
 7572: }
 7573: 
 7574: =pod 
 7575: 
 7576: =item prompt_for_corrections
 7577: 
 7578: Prompts for a potentially multiline correction to the
 7579: user's bubbling (factors out common code from scantron_get_correction
 7580: for multi and missing bubble cases).
 7581: 
 7582:  Arguments:
 7583:    $r           - Apache request object.
 7584:    $question    - The question number to prompt for.
 7585:    $scan_config - The scantron file configuration hash.
 7586:    $scan_record - Reference to the hash that has the the parsed scanlines.
 7587:    $error       - Type of error
 7588:    $randomorder - True if randomorder in use.
 7589:    $randompick  - True if randompick in use.
 7590:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
 7591:                     for current line to question number used for same question
 7592:                     in "Master Seqence" (as seen by Course Coordinator).
 7593:    $startline   - Reference to hash where key is question number (0 is first)
 7594:                   and value is number of first bubble line for current student
 7595:                   or code-based randompick and/or randomorder.
 7596: 
 7597: 
 7598:  Implicit inputs:
 7599:    %bubble_lines_per_response   - Starting line numbers for each question.
 7600:                                   Numbered from 0 (but question numbers are from
 7601:                                   1.
 7602:    %first_bubble_line           - Starting bubble line for each question.
 7603:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 7604:                                   type problems render as separate sub-questions, 
 7605:                                   in exam mode. This hash contains a 
 7606:                                   comma-separated list of the lines per 
 7607:                                   sub-question.
 7608:    %responsetype_per_response   - essayresponse, formularesponse,
 7609:                                   stringresponse, imageresponse, reactionresponse,
 7610:                                   and organicresponse type problem parts can have
 7611:                                   multiple lines per response if the weight
 7612:                                   assigned exceeds 10.  In this case, only
 7613:                                   one bubble per line is permitted, but more 
 7614:                                   than one line might contain bubbles, e.g.
 7615:                                   bubbling of: line 1 - J, line 2 - J, 
 7616:                                   line 3 - B would assign 22 points.  
 7617: 
 7618: =cut
 7619: 
 7620: sub prompt_for_corrections {
 7621:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
 7622:         $randompick, $respnumlookup, $startline) = @_;
 7623:     my ($current_line,$lines);
 7624:     my @linenums;
 7625:     my $questionnum = $question;
 7626:     my ($first,$responsenum);
 7627:     if ($question =~ /^(\d+)\.(\d+)$/) {
 7628:         $question = $1;
 7629:         my $subquestion = $2;
 7630:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7631:             $responsenum = $respnumlookup->{$question-1};
 7632:             if (ref($startline) eq 'HASH') {
 7633:                 $first = $startline->{$question-1};
 7634:             }
 7635:         } else {
 7636:             $responsenum = $question-1;
 7637:             $first = $first_bubble_line{$responsenum};
 7638:         }
 7639:         $current_line = $first + 1 ;
 7640:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 7641:         my $subcount = 1;
 7642:         while ($subcount<$subquestion) {
 7643:             $current_line += $subans[$subcount-1];
 7644:             $subcount ++;
 7645:         }
 7646:         $lines = $subans[$subquestion-1];
 7647:     } else {
 7648:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7649:             $responsenum = $respnumlookup->{$question-1};
 7650:             if (ref($startline) eq 'HASH') { 
 7651:                 $first = $startline->{$question-1};
 7652:             }
 7653:         } else {
 7654:             $responsenum = $question-1;
 7655:             $first = $first_bubble_line{$responsenum};
 7656:         }
 7657:         $current_line = $first + 1;
 7658:         $lines        = $bubble_lines_per_response{$responsenum};
 7659:     }
 7660:     if ($lines > 1) {
 7661:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7662:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 7663:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 7664:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 7665:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 7666:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 7667:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 7668:             $r->print(
 7669:                 &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)
 7670:                .'<br /><br />'
 7671:                .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
 7672:                .'<br />'
 7673:                .&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.')
 7674:                .'<br />'
 7675:                .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
 7676:                .'<br /><br />'
 7677:             );
 7678:         } else {
 7679:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7680:         }
 7681:     }
 7682:     for (my $i =0; $i < $lines; $i++) {
 7683:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7684: 	&scantron_bubble_selector($r,$scan_config,$current_line,
 7685: 	        		  $questionnum,$error,split('', $selected));
 7686:         push(@linenums,$current_line);
 7687: 	$current_line++;
 7688:     }
 7689:     if ($lines > 1) {
 7690: 	$r->print("<hr /><br />");
 7691:     }
 7692:     return @linenums;
 7693: }
 7694: 
 7695: =pod
 7696: 
 7697: =item scantron_bubble_selector
 7698:   
 7699:    Generates the html radiobuttons to correct a single bubble line
 7700:    possibly showing the existing the selected bubbles if known
 7701: 
 7702:  Arguments:
 7703:     $r           - Apache request object
 7704:     $scan_config - hash from &get_scantron_config()
 7705:     $line        - Number of the line being displayed.
 7706:     $questionnum - Question number (may include subquestion)
 7707:     $error       - Type of error.
 7708:     @selected    - Array of bubbles picked on this line.
 7709: 
 7710: =cut
 7711: 
 7712: sub scantron_bubble_selector {
 7713:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7714:     my $max=$$scan_config{'Qlength'};
 7715: 
 7716:     my $scmode=$$scan_config{'Qon'};
 7717:     if ($scmode eq 'number' || $scmode eq 'letter') { 
 7718:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
 7719:             ($$scan_config{'BubblesPerRow'} > 0)) {
 7720:             $max=$$scan_config{'BubblesPerRow'};
 7721:             if (($scmode eq 'number') && ($max > 10)) {
 7722:                 $max = 10;
 7723:             } elsif (($scmode eq 'letter') && $max > 26) {
 7724:                 $max = 26;
 7725:             }
 7726:         } else {
 7727:             $max = 10;
 7728:         }
 7729:     }
 7730: 
 7731:     my @alphabet=('A'..'Z');
 7732:     $r->print(&Apache::loncommon::start_data_table().
 7733:               &Apache::loncommon::start_data_table_row());
 7734:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7735:     for (my $i=0;$i<$max+1;$i++) {
 7736: 	$r->print("\n".'<td align="center">');
 7737: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7738: 	else { $r->print('&nbsp;'); }
 7739: 	$r->print('</td>');
 7740:     }
 7741:     $r->print(&Apache::loncommon::end_data_table_row().
 7742:               &Apache::loncommon::start_data_table_row());
 7743:     for (my $i=0;$i<$max;$i++) {
 7744: 	$r->print("\n".
 7745: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7746: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7747:     }
 7748:     my $nobub_checked = ' ';
 7749:     if ($error eq 'missingbubble') {
 7750:         $nobub_checked = ' checked = "checked" ';
 7751:     }
 7752:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7753: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7754:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7755:               $line.'" value="'.$questionnum.'" /></td>');
 7756:     $r->print(&Apache::loncommon::end_data_table_row().
 7757:               &Apache::loncommon::end_data_table());
 7758: }
 7759: 
 7760: =pod
 7761: 
 7762: =item num_matches
 7763: 
 7764:    Counts the number of characters that are the same between the two arguments.
 7765: 
 7766:  Arguments:
 7767:    $orig - CODE from the scanline
 7768:    $code - CODE to match against
 7769: 
 7770:  Returns:
 7771:    $count - integer count of the number of same characters between the
 7772:             two arguments
 7773: 
 7774: =cut
 7775: 
 7776: sub num_matches {
 7777:     my ($orig,$code) = @_;
 7778:     my @code=split(//,$code);
 7779:     my @orig=split(//,$orig);
 7780:     my $same=0;
 7781:     for (my $i=0;$i<scalar(@code);$i++) {
 7782: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7783:     }
 7784:     return $same;
 7785: }
 7786: 
 7787: =pod
 7788: 
 7789: =item scantron_get_closely_matching_CODEs
 7790: 
 7791:    Cycles through all CODEs and finds the set that has the greatest
 7792:    number of same characters as the provided CODE
 7793: 
 7794:  Arguments:
 7795:    $allcodes - hash ref returned by &get_codes()
 7796:    $CODE     - CODE from the current scanline
 7797: 
 7798:  Returns:
 7799:    2 element list
 7800:     - first elements is number of how closely matching the best fit is 
 7801:       (5 means best set has 5 matching characters)
 7802:     - second element is an arrary ref containing the set of valid CODEs
 7803:       that best fit the passed in CODE
 7804: 
 7805: =cut
 7806: 
 7807: sub scantron_get_closely_matching_CODEs {
 7808:     my ($allcodes,$CODE)=@_;
 7809:     my @CODEs;
 7810:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7811: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7812:     }
 7813: 
 7814:     return ($#CODEs,$CODEs[-1]);
 7815: }
 7816: 
 7817: =pod
 7818: 
 7819: =item get_codes
 7820: 
 7821:    Builds a hash which has keys of all of the valid CODEs from the selected
 7822:    set of remembered CODEs.
 7823: 
 7824:  Arguments:
 7825:   $old_name - name of the set of remembered CODEs
 7826:   $cdom     - domain of the course
 7827:   $cnum     - internal course name
 7828: 
 7829:  Returns:
 7830:   %allcodes - keys are the valid CODEs, values are all 1
 7831: 
 7832: =cut
 7833: 
 7834: sub get_codes {
 7835:     my ($old_name, $cdom, $cnum) = @_;
 7836:     if (!$old_name) {
 7837: 	$old_name=$env{'form.scantron_CODElist'};
 7838:     }
 7839:     if (!$cdom) {
 7840: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7841:     }
 7842:     if (!$cnum) {
 7843: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7844:     }
 7845:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7846: 				    $cdom,$cnum);
 7847:     my %allcodes;
 7848:     if ($result{"type\0$old_name"} eq 'number') {
 7849: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7850:     } else {
 7851: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7852:     }
 7853:     return %allcodes;
 7854: }
 7855: 
 7856: =pod
 7857: 
 7858: =item scantron_validate_CODE
 7859: 
 7860:    Validates all scanlines in the selected file to not have any
 7861:    invalid or underspecified CODEs and that none of the codes are
 7862:    duplicated if this was requested.
 7863: 
 7864: =cut
 7865: 
 7866: sub scantron_validate_CODE {
 7867:     my ($r,$currentphase) = @_;
 7868:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7869:     if ($scantron_config{'CODElocation'} &&
 7870: 	$scantron_config{'CODEstart'} &&
 7871: 	$scantron_config{'CODElength'}) {
 7872: 	if (!defined($env{'form.scantron_CODElist'})) {
 7873: 	    &FIXME_blow_up()
 7874: 	}
 7875:     } else {
 7876: 	return (0,$currentphase+1);
 7877:     }
 7878:     
 7879:     my %usedCODEs;
 7880: 
 7881:     my %allcodes=&get_codes();
 7882: 
 7883:     my $nav_error;
 7884:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
 7885:     if ($nav_error) {
 7886:         $r->print(&navmap_errormsg());
 7887:         return(1,$currentphase);
 7888:     }
 7889: 
 7890:     my ($scanlines,$scan_data)=&scantron_getfile();
 7891:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7892: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7893: 	if ($line=~/^[\s\cz]*$/) { next; }
 7894: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7895: 						 $scan_data);
 7896: 	my $CODE=$$scan_record{'scantron.CODE'};
 7897: 	my $error=0;
 7898: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7899: 	    &scantron_get_correction($r,$i,$scan_record,
 7900: 				     \%scantron_config,
 7901: 				     $line,'incorrectCODE',\%allcodes);
 7902: 	    return(1,$currentphase);
 7903: 	}
 7904: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7905: 	    && !$$scan_record{'scantron.useCODE'}) {
 7906: 	    &scantron_get_correction($r,$i,$scan_record,
 7907: 				     \%scantron_config,
 7908: 				     $line,'incorrectCODE',\%allcodes);
 7909: 	    return(1,$currentphase);
 7910: 	}
 7911: 	if (exists($usedCODEs{$CODE}) 
 7912: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 7913: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 7914: 	    &scantron_get_correction($r,$i,$scan_record,
 7915: 				     \%scantron_config,
 7916: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 7917: 	    return(1,$currentphase);
 7918: 	}
 7919: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 7920:     }
 7921:     return (0,$currentphase+1);
 7922: }
 7923: 
 7924: =pod
 7925: 
 7926: =item scantron_validate_doublebubble
 7927: 
 7928:    Validates all scanlines in the selected file to not have any
 7929:    bubble lines with multiple bubbles marked.
 7930: 
 7931: =cut
 7932: 
 7933: sub scantron_validate_doublebubble {
 7934:     my ($r,$currentphase) = @_;
 7935:     #get student info
 7936:     my $classlist=&Apache::loncoursedata::get_classlist();
 7937:     my %idmap=&username_to_idmap($classlist);
 7938:     my (undef,undef,$sequence)=
 7939:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 7940: 
 7941:     #get scantron line setup
 7942:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7943:     my ($scanlines,$scan_data)=&scantron_getfile();
 7944: 
 7945:     my $navmap = Apache::lonnavmaps::navmap->new();
 7946:     unless (ref($navmap)) {
 7947:         $r->print(&navmap_errormsg());
 7948:         return(1,$currentphase);
 7949:     }
 7950:     my $map=$navmap->getResourceByUrl($sequence);
 7951:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7952:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 7953:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 7954:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 7955: 
 7956:     my $nav_error;
 7957:     if (ref($map)) {
 7958:         $randomorder = $map->randomorder();
 7959:         $randompick = $map->randompick();
 7960:         if ($randomorder || $randompick) {
 7961:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 7962:             if ($nav_error) {
 7963:                 $r->print(&navmap_errormsg());
 7964:                 return(1,$currentphase);
 7965:             }
 7966:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 7967:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 7968:         }
 7969:     } else {
 7970:         $r->print(&navmap_errormsg());
 7971:         return(1,$currentphase);
 7972:     }
 7973: 
 7974:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
 7975:     if ($nav_error) {
 7976:         $r->print(&navmap_errormsg());
 7977:         return(1,$currentphase);
 7978:     }
 7979: 
 7980:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7981: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7982: 	if ($line=~/^[\s\cz]*$/) { next; }
 7983: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7984: 						 $scan_data,undef,\%idmap,$randomorder,
 7985:                                                  $randompick,$sequence,\@master_seq,
 7986:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 7987:                                                  \%orderedforcode,\%respnumlookup,\%startline);
 7988: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 7989: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 7990: 				 'doublebubble',
 7991: 				 $$scan_record{'scantron.doubleerror'},
 7992:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
 7993:     	return (1,$currentphase);
 7994:     }
 7995:     return (0,$currentphase+1);
 7996: }
 7997: 
 7998: 
 7999: sub scantron_get_maxbubble {
 8000:     my ($nav_error,$scantron_config) = @_;
 8001:     if (defined($env{'form.scantron_maxbubble'}) &&
 8002: 	$env{'form.scantron_maxbubble'}) {
 8003: 	&restore_bubble_lines();
 8004: 	return $env{'form.scantron_maxbubble'};
 8005:     }
 8006: 
 8007:     my (undef, undef, $sequence) =
 8008: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8009: 
 8010:     my $navmap=Apache::lonnavmaps::navmap->new();
 8011:     unless (ref($navmap)) {
 8012:         if (ref($nav_error)) {
 8013:             $$nav_error = 1;
 8014:         }
 8015:         return;
 8016:     }
 8017:     my $map=$navmap->getResourceByUrl($sequence);
 8018:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8019:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
 8020: 
 8021:     &Apache::lonxml::clear_problem_counter();
 8022: 
 8023:     my $uname       = $env{'user.name'};
 8024:     my $udom        = $env{'user.domain'};
 8025:     my $cid         = $env{'request.course.id'};
 8026:     my $total_lines = 0;
 8027:     %bubble_lines_per_response = ();
 8028:     %first_bubble_line         = ();
 8029:     %subdivided_bubble_lines   = ();
 8030:     %responsetype_per_response = ();
 8031:     %masterseq_id_responsenum  = ();
 8032: 
 8033:     my $response_number = 0;
 8034:     my $bubble_line     = 0;
 8035:     foreach my $resource (@resources) {
 8036:         my $resid = $resource->id(); 
 8037:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
 8038:                                                           $udom,undef,$bubbles_per_row);
 8039:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 8040: 	    foreach my $part_id (@{$parts}) {
 8041:                 my $lines;
 8042: 
 8043: 	        # TODO - make this a persistent hash not an array.
 8044: 
 8045:                 # optionresponse, matchresponse and rankresponse type items 
 8046:                 # render as separate sub-questions in exam mode.
 8047:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 8048:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 8049:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 8050:                     my ($numbub,$numshown);
 8051:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 8052:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 8053:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 8054:                         }
 8055:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 8056:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 8057:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 8058:                         }
 8059:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 8060:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 8061:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 8062:                         }
 8063:                     }
 8064:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 8065:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 8066:                     }
 8067:                     my $bubbles_per_row =
 8068:                         &bubblesheet_bubbles_per_row($scantron_config);
 8069:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
 8070:                     if (($numbub % $bubbles_per_row) != 0) {
 8071:                         $inner_bubble_lines++;
 8072:                     }
 8073:                     for (my $i=0; $i<$numshown; $i++) {
 8074:                         $subdivided_bubble_lines{$response_number} .= 
 8075:                             $inner_bubble_lines.',';
 8076:                     }
 8077:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 8078:                     $lines = $numshown * $inner_bubble_lines;
 8079:                 } else {
 8080:                     $lines = $analysis->{"$part_id.bubble_lines"};
 8081:                 }
 8082: 
 8083:                 $first_bubble_line{$response_number} = $bubble_line;
 8084: 	        $bubble_lines_per_response{$response_number} = $lines;
 8085:                 $responsetype_per_response{$response_number} = 
 8086:                     $analysis->{$part_id.'.type'};
 8087:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;  
 8088: 	        $response_number++;
 8089: 
 8090: 	        $bubble_line +=  $lines;
 8091: 	        $total_lines +=  $lines;
 8092: 	    }
 8093:         }
 8094:     }
 8095:     &Apache::lonnet::delenv('scantron.');
 8096: 
 8097:     &save_bubble_lines();
 8098:     $env{'form.scantron_maxbubble'} =
 8099: 	$total_lines;
 8100:     return $env{'form.scantron_maxbubble'};
 8101: }
 8102: 
 8103: sub bubblesheet_bubbles_per_row {
 8104:     my ($scantron_config) = @_;
 8105:     my $bubbles_per_row;
 8106:     if (ref($scantron_config) eq 'HASH') {
 8107:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
 8108:     }
 8109:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
 8110:         $bubbles_per_row = 10;
 8111:     }
 8112:     return $bubbles_per_row;
 8113: }
 8114: 
 8115: sub scantron_validate_missingbubbles {
 8116:     my ($r,$currentphase) = @_;
 8117:     #get student info
 8118:     my $classlist=&Apache::loncoursedata::get_classlist();
 8119:     my %idmap=&username_to_idmap($classlist);
 8120:     my (undef,undef,$sequence)=
 8121:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8122: 
 8123:     #get scantron line setup
 8124:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8125:     my ($scanlines,$scan_data)=&scantron_getfile();
 8126: 
 8127:     my $navmap = Apache::lonnavmaps::navmap->new();
 8128:     unless (ref($navmap)) {
 8129:         $r->print(&navmap_errormsg());
 8130:         return(1,$currentphase);
 8131:     }
 8132: 
 8133:     my $map=$navmap->getResourceByUrl($sequence);
 8134:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8135:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8136:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8137:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8138: 
 8139:     my $nav_error;
 8140:     if (ref($map)) {
 8141:         $randomorder = $map->randomorder();
 8142:         $randompick = $map->randompick();
 8143:         if ($randomorder || $randompick) {
 8144:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8145:             if ($nav_error) {
 8146:                 $r->print(&navmap_errormsg());
 8147:                 return(1,$currentphase);
 8148:             }
 8149:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8150:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8151:         }
 8152:     } else {
 8153:         $r->print(&navmap_errormsg());
 8154:         return(1,$currentphase);
 8155:     }
 8156: 
 8157: 
 8158:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 8159:     if ($nav_error) {
 8160:         $r->print(&navmap_errormsg());
 8161:         return(1,$currentphase);
 8162:     }
 8163: 
 8164:     if (!$max_bubble) { $max_bubble=2**31; }
 8165:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8166: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8167: 	if ($line=~/^[\s\cz]*$/) { next; }
 8168: 	my $scan_record =
 8169:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
 8170: 				     $randomorder,$randompick,$sequence,\@master_seq,
 8171:                                      \%symb_to_resource,\%grader_partids_by_symb,
 8172:                                      \%orderedforcode,\%respnumlookup,\%startline);
 8173: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 8174: 	my @to_correct;
 8175: 	
 8176: 	# Probably here's where the error is...
 8177: 
 8178: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 8179:             my $lastbubble;
 8180:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 8181:                my $question = $1;
 8182:                my $subquestion = $2;
 8183:                my ($first,$responsenum);
 8184:                if ($randomorder || $randompick) {
 8185:                    $responsenum = $respnumlookup{$question-1};
 8186:                    $first = $startline{$question-1};
 8187:                } else {
 8188:                    $responsenum = $question-1; 
 8189:                    $first = $first_bubble_line{$responsenum};
 8190:                }
 8191:                if (!defined($first)) { next; }
 8192:                my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8193:                my $subcount = 1;
 8194:                while ($subcount<$subquestion) {
 8195:                    $first += $subans[$subcount-1];
 8196:                    $subcount ++;
 8197:                }
 8198:                my $count = $subans[$subquestion-1];
 8199:                $lastbubble = $first + $count;
 8200:             } else {
 8201:                my ($first,$responsenum);
 8202:                if ($randomorder || $randompick) {
 8203:                    $responsenum = $respnumlookup{$missing-1};
 8204:                    $first = $startline{$missing-1};
 8205:                } else {
 8206:                    $responsenum = $missing-1;
 8207:                    $first = $first_bubble_line{$responsenum};
 8208:                }
 8209:                if (!defined($first)) { next; }
 8210:                $lastbubble = $first + $bubble_lines_per_response{$responsenum};
 8211:             }
 8212:             if ($lastbubble > $max_bubble) { next; }
 8213: 	    push(@to_correct,$missing);
 8214: 	}
 8215: 	if (@to_correct) {
 8216: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 8217: 				     $line,'missingbubble',\@to_correct,
 8218:                                      $randomorder,$randompick,\%respnumlookup,
 8219:                                      \%startline);
 8220: 	    return (1,$currentphase);
 8221: 	}
 8222: 
 8223:     }
 8224:     return (0,$currentphase+1);
 8225: }
 8226: 
 8227: sub hand_bubble_option {
 8228:     my (undef, undef, $sequence) =
 8229:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8230:     return if ($sequence eq '');
 8231:     my $navmap = Apache::lonnavmaps::navmap->new();
 8232:     unless (ref($navmap)) {
 8233:         return;
 8234:     }
 8235:     my $needs_hand_bubbles;
 8236:     my $map=$navmap->getResourceByUrl($sequence);
 8237:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8238:     foreach my $res (@resources) {
 8239:         if (ref($res)) {
 8240:             if ($res->is_problem()) {
 8241:                 my $partlist = $res->parts();
 8242:                 foreach my $part (@{ $partlist }) {
 8243:                     my @types = $res->responseType($part);
 8244:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
 8245:                         $needs_hand_bubbles = 1;
 8246:                         last;
 8247:                     }
 8248:                 }
 8249:             }
 8250:         }
 8251:     }
 8252:     if ($needs_hand_bubbles) {
 8253:         my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8254:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8255:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
 8256:                &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 />').
 8257:                '<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;'.
 8258:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
 8259:     }
 8260:     return;
 8261: }
 8262: 
 8263: sub scantron_process_students {
 8264:     my ($r,$symb) = @_;
 8265: 
 8266:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8267:     if (!$symb) {
 8268: 	return '';
 8269:     }
 8270:     my $default_form_data=&defaultFormData($symb);
 8271: 
 8272:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8273:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config); 
 8274:     my ($scanlines,$scan_data)=&scantron_getfile();
 8275:     my $classlist=&Apache::loncoursedata::get_classlist();
 8276:     my %idmap=&username_to_idmap($classlist);
 8277:     my $navmap=Apache::lonnavmaps::navmap->new();
 8278:     unless (ref($navmap)) {
 8279:         $r->print(&navmap_errormsg());
 8280:         return '';
 8281:     }
 8282:     my $map=$navmap->getResourceByUrl($sequence);
 8283:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8284:         %grader_randomlists_by_symb);
 8285:     if (ref($map)) {
 8286:         $randomorder = $map->randomorder();
 8287:         $randompick = $map->randompick();
 8288:     } else {
 8289:         $r->print(&navmap_errormsg());
 8290:         return '';
 8291:     }
 8292:     my $nav_error;
 8293:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8294:     if ($randomorder || $randompick) {
 8295:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8296:         if ($nav_error) {
 8297:             $r->print(&navmap_errormsg());
 8298:             return '';
 8299:         }
 8300:     }
 8301:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8302:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 8303: 
 8304:     my ($uname,$udom);
 8305:     my $result= <<SCANTRONFORM;
 8306: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 8307:   <input type="hidden" name="command" value="scantron_configphase" />
 8308:   $default_form_data
 8309: SCANTRONFORM
 8310:     $r->print($result);
 8311: 
 8312:     my @delayqueue;
 8313:     my (%completedstudents,%scandata);
 8314:     
 8315:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 8316:     my $count=&get_todo_count($scanlines,$scan_data);
 8317:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 8318:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
 8319:     $r->print('<br />');
 8320:     my $start=&Time::HiRes::time();
 8321:     my $i=-1;
 8322:     my $started;
 8323: 
 8324:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 8325:     if ($nav_error) {
 8326:         $r->print(&navmap_errormsg());
 8327:         return '';
 8328:     }
 8329: 
 8330:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 8331:     # the user and return.
 8332: 
 8333:     if ($ssi_error) {
 8334: 	$r->print("</form>");
 8335: 	&ssi_print_error($r);
 8336:         &Apache::lonnet::remove_lock($lock);
 8337: 	return '';		# Dunno why the other returns return '' rather than just returning.
 8338:     }
 8339: 
 8340:     my %lettdig = &letter_to_digits();
 8341:     my $numletts = scalar(keys(%lettdig));
 8342:     my %orderedforcode;
 8343: 
 8344:     while ($i<$scanlines->{'count'}) {
 8345:  	($uname,$udom)=('','');
 8346:  	$i++;
 8347:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8348:  	if ($line=~/^[\s\cz]*$/) { next; }
 8349: 	if ($started) {
 8350: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 8351: 	}
 8352: 	$started=1;
 8353:         my %respnumlookup = ();
 8354:         my %startline = ();
 8355:         my $total;
 8356:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8357:                                                  $scan_data,undef,\%idmap,$randomorder,
 8358:                                                  $randompick,$sequence,\@master_seq,
 8359:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8360:                                                  \%orderedforcode,\%respnumlookup,\%startline,
 8361:                                                  \$total);
 8362:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 8363:  					      \%idmap,$i)) {
 8364:   	    &scantron_add_delay(\@delayqueue,$line,
 8365:  				'Unable to find a student that matches',1);
 8366:  	    next;
 8367:   	}
 8368:  	if (exists $completedstudents{$uname}) {
 8369:  	    &scantron_add_delay(\@delayqueue,$line,
 8370:  				'Student '.$uname.' has multiple sheets',2);
 8371:  	    next;
 8372:  	}
 8373:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 8374:         my $user = $uname.':'.$usec;
 8375:   	($uname,$udom)=split(/:/,$uname);
 8376: 
 8377:         my $scancode;
 8378:         if ((exists($scan_record->{'scantron.CODE'})) &&
 8379:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 8380:             $scancode = $scan_record->{'scantron.CODE'};
 8381:         } else {
 8382:             $scancode = '';
 8383:         }
 8384: 
 8385:         my @mapresources = @resources;
 8386:         if ($randomorder || $randompick) {
 8387:             @mapresources = 
 8388:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 8389:                              \%orderedforcode);
 8390:         }
 8391:         my (%partids_by_symb,$res_error);
 8392:         foreach my $resource (@mapresources) {
 8393:             my $ressymb;
 8394:             if (ref($resource)) {
 8395:                 $ressymb = $resource->symb();
 8396:             } else {
 8397:                 $res_error = 1;
 8398:                 last;
 8399:             }
 8400:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8401:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8402:                 my ($analysis,$parts) =
 8403:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 8404:                                               $uname,$udom,undef,$bubbles_per_row);
 8405:                 $partids_by_symb{$ressymb} = $parts;
 8406:             } else {
 8407:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 8408:             }
 8409:         }
 8410: 
 8411:         if ($res_error) {
 8412:             &scantron_add_delay(\@delayqueue,$line,
 8413:                                 'An error occurred while grading student '.$uname,2);
 8414:             next;
 8415:         }
 8416: 
 8417: 	&Apache::lonxml::clear_problem_counter();
 8418:   	&Apache::lonnet::appenv($scan_record);
 8419: 
 8420: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 8421: 	    &scantron_putfile($scanlines,$scan_data);
 8422: 	}
 8423: 	
 8424:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8425:                                    \@mapresources,\%partids_by_symb,
 8426:                                    $bubbles_per_row,$randomorder,$randompick,
 8427:                                    \%respnumlookup,\%startline) 
 8428:             eq 'ssi_error') {
 8429:             $ssi_error = 0; # So end of handler error message does not trigger.
 8430:             $r->print("</form>");
 8431:             &ssi_print_error($r);
 8432:             &Apache::lonnet::remove_lock($lock);
 8433:             return '';      # Why return ''?  Beats me.
 8434:         }
 8435: 
 8436:         if (($scancode) && ($randomorder || $randompick)) {
 8437:             my $parmresult =
 8438:                 &Apache::lonparmset::storeparm_by_symb($symb,
 8439:                                                        '0_examcode',2,$scancode,
 8440:                                                        'string_examcode',$uname,
 8441:                                                        $udom);
 8442:         }
 8443: 	$completedstudents{$uname}={'line'=>$line};
 8444:         if ($env{'form.verifyrecord'}) {
 8445:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8446:             if ($randompick) {
 8447:                 if ($total) {
 8448:                     $lastpos = $total*$scantron_config{'Qlength'};
 8449:                 }
 8450:             }
 8451: 
 8452:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8453:             chomp($studentdata);
 8454:             $studentdata =~ s/\r$//;
 8455:             my $studentrecord = '';
 8456:             my $counter = -1;
 8457:             foreach my $resource (@mapresources) {
 8458:                 my $ressymb = $resource->symb();
 8459:                 ($counter,my $recording) =
 8460:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8461:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 8462:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
 8463:                                              $randompick,\%respnumlookup,\%startline);
 8464:                 $studentrecord .= $recording;
 8465:             }
 8466:             if ($studentrecord ne $studentdata) {
 8467:                 &Apache::lonxml::clear_problem_counter();
 8468:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8469:                                            \@mapresources,\%partids_by_symb,
 8470:                                            $bubbles_per_row,$randomorder,$randompick,
 8471:                                            \%respnumlookup,\%startline) 
 8472:                     eq 'ssi_error') {
 8473:                     $ssi_error = 0; # So end of handler error message does not trigger.
 8474:                     $r->print("</form>");
 8475:                     &ssi_print_error($r);
 8476:                     &Apache::lonnet::remove_lock($lock);
 8477:                     delete($completedstudents{$uname});
 8478:                     return '';
 8479:                 }
 8480:                 $counter = -1;
 8481:                 $studentrecord = '';
 8482:                 foreach my $resource (@mapresources) {
 8483:                     my $ressymb = $resource->symb();
 8484:                     ($counter,my $recording) =
 8485:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8486:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 8487:                                                  \%scantron_config,\%lettdig,$numletts,
 8488:                                                  $randomorder,$randompick,\%respnumlookup,
 8489:                                                  \%startline);
 8490:                     $studentrecord .= $recording;
 8491:                 }
 8492:                 if ($studentrecord ne $studentdata) {
 8493:                     $r->print('<p><span class="LC_warning">');
 8494:                     if ($scancode eq '') {
 8495:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
 8496:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 8497:                     } else {
 8498:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
 8499:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 8500:                     }
 8501:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 8502:                               &Apache::loncommon::start_data_table_header_row()."\n".
 8503:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 8504:                               &Apache::loncommon::end_data_table_header_row()."\n".
 8505:                               &Apache::loncommon::start_data_table_row().
 8506:                               '<td>'.&mt('Bubblesheet').'</td>'.
 8507:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
 8508:                               &Apache::loncommon::end_data_table_row().
 8509:                               &Apache::loncommon::start_data_table_row().
 8510:                               '<td>'.&mt('Stored submissions').'</td>'.
 8511:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
 8512:                               &Apache::loncommon::end_data_table_row().
 8513:                               &Apache::loncommon::end_data_table().'</p>');
 8514:                 } else {
 8515:                     $r->print('<br /><span class="LC_warning">'.
 8516:                              &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 />'.
 8517:                              &mt("As a consequence, this user's submission history records two tries.").
 8518:                                  '</span><br />');
 8519:                 }
 8520:             }
 8521:         }
 8522:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 8523:     } continue {
 8524: 	&Apache::lonxml::clear_problem_counter();
 8525: 	&Apache::lonnet::delenv('scantron.');
 8526:     }
 8527:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8528:     &Apache::lonnet::remove_lock($lock);
 8529: #    my $lasttime = &Time::HiRes::time()-$start;
 8530: #    $r->print("<p>took $lasttime</p>");
 8531: 
 8532:     $r->print("</form>");
 8533:     return '';
 8534: }
 8535: 
 8536: sub graders_resources_pass {
 8537:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
 8538:         $bubbles_per_row) = @_;
 8539:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 8540:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 8541:         foreach my $resource (@{$resources}) {
 8542:             my $ressymb = $resource->symb();
 8543:             my ($analysis,$parts) =
 8544:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 8545:                                           $env{'user.name'},$env{'user.domain'},
 8546:                                           1,$bubbles_per_row);
 8547:             $grader_partids_by_symb->{$ressymb} = $parts;
 8548:             if (ref($analysis) eq 'HASH') {
 8549:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 8550:                     $grader_randomlists_by_symb->{$ressymb} =
 8551:                         $analysis->{'parts_withrandomlist'};
 8552:                 }
 8553:             }
 8554:         }
 8555:     }
 8556:     return;
 8557: }
 8558: 
 8559: =pod
 8560: 
 8561: =item users_order
 8562: 
 8563:   Returns array of resources in current map, ordered based on either CODE,
 8564:   if this is a CODEd exam, or based on student's identity if this is a 
 8565:   "NAMEd" exam.
 8566: 
 8567:   Should be used when randomorder and/or randompick applied when the 
 8568:   corresponding exam was printed, prior to students completing bubblesheets 
 8569:   for the version of the exam the student received.
 8570: 
 8571: =cut
 8572: 
 8573: sub users_order  {
 8574:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
 8575:     my @mapresources;
 8576:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
 8577:         return @mapresources;
 8578:     }
 8579:     if ($scancode) {
 8580:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
 8581:             @mapresources = @{$orderedforcode->{$scancode}};
 8582:         } else {
 8583:             $env{'form.CODE'} = $scancode;
 8584:             my $actual_seq =
 8585:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 8586:                                                                $master_seq,
 8587:                                                                $user,$scancode,1);
 8588:             if (ref($actual_seq) eq 'ARRAY') {
 8589:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
 8590:                 if (ref($orderedforcode) eq 'HASH') {
 8591:                     if (@mapresources > 0) { 
 8592:                         $orderedforcode->{$scancode} = \@mapresources;
 8593:                     }
 8594:                 }
 8595:             }
 8596:             delete($env{'form.CODE'});
 8597:         }
 8598:     } else {
 8599:         my $actual_seq =
 8600:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 8601:                                                            $master_seq,
 8602:                                                            $user,undef,1);
 8603:         if (ref($actual_seq) eq 'ARRAY') {
 8604:             @mapresources = 
 8605:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
 8606:         }
 8607:     }
 8608:     return @mapresources;
 8609: }
 8610: 
 8611: sub grade_student_bubbles {
 8612:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
 8613:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
 8614:     my $uselookup = 0;
 8615:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
 8616:         (ref($startline) eq 'HASH')) {
 8617:         $uselookup = 1;
 8618:     }
 8619: 
 8620:     if (ref($resources) eq 'ARRAY') {
 8621:         my $count = 0;
 8622:         foreach my $resource (@{$resources}) {
 8623:             my $ressymb = $resource->symb();
 8624:             my %form = ('submitted'      => 'scantron',
 8625:                         'grade_target'   => 'grade',
 8626:                         'grade_username' => $uname,
 8627:                         'grade_domain'   => $udom,
 8628:                         'grade_courseid' => $env{'request.course.id'},
 8629:                         'grade_symb'     => $ressymb,
 8630:                         'CODE'           => $scancode
 8631:                        );
 8632:             if ($bubbles_per_row ne '') {
 8633:                 $form{'bubbles_per_row'} = $bubbles_per_row;
 8634:             }
 8635:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
 8636:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
 8637:             }
 8638:             if (ref($parts) eq 'HASH') {
 8639:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 8640:                     foreach my $part (@{$parts->{$ressymb}}) {
 8641:                         if ($uselookup) {
 8642:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
 8643:                         } else {
 8644:                             $form{'scantron_questnum_start.'.$part} =
 8645:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
 8646:                         }
 8647:                         $count++;
 8648:                     }
 8649:                 }
 8650:             }
 8651:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 8652:             return 'ssi_error' if ($ssi_error);
 8653:             last if (&Apache::loncommon::connection_aborted($r));
 8654:         }
 8655:     }
 8656:     return;
 8657: }
 8658: 
 8659: sub scantron_upload_scantron_data {
 8660:     my ($r,$symb)=@_;
 8661:     my $dom = $env{'request.role.domain'};
 8662:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 8663:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 8664:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 8665: 							  'domainid',
 8666: 							  'coursename',$dom);
 8667:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 8668:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
 8669:     my $default_form_data=&defaultFormData($symb);
 8670:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 8671:     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.");
 8672:     $r->print(&Apache::lonhtmlcommon::scripttag('
 8673:     function checkUpload(formname) {
 8674: 	if (formname.upfile.value == "") {
 8675: 	    alert("'.$nofile_alert.'");
 8676: 	    return false;
 8677: 	}
 8678:         if (formname.courseid.value == "") {
 8679:             alert("'.$nocourseid_alert.'");
 8680:             return false;
 8681:         }
 8682: 	formname.submit();
 8683:     }
 8684: 
 8685:     function ToSyllabus() {
 8686:         var cdom = '."'$dom'".';
 8687:         var cnum = document.rules.courseid.value;
 8688:         if (cdom == "" || cdom == null) {
 8689:             return;
 8690:         }
 8691:         if (cnum == "" || cnum == null) {
 8692:            return;
 8693:         }
 8694:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 8695:                             "height=350,width=350,scrollbars=yes,menubar=no");
 8696:         return;
 8697:     }
 8698: 
 8699: '));
 8700:     $r->print('
 8701: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
 8702: 
 8703: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 8704: '.$default_form_data.
 8705:   &Apache::lonhtmlcommon::start_pick_box().
 8706:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 8707:   '<input name="courseid" type="text" size="30" />'.$select_link.
 8708:   &Apache::lonhtmlcommon::row_closure().
 8709:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 8710:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 8711:   &Apache::lonhtmlcommon::row_closure().
 8712:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 8713:   '<input name="domainid" type="hidden" />'.$domdesc.
 8714:   &Apache::lonhtmlcommon::row_closure().
 8715:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 8716:   '<input type="file" name="upfile" size="50" />'.
 8717:   &Apache::lonhtmlcommon::row_closure(1).
 8718:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 8719: 
 8720: <input name="command" value="scantronupload_save" type="hidden" />
 8721: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 8722: </form>
 8723: ');
 8724:     return '';
 8725: }
 8726: 
 8727: 
 8728: sub scantron_upload_scantron_data_save {
 8729:     my($r,$symb)=@_;
 8730:     my $doanotherupload=
 8731: 	'<br /><form action="/adm/grades" method="post">'."\n".
 8732: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 8733: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 8734: 	'</form>'."\n";
 8735:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 8736: 	!&Apache::lonnet::allowed('usc',
 8737: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 8738: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 8739: 	unless ($symb) {
 8740: 	    $r->print($doanotherupload);
 8741: 	}
 8742: 	return '';
 8743:     }
 8744:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 8745:     my $uploadedfile;
 8746:     $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
 8747:     if (length($env{'form.upfile'}) < 2) {
 8748:         $r->print(
 8749:             &Apache::lonhtmlcommon::confirm_success(
 8750:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
 8751:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
 8752:     } else {
 8753:         my $result = 
 8754:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
 8755:                                             $env{'form.courseid'},$env{'form.domainid'});
 8756:         if ($result =~ m{^/uploaded/}) {
 8757:             $r->print(
 8758:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
 8759:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
 8760:                         (length($env{'form.upfile'})-1),
 8761:                         '<span class="LC_filename">'.$result.'</span>'));
 8762:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 8763:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 8764:                                                        $env{'form.courseid'},$uploadedfile));
 8765:         } else {
 8766:             $r->print(
 8767:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
 8768:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
 8769:                           $result,
 8770: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 8771: 	}
 8772:     }
 8773:     if ($symb) {
 8774: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
 8775:     } else {
 8776: 	$r->print($doanotherupload);
 8777:     }
 8778:     return '';
 8779: }
 8780: 
 8781: sub validate_uploaded_scantron_file {
 8782:     my ($cdom,$cname,$fname) = @_;
 8783:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 8784:     my @lines;
 8785:     if ($scanlines ne '-1') {
 8786:         @lines=split("\n",$scanlines,-1);
 8787:     }
 8788:     my $output;
 8789:     if (@lines) {
 8790:         my (%counts,$max_match_format);
 8791:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
 8792:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 8793:         my %idmap = &username_to_idmap($classlist);
 8794:         foreach my $key (keys(%idmap)) {
 8795:             my $lckey = lc($key);
 8796:             $idmap{$lckey} = $idmap{$key};
 8797:         }
 8798:         my %unique_formats;
 8799:         my @formatlines = &get_scantronformat_file();
 8800:         foreach my $line (@formatlines) {
 8801:             chomp($line);
 8802:             my @config = split(/:/,$line);
 8803:             my $idstart = $config[5];
 8804:             my $idlength = $config[6];
 8805:             if (($idstart ne '') && ($idlength > 0)) {
 8806:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 8807:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 8808:                 } else {
 8809:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 8810:                 }
 8811:             }
 8812:         }
 8813:         foreach my $key (keys(%unique_formats)) {
 8814:             my ($idstart,$idlength) = split(':',$key);
 8815:             %{$counts{$key}} = (
 8816:                                'found'   => 0,
 8817:                                'total'   => 0,
 8818:                               );
 8819:             foreach my $line (@lines) {
 8820:                 next if ($line =~ /^#/);
 8821:                 next if ($line =~ /^[\s\cz]*$/);
 8822:                 my $id = substr($line,$idstart-1,$idlength);
 8823:                 $id = lc($id);
 8824:                 if (exists($idmap{$id})) {
 8825:                     $counts{$key}{'found'} ++;
 8826:                 }
 8827:                 $counts{$key}{'total'} ++;
 8828:             }
 8829:             if ($counts{$key}{'total'}) {
 8830:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 8831:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 8832:                     $max_match_pct = $percent_match;
 8833:                     $max_match_format = $key;
 8834:                     $found_match_count = $counts{$key}{'found'};
 8835:                     $max_match_count = $counts{$key}{'total'};
 8836:                 }
 8837:             }
 8838:         }
 8839:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 8840:             my $format_descs;
 8841:             my $numwithformat = @{$unique_formats{$max_match_format}};
 8842:             for (my $i=0; $i<$numwithformat; $i++) {
 8843:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 8844:                 if ($i<$numwithformat-2) {
 8845:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 8846:                 } elsif ($i==$numwithformat-2) {
 8847:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 8848:                 } elsif ($i==$numwithformat-1) {
 8849:                     $format_descs .= '"<i>'.$desc.'</i>"';
 8850:                 }
 8851:             }
 8852:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 8853:             $output .= '<br />';
 8854:             if ($found_match_count == $max_match_count) {
 8855:                 # 100% matching entries
 8856:                 $output .= &Apache::lonhtmlcommon::confirm_success(
 8857:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
 8858:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
 8859:                 &mt('Comparison of student IDs in the uploaded file with'.
 8860:                     ' the course roster found matches for [_1] of the [_2] entries'.
 8861:                     ' in the file (for the format defined for [_3]).',
 8862:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
 8863:             } else {
 8864:                 # Not all entries matching? -> Show warning and additional info
 8865:                 $output .=
 8866:                     &Apache::lonhtmlcommon::confirm_success(
 8867:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
 8868:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
 8869:                         &mt('Not all entries could be matched!'),1).'<br />'.
 8870:                     &mt('Comparison of student IDs in the uploaded file with'.
 8871:                         ' the course roster found matches for [_1] of the [_2] entries'.
 8872:                         ' in the file (for the format defined for [_3]).',
 8873:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
 8874:                     '<p class="LC_info">'.
 8875:                     &mt('A low percentage of matches results from one of the following:').
 8876:                     '</p><ul>'.
 8877:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
 8878:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
 8879:                                '<i>'.$cdom.'</i>').'</li>'.
 8880:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 8881:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
 8882:                     '</ul>';
 8883:             }
 8884:         }
 8885:     } else {
 8886:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
 8887:     }
 8888:     return $output;
 8889: }
 8890: 
 8891: sub valid_file {
 8892:     my ($requested_file)=@_;
 8893:     foreach my $filename (sort(&scantron_filenames())) {
 8894: 	if ($requested_file eq $filename) { return 1; }
 8895:     }
 8896:     return 0;
 8897: }
 8898: 
 8899: sub scantron_download_scantron_data {
 8900:     my ($r,$symb)=@_;
 8901:     my $default_form_data=&defaultFormData($symb);
 8902:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8903:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8904:     my $file=$env{'form.scantron_selectfile'};
 8905:     if (! &valid_file($file)) {
 8906: 	$r->print('
 8907: 	<p>
 8908: 	    '.&mt('The requested filename was invalid.').'
 8909:         </p>
 8910: ');
 8911: 	return;
 8912:     }
 8913:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 8914:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 8915:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 8916:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 8917:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 8918:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 8919:     $r->print('
 8920:     <p>
 8921: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
 8922: 	      '<a href="'.$orig.'">','</a>').'
 8923:     </p>
 8924:     <p>
 8925: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 8926: 	      '<a href="'.$corrected.'">','</a>').'
 8927:     </p>
 8928:     <p>
 8929: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 8930: 	      '<a href="'.$skipped.'">','</a>').'
 8931:     </p>
 8932: ');
 8933:     return '';
 8934: }
 8935: 
 8936: sub checkscantron_results {
 8937:     my ($r,$symb) = @_;
 8938:     if (!$symb) {return '';}
 8939:     my $cid = $env{'request.course.id'};
 8940:     my %lettdig = &letter_to_digits();
 8941:     my $numletts = scalar(keys(%lettdig));
 8942:     my $cnum = $env{'course.'.$cid.'.num'};
 8943:     my $cdom = $env{'course.'.$cid.'.domain'};
 8944:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8945:     my %record;
 8946:     my %scantron_config =
 8947:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 8948:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8949:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 8950:     my $classlist=&Apache::loncoursedata::get_classlist();
 8951:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 8952:     my $navmap=Apache::lonnavmaps::navmap->new();
 8953:     unless (ref($navmap)) {
 8954:         $r->print(&navmap_errormsg());
 8955:         return '';
 8956:     }
 8957:     my $map=$navmap->getResourceByUrl($sequence);
 8958:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8959:         %grader_randomlists_by_symb,%orderedforcode);
 8960:     if (ref($map)) { 
 8961:         $randomorder=$map->randomorder();
 8962:         $randompick=$map->randompick();
 8963:     }
 8964:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8965:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8966:     if ($nav_error) {
 8967:         $r->print(&navmap_errormsg());
 8968:         return '';
 8969:     }
 8970:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8971:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 8972:     my ($uname,$udom);
 8973:     my (%scandata,%lastname,%bylast);
 8974:     $r->print('
 8975: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 8976: 
 8977:     my @delayqueue;
 8978:     my %completedstudents;
 8979: 
 8980:     my $count=&get_todo_count($scanlines,$scan_data);
 8981:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 8982:     my ($username,$domain,$started);
 8983:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 8984:     if ($nav_error) {
 8985:         $r->print(&navmap_errormsg());
 8986:         return '';
 8987:     }
 8988: 
 8989:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
 8990:     my $start=&Time::HiRes::time();
 8991:     my $i=-1;
 8992: 
 8993:     while ($i<$scanlines->{'count'}) {
 8994:         ($username,$domain,$uname)=('','','');
 8995:         $i++;
 8996:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 8997:         if ($line=~/^[\s\cz]*$/) { next; }
 8998:         if ($started) {
 8999:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 9000:         }
 9001:         $started=1;
 9002:         my $scan_record=
 9003:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 9004:                                                      $scan_data);
 9005:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
 9006:                                               \%idmap,$i)) {
 9007:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9008:                                 'Unable to find a student that matches',1);
 9009:             next;
 9010:         }
 9011:         if (exists $completedstudents{$uname}) {
 9012:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9013:                                 'Student '.$uname.' has multiple sheets',2);
 9014:             next;
 9015:         }
 9016:         my $pid = $scan_record->{'scantron.ID'};
 9017:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 9018:         push(@{$bylast{$lastname{$pid}}},$pid);
 9019:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 9020:         my $user = $uname.':'.$usec;
 9021:         ($username,$domain)=split(/:/,$uname);
 9022: 
 9023:         my $scancode;
 9024:         if ((exists($scan_record->{'scantron.CODE'})) &&
 9025:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 9026:             $scancode = $scan_record->{'scantron.CODE'};
 9027:         } else {
 9028:             $scancode = '';
 9029:         }
 9030: 
 9031:         my @mapresources = @resources;
 9032:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 9033:         my %respnumlookup=();
 9034:         my %startline=();
 9035:         if ($randomorder || $randompick) {
 9036:             @mapresources =
 9037:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 9038:                              \%orderedforcode);
 9039:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
 9040:                                              $scan_record,\@master_seq,\%symb_to_resource,
 9041:                                              \%grader_partids_by_symb,\%orderedforcode,
 9042:                                              \%respnumlookup,\%startline);
 9043:             if ($randompick && $total) {
 9044:                 $lastpos = $total*$scantron_config{'Qlength'};
 9045:             }
 9046:         }
 9047:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 9048:         chomp($scandata{$pid});
 9049:         $scandata{$pid} =~ s/\r$//;
 9050: 
 9051:         my $counter = -1;
 9052:         foreach my $resource (@mapresources) {
 9053:             my $parts;
 9054:             my $ressymb = $resource->symb();
 9055:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 9056:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 9057:                 (my $analysis,$parts) =
 9058:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 9059:                                               $username,$domain,undef,
 9060:                                               $bubbles_per_row);
 9061:             } else {
 9062:                 $parts = $grader_partids_by_symb{$ressymb};
 9063:             }
 9064:             ($counter,my $recording) =
 9065:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 9066:                                          $scandata{$pid},$parts,
 9067:                                          \%scantron_config,\%lettdig,$numletts,
 9068:                                          $randomorder,$randompick,
 9069:                                          \%respnumlookup,\%startline);
 9070:             $record{$pid} .= $recording;
 9071:         }
 9072:     }
 9073:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 9074:     $r->print('<br />');
 9075:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 9076:     $passed = 0;
 9077:     $failed = 0;
 9078:     $numstudents = 0;
 9079:     foreach my $last (sort(keys(%bylast))) {
 9080:         if (ref($bylast{$last}) eq 'ARRAY') {
 9081:             foreach my $pid (sort(@{$bylast{$last}})) {
 9082:                 my $showscandata = $scandata{$pid};
 9083:                 my $showrecord = $record{$pid};
 9084:                 $showscandata =~ s/\s/&nbsp;/g;
 9085:                 $showrecord =~ s/\s/&nbsp;/g;
 9086:                 if ($scandata{$pid} eq $record{$pid}) {
 9087:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 9088:                     $okstudents .= '<tr class="'.$css_class.'">'.
 9089: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 9090: '</tr>'."\n".
 9091: '<tr class="'.$css_class.'">'."\n".
 9092: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
 9093:                     $passed ++;
 9094:                 } else {
 9095:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 9096:                     $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".
 9097: '</tr>'."\n".
 9098: '<tr class="'.$css_class.'">'."\n".
 9099: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 9100: '</tr>'."\n";
 9101:                     $failed ++;
 9102:                 }
 9103:                 $numstudents ++;
 9104:             }
 9105:         }
 9106:     }
 9107:     $r->print(
 9108:         '<p>'
 9109:        .&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).',
 9110:             '<b>',
 9111:             $numstudents,
 9112:             '</b>',
 9113:             $env{'form.scantron_maxbubble'})
 9114:        .'</p>'
 9115:     );
 9116:     $r->print('<p>'
 9117:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
 9118:              .'<br />'
 9119:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
 9120:              .'</p>'
 9121:     );
 9122:     if ($passed) {
 9123:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 9124:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9125:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9126:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9127:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9128:                  $okstudents."\n".
 9129:                  &Apache::loncommon::end_data_table().'<br />');
 9130:     }
 9131:     if ($failed) {
 9132:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 9133:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9134:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9135:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9136:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9137:                  $badstudents."\n".
 9138:                  &Apache::loncommon::end_data_table()).'<br />'.
 9139:                  &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.');  
 9140:     }
 9141:     $r->print('</form><br />');
 9142:     return;
 9143: }
 9144: 
 9145: sub verify_scantron_grading {
 9146:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 9147:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
 9148:         $respnumlookup,$startline) = @_;
 9149:     my ($record,%expected,%startpos);
 9150:     return ($counter,$record) if (!ref($resource));
 9151:     return ($counter,$record) if (!$resource->is_problem());
 9152:     my $symb = $resource->symb();
 9153:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 9154:     foreach my $part_id (@{$partids}) {
 9155:         $counter ++;
 9156:         $expected{$part_id} = 0;
 9157:         my $respnum = $counter;
 9158:         if ($randomorder || $randompick) {
 9159:             $respnum = $respnumlookup->{$counter};
 9160:             $startpos{$part_id} = $startline->{$counter} + 1;
 9161:         } else {
 9162:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 9163:         }
 9164:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
 9165:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
 9166:             foreach my $item (@sub_lines) {
 9167:                 $expected{$part_id} += $item;
 9168:             }
 9169:         } else {
 9170:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
 9171:         }
 9172:     }
 9173:     if ($symb) {
 9174:         my %recorded;
 9175:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 9176:         if ($returnhash{'version'}) {
 9177:             my %lasthash=();
 9178:             my $version;
 9179:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 9180:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 9181:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 9182:                 }
 9183:             }
 9184:             foreach my $key (keys(%lasthash)) {
 9185:                 if ($key =~ /\.scantron$/) {
 9186:                     my $value = &unescape($lasthash{$key});
 9187:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 9188:                     if ($value eq '') {
 9189:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 9190:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 9191:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9192:                             }
 9193:                         }
 9194:                     } else {
 9195:                         my @tocheck;
 9196:                         my @items = split(//,$value);
 9197:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 9198:                             ($scantron_config->{'Qon'} eq 'number')) {
 9199:                             if (@items < $expected{$part_id}) {
 9200:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 9201:                                 my @singles = split(//,$fragment);
 9202:                                 foreach my $pos (@singles) {
 9203:                                     if ($pos eq ' ') {
 9204:                                         push(@tocheck,$pos);
 9205:                                     } else {
 9206:                                         my $next = shift(@items);
 9207:                                         push(@tocheck,$next);
 9208:                                     }
 9209:                                 }
 9210:                             } else {
 9211:                                 @tocheck = @items;
 9212:                             }
 9213:                             foreach my $letter (@tocheck) {
 9214:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 9215:                                     if ($letter !~ /^[A-J]$/) {
 9216:                                         $letter = $scantron_config->{'Qoff'};
 9217:                                     }
 9218:                                     $recorded{$part_id} .= $letter;
 9219:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 9220:                                     my $digit;
 9221:                                     if ($letter !~ /^[A-J]$/) {
 9222:                                         $digit = $scantron_config->{'Qoff'};
 9223:                                     } else {
 9224:                                         $digit = $lettdig->{$letter};
 9225:                                     }
 9226:                                     $recorded{$part_id} .= $digit;
 9227:                                 }
 9228:                             }
 9229:                         } else {
 9230:                             @tocheck = @items;
 9231:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 9232:                                 my $curr_sub = shift(@tocheck);
 9233:                                 my $digit;
 9234:                                 if ($curr_sub =~ /^[A-J]$/) {
 9235:                                     $digit = $lettdig->{$curr_sub}-1;
 9236:                                 }
 9237:                                 if ($curr_sub eq 'J') {
 9238:                                     $digit += scalar($numletts);
 9239:                                 }
 9240:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9241:                                     if ($j == $digit) {
 9242:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 9243:                                     } else {
 9244:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9245:                                     }
 9246:                                 }
 9247:                             }
 9248:                         }
 9249:                     }
 9250:                 }
 9251:             }
 9252:         }
 9253:         foreach my $part_id (@{$partids}) {
 9254:             if ($recorded{$part_id} eq '') {
 9255:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 9256:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9257:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9258:                     }
 9259:                 }
 9260:             }
 9261:             $record .= $recorded{$part_id};
 9262:         }
 9263:     }
 9264:     return ($counter,$record);
 9265: }
 9266: 
 9267: sub letter_to_digits {
 9268:     my %lettdig = (
 9269:                     A => 1,
 9270:                     B => 2,
 9271:                     C => 3,
 9272:                     D => 4,
 9273:                     E => 5,
 9274:                     F => 6,
 9275:                     G => 7,
 9276:                     H => 8,
 9277:                     I => 9,
 9278:                     J => 0,
 9279:                   );
 9280:     return %lettdig;
 9281: }
 9282: 
 9283: 
 9284: #-------- end of section for handling grading scantron forms -------
 9285: #
 9286: #-------------------------------------------------------------------
 9287: 
 9288: #-------------------------- Menu interface -------------------------
 9289: #
 9290: #--- Href with symb and command ---
 9291: 
 9292: sub href_symb_cmd {
 9293:     my ($symb,$cmd)=@_;
 9294:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
 9295: }
 9296: 
 9297: sub grading_menu {
 9298:     my ($request,$symb) = @_;
 9299:     if (!$symb) {return '';}
 9300: 
 9301:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 9302:                   'command'=>'individual');
 9303:     
 9304:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9305: 
 9306:     $fields{'command'}='ungraded';
 9307:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9308: 
 9309:     $fields{'command'}='table';
 9310:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9311: 
 9312:     $fields{'command'}='all_for_one';
 9313:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9314: 
 9315:     $fields{'command'}='downloadfilesselect';
 9316:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9317: 
 9318:     $fields{'command'} = 'csvform';
 9319:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9320:     
 9321:     $fields{'command'} = 'processclicker';
 9322:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9323:     
 9324:     $fields{'command'} = 'scantron_selectphase';
 9325:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9326: 
 9327:     $fields{'command'} = 'initialverifyreceipt';
 9328:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9329:     
 9330:     my @menu = ({	categorytitle=>'Hand Grading',
 9331:             items =>[
 9332:                         {	linktext => 'Select individual students to grade',
 9333:                     		url => $url1a,
 9334:                     		permission => 'F',
 9335:                     		icon => 'grade_students.png',
 9336:                     		linktitle => 'Grade current resource for a selection of students.'
 9337:                         }, 
 9338:                         {       linktext => 'Grade ungraded submissions.',
 9339:                                 url => $url1b,
 9340:                                 permission => 'F',
 9341:                                 icon => 'ungrade_sub.png',
 9342:                                 linktitle => 'Grade all submissions that have not been graded yet.'
 9343:                         },
 9344: 
 9345:                         {       linktext => 'Grading table',
 9346:                                 url => $url1c,
 9347:                                 permission => 'F',
 9348:                                 icon => 'grading_table.png',
 9349:                                 linktitle => 'Grade current resource for all students.'
 9350:                         },
 9351:                         {       linktext => 'Grade page/folder for one student',
 9352:                                 url => $url1d,
 9353:                                 permission => 'F',
 9354:                                 icon => 'grade_PageFolder.png',
 9355:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
 9356:                         },
 9357:                         {       linktext => 'Download submissions',
 9358:                                 url => $url1e,
 9359:                                 permission => 'F',
 9360:                                 icon => 'download_sub.png',
 9361:                                 linktitle => 'Download all students submissions.'
 9362:                         }]},
 9363:                          { categorytitle=>'Automated Grading',
 9364:                items =>[
 9365: 
 9366:                 	    {	linktext => 'Upload Scores',
 9367:                     		url => $url2,
 9368:                     		permission => 'F',
 9369:                     		icon => 'uploadscores.png',
 9370:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 9371:                 	    },
 9372:                 	    {	linktext => 'Process Clicker',
 9373:                     		url => $url3,
 9374:                     		permission => 'F',
 9375:                     		icon => 'addClickerInfoFile.png',
 9376:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 9377:                 	    },
 9378:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
 9379:                     		url => $url4,
 9380:                     		permission => 'F',
 9381:                     		icon => 'bubblesheet.png',
 9382:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
 9383:                 	    },
 9384:                             {   linktext => 'Verify Receipt Number',
 9385:                                 url => $url5,
 9386:                                 permission => 'F',
 9387:                                 icon => 'receipt_number.png',
 9388:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
 9389:                             }
 9390: 
 9391:                     ]
 9392:             });
 9393: 
 9394:     # Create the menu
 9395:     my $Str;
 9396:     $Str .= '<form method="post" action="" name="gradingMenu">';
 9397:     $Str .= '<input type="hidden" name="command" value="" />'.
 9398:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9399: 
 9400:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
 9401:     return $Str;    
 9402: }
 9403: 
 9404: 
 9405: sub ungraded {
 9406:     my ($request)=@_;
 9407:     &submit_options($request);
 9408: }
 9409: 
 9410: sub submit_options_sequence {
 9411:     my ($request,$symb) = @_;
 9412:     if (!$symb) {return '';}
 9413:     &commonJSfunctions($request);
 9414:     my $result;
 9415: 
 9416:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9417:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9418:     $result.=&selectfield(0).
 9419:             '<input type="hidden" name="command" value="pickStudentPage" />
 9420:             <div>
 9421:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 9422:             </div>
 9423:         </div>
 9424:   </form>';
 9425:     return $result;
 9426: }
 9427: 
 9428: sub submit_options_table {
 9429:     my ($request,$symb) = @_;
 9430:     if (!$symb) {return '';}
 9431:     &commonJSfunctions($request);
 9432:     my $result;
 9433: 
 9434:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9435:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9436: 
 9437:     $result.=&selectfield(0).
 9438:             '<input type="hidden" name="command" value="viewgrades" />
 9439:             <div>
 9440:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 9441:             </div>
 9442:         </div>
 9443:   </form>';
 9444:     return $result;
 9445: }
 9446: 
 9447: sub submit_options_download {
 9448:     my ($request,$symb) = @_;
 9449:     if (!$symb) {return '';}
 9450: 
 9451:     &commonJSfunctions($request);
 9452: 
 9453:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9454:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9455:     $result.='
 9456: <h2>
 9457:   '.&mt('Select Students for Which to Download Submissions').'
 9458: </h2>'.&selectfield(1).'
 9459:                 <input type="hidden" name="command" value="downloadfileslink" /> 
 9460:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 9461:             </div>
 9462:           </div>
 9463: 
 9464: 
 9465:   </form>';
 9466:     return $result;
 9467: }
 9468: 
 9469: #--- Displays the submissions first page -------
 9470: sub submit_options {
 9471:     my ($request,$symb) = @_;
 9472:     if (!$symb) {return '';}
 9473: 
 9474:     &commonJSfunctions($request);
 9475:     my $result;
 9476: 
 9477:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9478: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9479:     $result.=&selectfield(1).'
 9480:                 <input type="hidden" name="command" value="submission" /> 
 9481: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
 9482:             </div>
 9483:           </div>
 9484: 
 9485: 
 9486:   </form>';
 9487:     return $result;
 9488: }
 9489: 
 9490: sub selectfield {
 9491:    my ($full)=@_;
 9492:    my %options = 
 9493:           (&Apache::lonlocal::texthash(
 9494:              'yes'       => 'with submissions',
 9495:              'queued'    => 'in grading queue',
 9496:              'graded'    => 'with ungraded submissions',
 9497:              'incorrect' => 'with incorrect submissions',
 9498:              'all'       => 'with any status'),
 9499:              'select_form_order' => ['yes','queued','graded','incorrect','all']);
 9500:    my $result='<div class="LC_columnSection">
 9501:   
 9502:     <fieldset>
 9503:       <legend>
 9504:        '.&mt('Sections').'
 9505:       </legend>
 9506:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
 9507:     </fieldset>
 9508:   
 9509:     <fieldset>
 9510:       <legend>
 9511:         '.&mt('Groups').'
 9512:       </legend>
 9513:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 9514:     </fieldset>
 9515:   
 9516:     <fieldset>
 9517:       <legend>
 9518:         '.&mt('Access Status').'
 9519:       </legend>
 9520:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
 9521:     </fieldset>';
 9522:     if ($full) {
 9523:        $result.='
 9524:     <fieldset>
 9525:       <legend>
 9526:         '.&mt('Submission Status').'
 9527:       </legend>'.
 9528:        &Apache::loncommon::select_form('all','submitonly',\%options).
 9529:    '</fieldset>';
 9530:     }
 9531:     $result.='</div><br />';
 9532:     return $result;
 9533: }
 9534: 
 9535: sub reset_perm {
 9536:     undef(%perm);
 9537: }
 9538: 
 9539: sub init_perm {
 9540:     &reset_perm();
 9541:     foreach my $test_perm ('vgr','mgr','opa') {
 9542: 
 9543: 	my $scope = $env{'request.course.id'};
 9544: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 9545: 
 9546: 	    $scope .= '/'.$env{'request.course.sec'};
 9547: 	    if ( $perm{$test_perm}=
 9548: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 9549: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 9550: 	    } else {
 9551: 		delete($perm{$test_perm});
 9552: 	    }
 9553: 	}
 9554:     }
 9555: }
 9556: 
 9557: sub init_old_essays {
 9558:     my ($symb,$apath,$adom,$aname) = @_;
 9559:     if ($symb ne '') {
 9560:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 9561:         if (keys(%essays) > 0) {
 9562:             $old_essays{$symb} = \%essays;
 9563:         }
 9564:     }
 9565:     return;
 9566: }
 9567: 
 9568: sub reset_old_essays {
 9569:     undef(%old_essays);
 9570: }
 9571: 
 9572: sub gather_clicker_ids {
 9573:     my %clicker_ids;
 9574: 
 9575:     my $classlist = &Apache::loncoursedata::get_classlist();
 9576: 
 9577:     # Set up a couple variables.
 9578:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 9579:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 9580:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 9581: 
 9582:     foreach my $student (keys(%$classlist)) {
 9583:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 9584:         my $username = $classlist->{$student}->[$username_idx];
 9585:         my $domain   = $classlist->{$student}->[$domain_idx];
 9586:         my $clickers =
 9587: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 9588:         foreach my $id (split(/\,/,$clickers)) {
 9589:             $id=~s/^[\#0]+//;
 9590:             $id=~s/[\-\:]//g;
 9591:             if (exists($clicker_ids{$id})) {
 9592: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 9593:             } else {
 9594: 		$clicker_ids{$id}=$username.':'.$domain;
 9595:             }
 9596:         }
 9597:     }
 9598:     return %clicker_ids;
 9599: }
 9600: 
 9601: sub gather_adv_clicker_ids {
 9602:     my %clicker_ids;
 9603:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 9604:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9605:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 9606:     foreach my $element (sort(keys(%coursepersonnel))) {
 9607:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 9608:             my ($puname,$pudom)=split(/\:/,$person);
 9609:             my $clickers =
 9610: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 9611:             foreach my $id (split(/\,/,$clickers)) {
 9612: 		$id=~s/^[\#0]+//;
 9613:                 $id=~s/[\-\:]//g;
 9614: 		if (exists($clicker_ids{$id})) {
 9615: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 9616: 		} else {
 9617: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 9618: 		}
 9619:             }
 9620:         }
 9621:     }
 9622:     return %clicker_ids;
 9623: }
 9624: 
 9625: sub clicker_grading_parameters {
 9626:     return ('gradingmechanism' => 'scalar',
 9627:             'upfiletype' => 'scalar',
 9628:             'specificid' => 'scalar',
 9629:             'pcorrect' => 'scalar',
 9630:             'pincorrect' => 'scalar');
 9631: }
 9632: 
 9633: sub process_clicker {
 9634:     my ($r,$symb)=@_;
 9635:     if (!$symb) {return '';}
 9636:     my $result=&checkforfile_js();
 9637:     $result.=&Apache::loncommon::start_data_table().
 9638:              &Apache::loncommon::start_data_table_header_row().
 9639:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
 9640:              &Apache::loncommon::end_data_table_header_row().
 9641:              &Apache::loncommon::start_data_table_row()."<td>\n";
 9642: # Attempt to restore parameters from last session, set defaults if not present
 9643:     my %Saveable_Parameters=&clicker_grading_parameters();
 9644:     &Apache::loncommon::restore_course_settings('grades_clicker',
 9645:                                                  \%Saveable_Parameters);
 9646:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 9647:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 9648:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 9649:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 9650: 
 9651:     my %checked;
 9652:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 9653:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 9654:           $checked{$gradingmechanism}=' checked="checked"';
 9655:        }
 9656:     }
 9657: 
 9658:     my $upload=&mt("Evaluate File");
 9659:     my $type=&mt("Type");
 9660:     my $attendance=&mt("Award points just for participation");
 9661:     my $personnel=&mt("Correctness determined from response by course personnel");
 9662:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 9663:     my $given=&mt("Correctness determined from given list of answers").' '.
 9664:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 9665:     my $pcorrect=&mt("Percentage points for correct solution");
 9666:     my $pincorrect=&mt("Percentage points for incorrect solution");
 9667:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 9668: 						   {'iclicker' => 'i>clicker',
 9669:                                                     'interwrite' => 'interwrite PRS',
 9670:                                                     'turning' => 'Turning Technologies'});
 9671:     $symb = &Apache::lonenc::check_encrypt($symb);
 9672:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
 9673: function sanitycheck() {
 9674: // Accept only integer percentages
 9675:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 9676:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 9677: // Find out grading choice
 9678:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 9679:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 9680:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 9681:       }
 9682:    }
 9683: // By default, new choice equals user selection
 9684:    newgradingchoice=gradingchoice;
 9685: // Not good to give more points for false answers than correct ones
 9686:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 9687:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 9688:    }
 9689: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 9690:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 9691:       document.forms.gradesupload.pcorrect.value=100;
 9692:       document.forms.gradesupload.pincorrect.value=100;
 9693:    }
 9694: // If the values are different, cannot be attendance only
 9695:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 9696:        (gradingchoice=='attendance')) {
 9697:        newgradingchoice='personnel';
 9698:    }
 9699: // Change grading choice to new one
 9700:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 9701:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 9702:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 9703:       } else {
 9704:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 9705:       }
 9706:    }
 9707: // Remember the old state
 9708:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 9709: }
 9710: ENDUPFORM
 9711:     $result.= <<ENDUPFORM;
 9712: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 9713: <input type="hidden" name="symb" value="$symb" />
 9714: <input type="hidden" name="command" value="processclickerfile" />
 9715: <input type="file" name="upfile" size="50" />
 9716: <br /><label>$type: $selectform</label>
 9717: ENDUPFORM
 9718:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
 9719:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
 9720:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
 9721: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
 9722: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
 9723: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 9724: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
 9725: <br />&nbsp;&nbsp;&nbsp;
 9726: <input type="text" name="givenanswer" size="50" />
 9727: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 9728: ENDGRADINGFORM
 9729:          $result.='</td>'.&Apache::loncommon::end_data_table_row().
 9730:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
 9731:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
 9732: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
 9733: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 9734: </form>'
 9735: ENDPERCFORM
 9736:     $result.='</td>'.
 9737:              &Apache::loncommon::end_data_table_row().
 9738:              &Apache::loncommon::end_data_table();
 9739:     return $result;
 9740: }
 9741: 
 9742: sub process_clicker_file {
 9743:     my ($r,$symb)=@_;
 9744:     if (!$symb) {return '';}
 9745: 
 9746:     my %Saveable_Parameters=&clicker_grading_parameters();
 9747:     &Apache::loncommon::store_course_settings('grades_clicker',
 9748:                                               \%Saveable_Parameters);
 9749:     my $result='';
 9750:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 9751: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 9752: 	return $result;
 9753:     }
 9754:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 9755:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 9756:         return $result;
 9757:     }
 9758:     my $foundgiven=0;
 9759:     if ($env{'form.gradingmechanism'} eq 'given') {
 9760:         $env{'form.givenanswer'}=~s/^\s*//gs;
 9761:         $env{'form.givenanswer'}=~s/\s*$//gs;
 9762:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
 9763:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 9764:         my @answers=split(/\,/,$env{'form.givenanswer'});
 9765:         $foundgiven=$#answers+1;
 9766:     }
 9767:     my %clicker_ids=&gather_clicker_ids();
 9768:     my %correct_ids;
 9769:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 9770: 	%correct_ids=&gather_adv_clicker_ids();
 9771:     }
 9772:     if ($env{'form.gradingmechanism'} eq 'specific') {
 9773: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 9774: 	   $correct_id=~tr/a-z/A-Z/;
 9775: 	   $correct_id=~s/\s//gs;
 9776: 	   $correct_id=~s/^[\#0]+//;
 9777:            $correct_id=~s/[\-\:]//g;
 9778:            if ($correct_id) {
 9779: 	      $correct_ids{$correct_id}='specified';
 9780:            }
 9781:         }
 9782:     }
 9783:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 9784: 	$result.=&mt('Score based on attendance only');
 9785:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
 9786:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
 9787:     } else {
 9788: 	my $number=0;
 9789: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 9790: 	foreach my $id (sort(keys(%correct_ids))) {
 9791: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 9792: 	    if ($correct_ids{$id} eq 'specified') {
 9793: 		$result.=&mt('specified');
 9794: 	    } else {
 9795: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 9796: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 9797: 	    }
 9798: 	    $number++;
 9799: 	}
 9800:         $result.="</p>\n";
 9801:         if ($number==0) {
 9802:             $result .=
 9803:                  &Apache::lonhtmlcommon::confirm_success(
 9804:                      &mt('No IDs found to determine correct answer'),1);
 9805:             return $result;
 9806:         }
 9807:     }
 9808:     if (length($env{'form.upfile'}) < 2) {
 9809:         $result .=
 9810:             &Apache::lonhtmlcommon::confirm_success(
 9811:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
 9812:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
 9813:         return $result;
 9814:     }
 9815: 
 9816: # Were able to get all the info needed, now analyze the file
 9817: 
 9818:     $result.=&Apache::loncommon::studentbrowser_javascript();
 9819:     $symb = &Apache::lonenc::check_encrypt($symb);
 9820:     $result.=&Apache::loncommon::start_data_table().
 9821:              &Apache::loncommon::start_data_table_header_row().
 9822:              '<th>'.&mt('Evaluate clicker file').'</th>'.
 9823:              &Apache::loncommon::end_data_table_header_row().
 9824:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
 9825: <td>
 9826: <form method="post" action="/adm/grades" name="clickeranalysis">
 9827: <input type="hidden" name="symb" value="$symb" />
 9828: <input type="hidden" name="command" value="assignclickergrades" />
 9829: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 9830: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 9831: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 9832: ENDHEADER
 9833:     if ($env{'form.gradingmechanism'} eq 'given') {
 9834:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
 9835:     } 
 9836:     my %responses;
 9837:     my @questiontitles;
 9838:     my $errormsg='';
 9839:     my $number=0;
 9840:     if ($env{'form.upfiletype'} eq 'iclicker') {
 9841: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 9842:     }
 9843:     if ($env{'form.upfiletype'} eq 'interwrite') {
 9844:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 9845:     }
 9846:     if ($env{'form.upfiletype'} eq 'turning') {
 9847:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
 9848:     }
 9849:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 9850:              '<input type="hidden" name="number" value="'.$number.'" />'.
 9851:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 9852:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 9853:              '<br />';
 9854:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
 9855:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
 9856:        return $result;
 9857:     } 
 9858: # Remember Question Titles
 9859: # FIXME: Possibly need delimiter other than ":"
 9860:     for (my $i=0;$i<$number;$i++) {
 9861:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 9862:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 9863:     }
 9864:     my $correct_count=0;
 9865:     my $student_count=0;
 9866:     my $unknown_count=0;
 9867: # Match answers with usernames
 9868: # FIXME: Possibly need delimiter other than ":"
 9869:     foreach my $id (keys(%responses)) {
 9870:        if ($correct_ids{$id}) {
 9871:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 9872:           $correct_count++;
 9873:        } elsif ($clicker_ids{$id}) {
 9874:           if ($clicker_ids{$id}=~/\,/) {
 9875: # More than one user with the same clicker!
 9876:              $result.="</td>".&Apache::loncommon::end_data_table_row().
 9877:                            &Apache::loncommon::start_data_table_row()."<td>".
 9878:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 9879:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9880:                            "<select name='multi".$id."'>";
 9881:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 9882:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 9883:              }
 9884:              $result.='</select>';
 9885:              $unknown_count++;
 9886:           } else {
 9887: # Good: found one and only one user with the right clicker
 9888:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 9889:              $student_count++;
 9890:           }
 9891:        } else {
 9892:           $result.="</td>".&Apache::loncommon::end_data_table_row().
 9893:                            &Apache::loncommon::start_data_table_row()."<td>".
 9894:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 9895:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9896:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 9897:                    "\n".&mt("Domain").": ".
 9898:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 9899:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
 9900:           $unknown_count++;
 9901:        }
 9902:     }
 9903:     $result.='<hr />'.
 9904:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 9905:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
 9906:        if ($correct_count==0) {
 9907:           $errormsg.="Found no correct answers for grading!";
 9908:        } elsif ($correct_count>1) {
 9909:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 9910:        }
 9911:     }
 9912:     if ($number<1) {
 9913:        $errormsg.="Found no questions.";
 9914:     }
 9915:     if ($errormsg) {
 9916:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 9917:     } else {
 9918:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 9919:     }
 9920:     $result.='</form></td>'.
 9921:              &Apache::loncommon::end_data_table_row().
 9922:              &Apache::loncommon::end_data_table();
 9923:     return $result;
 9924: }
 9925: 
 9926: sub iclicker_eval {
 9927:     my ($questiontitles,$responses)=@_;
 9928:     my $number=0;
 9929:     my $errormsg='';
 9930:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9931:         my %components=&Apache::loncommon::record_sep($line);
 9932:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9933: 	if ($entries[0] eq 'Question') {
 9934: 	    for (my $i=3;$i<$#entries;$i+=6) {
 9935: 		$$questiontitles[$number]=$entries[$i];
 9936: 		$number++;
 9937: 	    }
 9938: 	}
 9939: 	if ($entries[0]=~/^\#/) {
 9940: 	    my $id=$entries[0];
 9941: 	    my @idresponses;
 9942: 	    $id=~s/^[\#0]+//;
 9943: 	    for (my $i=0;$i<$number;$i++) {
 9944: 		my $idx=3+$i*6;
 9945:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
 9946: 		push(@idresponses,$entries[$idx]);
 9947: 	    }
 9948: 	    $$responses{$id}=join(',',@idresponses);
 9949: 	}
 9950:     }
 9951:     return ($errormsg,$number);
 9952: }
 9953: 
 9954: sub interwrite_eval {
 9955:     my ($questiontitles,$responses)=@_;
 9956:     my $number=0;
 9957:     my $errormsg='';
 9958:     my $skipline=1;
 9959:     my $questionnumber=0;
 9960:     my %idresponses=();
 9961:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9962:         my %components=&Apache::loncommon::record_sep($line);
 9963:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9964:         if ($entries[1] eq 'Time') { $skipline=0; next; }
 9965:         if ($entries[1] eq 'Response') { $skipline=1; }
 9966:         next if $skipline;
 9967:         if ($entries[0]!=$questionnumber) {
 9968:            $questionnumber=$entries[0];
 9969:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
 9970:            $number++;
 9971:         }
 9972:         my $id=$entries[4];
 9973:         $id=~s/^[\#0]+//;
 9974:         $id=~s/^v\d*\://i;
 9975:         $id=~s/[\-\:]//g;
 9976:         $idresponses{$id}[$number]=$entries[6];
 9977:     }
 9978:     foreach my $id (keys(%idresponses)) {
 9979:        $$responses{$id}=join(',',@{$idresponses{$id}});
 9980:        $$responses{$id}=~s/^\s*\,//;
 9981:     }
 9982:     return ($errormsg,$number);
 9983: }
 9984: 
 9985: sub turning_eval {
 9986:     my ($questiontitles,$responses)=@_;
 9987:     my $number=0;
 9988:     my $errormsg='';
 9989:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9990:         my %components=&Apache::loncommon::record_sep($line);
 9991:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9992:         if ($#entries>$number) { $number=$#entries; }
 9993:         my $id=$entries[0];
 9994:         my @idresponses;
 9995:         $id=~s/^[\#0]+//;
 9996:         unless ($id) { next; }
 9997:         for (my $idx=1;$idx<=$#entries;$idx++) {
 9998:             $entries[$idx]=~s/\,/\;/g;
 9999:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
10000:             push(@idresponses,$entries[$idx]);
10001:         }
10002:         $$responses{$id}=join(',',@idresponses);
10003:     }
10004:     for (my $i=1; $i<=$number; $i++) {
10005:         $$questiontitles[$i]=&mt('Question [_1]',$i);
10006:     }
10007:     return ($errormsg,$number);
10008: }
10009: 
10010: 
10011: sub assign_clicker_grades {
10012:     my ($r,$symb)=@_;
10013:     if (!$symb) {return '';}
10014: # See which part we are saving to
10015:     my $res_error;
10016:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
10017:     if ($res_error) {
10018:         return &navmap_errormsg();
10019:     }
10020: # FIXME: This should probably look for the first handgradeable part
10021:     my $part=$$partlist[0];
10022: # Start screen output
10023:     my $result=&Apache::loncommon::start_data_table().
10024:              &Apache::loncommon::start_data_table_header_row().
10025:              '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
10026:              &Apache::loncommon::end_data_table_header_row().
10027:              &Apache::loncommon::start_data_table_row().'<td>';
10028: # Get correct result
10029: # FIXME: Possibly need delimiter other than ":"
10030:     my @correct=();
10031:     my $gradingmechanism=$env{'form.gradingmechanism'};
10032:     my $number=$env{'form.number'};
10033:     if ($gradingmechanism ne 'attendance') {
10034:        foreach my $key (keys(%env)) {
10035:           if ($key=~/^form\.correct\:/) {
10036:              my @input=split(/\,/,$env{$key});
10037:              for (my $i=0;$i<=$#input;$i++) {
10038:                  if (($correct[$i]) && ($input[$i]) &&
10039:                      ($correct[$i] ne $input[$i])) {
10040:                     $result.='<br /><span class="LC_warning">'.
10041:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
10042:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
10043:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
10044:                     $correct[$i]=$input[$i];
10045:                  }
10046:              }
10047:           }
10048:        }
10049:        for (my $i=0;$i<$number;$i++) {
10050:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
10051:              $result.='<br /><span class="LC_error">'.
10052:                       &mt('No correct result given for question "[_1]"!',
10053:                           $env{'form.question:'.$i}).'</span>';
10054:           }
10055:        }
10056:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
10057:     }
10058: # Start grading
10059:     my $pcorrect=$env{'form.pcorrect'};
10060:     my $pincorrect=$env{'form.pincorrect'};
10061:     my $storecount=0;
10062:     my %users=();
10063:     foreach my $key (keys(%env)) {
10064:        my $user='';
10065:        if ($key=~/^form\.student\:(.*)$/) {
10066:           $user=$1;
10067:        }
10068:        if ($key=~/^form\.unknown\:(.*)$/) {
10069:           my $id=$1;
10070:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
10071:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
10072:           } elsif ($env{'form.multi'.$id}) {
10073:              $user=$env{'form.multi'.$id};
10074:           }
10075:        }
10076:        if ($user) {
10077:           if ($users{$user}) {
10078:              $result.='<br /><span class="LC_warning">'.
10079:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
10080:                       '</span><br />';
10081:           }
10082:           $users{$user}=1; 
10083:           my @answer=split(/\,/,$env{$key});
10084:           my $sum=0;
10085:           my $realnumber=$number;
10086:           for (my $i=0;$i<$number;$i++) {
10087:              if  ($correct[$i] eq '-') {
10088:                 $realnumber--;
10089:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/))  {
10090:                 if ($gradingmechanism eq 'attendance') {
10091:                    $sum+=$pcorrect;
10092:                 } elsif ($correct[$i] eq '*') {
10093:                    $sum+=$pcorrect;
10094:                 } else {
10095: # We actually grade if correct or not
10096:                    my $increment=$pincorrect;
10097: # Special case: numerical answer "0"
10098:                    if ($correct[$i] eq '0') {
10099:                       if ($answer[$i]=~/^[0\.]+$/) {
10100:                          $increment=$pcorrect;
10101:                       }
10102: # General numerical answer, both evaluate to something non-zero
10103:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
10104:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
10105:                          $increment=$pcorrect;
10106:                       }
10107: # Must be just alphanumeric
10108:                    } elsif ($answer[$i] eq $correct[$i]) {
10109:                       $increment=$pcorrect;
10110:                    }
10111:                    $sum+=$increment;
10112:                 }
10113:              }
10114:           }
10115:           my $ave=$sum/(100*$realnumber);
10116: # Store
10117:           my ($username,$domain)=split(/\:/,$user);
10118:           my %grades=();
10119:           $grades{"resource.$part.solved"}='correct_by_override';
10120:           $grades{"resource.$part.awarded"}=$ave;
10121:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
10122:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
10123:                                                  $env{'request.course.id'},
10124:                                                  $domain,$username);
10125:           if ($returncode ne 'ok') {
10126:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
10127:           } else {
10128:              $storecount++;
10129:           }
10130:        }
10131:     }
10132: # We are done
10133:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
10134:              '</td>'.
10135:              &Apache::loncommon::end_data_table_row().
10136:              &Apache::loncommon::end_data_table();
10137:     return $result;
10138: }
10139: 
10140: sub navmap_errormsg {
10141:     return '<div class="LC_error">'.
10142:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
10143:            &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>').
10144:            '</div>';
10145: }
10146: 
10147: sub startpage {
10148:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js) = @_;
10149:     if ($nomenu) {
10150:         $r->print(&Apache::loncommon::start_page("Student's Version",$js,{'only_body' => '1'}));
10151:     } else {
10152:         unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
10153:         $r->print(&Apache::loncommon::start_page('Grading',$js,
10154:                                                  {'bread_crumbs' => $crumbs}));
10155:         &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
10156:     }
10157:     unless ($nodisplayflag) {
10158:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
10159:     }
10160: }
10161: 
10162: sub select_problem {
10163:     my ($r)=@_;
10164:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
10165:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1));
10166:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
10167:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
10168: }
10169: 
10170: sub handler {
10171:     my $request=$_[0];
10172:     &reset_caches();
10173:     if ($request->header_only) {
10174:         &Apache::loncommon::content_type($request,'text/html');
10175:         $request->send_http_header;
10176:         return OK;
10177:     }
10178:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
10179: 
10180: # see what command we need to execute
10181: 
10182:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
10183:     my $command=$commands[0];
10184: 
10185:     &init_perm();
10186:     if (!$env{'request.course.id'}) {
10187:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
10188:                 ($command =~ /^scantronupload/)) {
10189:             # Not in a course.
10190:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
10191:             return HTTP_NOT_ACCEPTABLE;
10192:         }
10193:     } elsif (!%perm) {
10194:         $request->internal_redirect('/adm/quickgrades');
10195:         return OK;
10196:     }
10197:     &Apache::loncommon::content_type($request,'text/html');
10198:     $request->send_http_header;
10199: 
10200:     if ($#commands > 0) {
10201: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
10202:     }
10203: 
10204: # see what the symb is
10205: 
10206:     my $symb=$env{'form.symb'};
10207:     unless ($symb) {
10208:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
10209:        $symb=&Apache::lonnet::symbread($url);
10210:     }
10211:     &Apache::lonenc::check_decrypt(\$symb);
10212: 
10213:     $ssi_error = 0;
10214:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
10215: #
10216: # Not called from a resource, but inside a course
10217: #    
10218:         &startpage($request,undef,[],1,1);
10219:         &select_problem($request);
10220:     } else {
10221: 	if ($command eq 'submission' && $perm{'vgr'}) {
10222:             my ($stuvcurrent,$stuvdisp,$versionform,$js);
10223:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
10224:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
10225:                     &choose_task_version_form($symb,$env{'form.student'},
10226:                                               $env{'form.userdom'});
10227:             }
10228:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
10229:             if ($versionform) {
10230:                 $request->print($versionform);
10231:             }
10232:             $request->print('<br clear="all" />');
10233: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
10234:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
10235:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
10236:                 &choose_task_version_form($symb,$env{'form.student'},
10237:                                           $env{'form.userdom'},
10238:                                           $env{'form.inhibitmenu'});
10239:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
10240:             if ($versionform) {
10241:                 $request->print($versionform);
10242:             }
10243:             $request->print('<br clear="all" />');
10244:             $request->print(&show_previous_task_version($request,$symb));
10245: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
10246:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10247:                                        {href=>'',text=>'Select student'}],1,1);
10248: 	    &pickStudentPage($request,$symb);
10249: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
10250:             &startpage($request,$symb,
10251:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10252:                                        {href=>'',text=>'Select student'},
10253:                                        {href=>'',text=>'Grade student'}],1,1);
10254: 	    &displayPage($request,$symb);
10255: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
10256:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10257:                                        {href=>'',text=>'Select student'},
10258:                                        {href=>'',text=>'Grade student'},
10259:                                        {href=>'',text=>'Store grades'}],1,1);
10260: 	    &updateGradeByPage($request,$symb);
10261: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
10262:             &startpage($request,$symb,[{href=>'',text=>'...'},
10263:                                        {href=>'',text=>'Modify grades'}]);
10264: 	    &processGroup($request,$symb);
10265: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
10266:             &startpage($request,$symb);
10267: 	    $request->print(&grading_menu($request,$symb));
10268: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
10269:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
10270: 	    $request->print(&submit_options($request,$symb));
10271:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
10272:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
10273:             $request->print(&listStudents($request,$symb,'graded'));
10274:         } elsif ($command eq 'table' && $perm{'vgr'}) {
10275:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
10276:             $request->print(&submit_options_table($request,$symb));
10277:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
10278:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
10279:             $request->print(&submit_options_sequence($request,$symb));
10280: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
10281:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
10282: 	    $request->print(&viewgrades($request,$symb));
10283: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
10284:             &startpage($request,$symb,[{href=>'',text=>'...'},
10285:                                        {href=>'',text=>'Store grades'}]);
10286: 	    $request->print(&processHandGrade($request,$symb));
10287: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
10288:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
10289:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
10290:                                                                              text=>"Modify grades"},
10291:                                        {href=>'', text=>"Store grades"}]);
10292: 	    $request->print(&editgrades($request,$symb));
10293:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
10294:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
10295:             $request->print(&initialverifyreceipt($request,$symb));
10296: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
10297:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
10298:                                        {href=>'',text=>'Verification Result'}]);
10299: 	    $request->print(&verifyreceipt($request,$symb));
10300:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
10301:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
10302:             $request->print(&process_clicker($request,$symb));
10303:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
10304:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
10305:                                        {href=>'', text=>'Process clicker file'}]);
10306:             $request->print(&process_clicker_file($request,$symb));
10307:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
10308:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
10309:                                        {href=>'', text=>'Process clicker file'},
10310:                                        {href=>'', text=>'Store grades'}]);
10311:             $request->print(&assign_clicker_grades($request,$symb));
10312: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
10313:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10314: 	    $request->print(&upcsvScores_form($request,$symb));
10315: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
10316:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10317: 	    $request->print(&csvupload($request,$symb));
10318: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
10319:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10320: 	    $request->print(&csvuploadmap($request,$symb));
10321: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
10322: 	    if ($env{'form.associate'} ne 'Reverse Association') {
10323:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10324: 		$request->print(&csvuploadoptions($request,$symb));
10325: 	    } else {
10326: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
10327: 		    $env{'form.upfile_associate'} = 'reverse';
10328: 		} else {
10329: 		    $env{'form.upfile_associate'} = 'forward';
10330: 		}
10331:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10332: 		$request->print(&csvuploadmap($request,$symb));
10333: 	    }
10334: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
10335:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10336: 	    $request->print(&csvuploadassign($request,$symb));
10337: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
10338:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10339: 	    $request->print(&scantron_selectphase($request,undef,$symb));
10340:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
10341:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10342:  	    $request->print(&scantron_do_warning($request,$symb));
10343: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
10344:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10345: 	    $request->print(&scantron_validate_file($request,$symb));
10346: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
10347:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10348: 	    $request->print(&scantron_process_students($request,$symb));
10349:  	} elsif ($command eq 'scantronupload' && 
10350:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10351: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10352:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10353:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
10354:  	} elsif ($command eq 'scantronupload_save' &&
10355:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10356: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10357:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10358:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
10359:  	} elsif ($command eq 'scantron_download' &&
10360: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
10361:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10362:  	    $request->print(&scantron_download_scantron_data($request,$symb));
10363:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
10364:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10365:             $request->print(&checkscantron_results($request,$symb));
10366:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
10367:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
10368:             $request->print(&submit_options_download($request,$symb));
10369:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
10370:             &startpage($request,$symb,
10371:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
10372:     {href=>'', text=>'Download submissions'}]);
10373:             &submit_download_link($request,$symb);
10374: 	} elsif ($command) {
10375:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
10376: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
10377: 	}
10378:     }
10379:     if ($ssi_error) {
10380: 	&ssi_print_error($request);
10381:     }
10382:     if ($env{'form.inhibitmenu'}) {
10383:         $request->print(&Apache::loncommon::end_page());
10384:     } else {
10385:         &Apache::lonquickgrades::endGradeScreen($request);
10386:     }
10387:     &reset_caches();
10388:     return OK;
10389: }
10390: 
10391: 1;
10392: 
10393: __END__;
10394: 
10395: 
10396: =head1 NAME
10397: 
10398: Apache::grades
10399: 
10400: =head1 SYNOPSIS
10401: 
10402: Handles the viewing of grades.
10403: 
10404: This is part of the LearningOnline Network with CAPA project
10405: described at http://www.lon-capa.org.
10406: 
10407: =head1 OVERVIEW
10408: 
10409: Do an ssi with retries:
10410: While I'd love to factor out this with the version in lonprintout,
10411: 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
10412: I'm not quite ready to invent (e.g. an ssi_with_retry object).
10413: 
10414: At least the logic that drives this has been pulled out into loncommon.
10415: 
10416: 
10417: 
10418: ssi_with_retries - Does the server side include of a resource.
10419:                      if the ssi call returns an error we'll retry it up to
10420:                      the number of times requested by the caller.
10421:                      If we still have a problem, no text is appended to the
10422:                      output and we set some global variables.
10423:                      to indicate to the caller an SSI error occurred.  
10424:                      All of this is supposed to deal with the issues described
10425:                      in LON-CAPA BZ 5631 see:
10426:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
10427:                      by informing the user that this happened.
10428: 
10429: Parameters:
10430:   resource   - The resource to include.  This is passed directly, without
10431:                interpretation to lonnet::ssi.
10432:   form       - The form hash parameters that guide the interpretation of the resource
10433:                
10434:   retries    - Number of retries allowed before giving up completely.
10435: Returns:
10436:   On success, returns the rendered resource identified by the resource parameter.
10437: Side Effects:
10438:   The following global variables can be set:
10439:    ssi_error                - If an unrecoverable error occurred this becomes true.
10440:                               It is up to the caller to initialize this to false
10441:                               if desired.
10442:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
10443:                               of the resource that could not be rendered by the ssi
10444:                               call.
10445:    ssi_error_message   - The error string fetched from the ssi response
10446:                               in the event of an error.
10447: 
10448: 
10449: =head1 HANDLER SUBROUTINE
10450: 
10451: ssi_with_retries()
10452: 
10453: =head1 SUBROUTINES
10454: 
10455: =over
10456: 
10457: =head1 Routines to display previous version of a Task for a specific student
10458: 
10459: Tasks are graded pass/fail. Students who have yet to pass a particular Task
10460: can receive another opportunity. Access to tasks is slot-based. If a slot
10461: requires a proctor to check-in the student, a new version of the Task will
10462: be created when the student is checked in to the new opportunity.
10463: 
10464: If a particular student has tried two or more versions of a particular task,
10465: the submission screen provides a user with vgr privileges (e.g., a Course
10466: Coordinator) the ability to display a previous version worked on by the
10467: student.  By default, the current version is displayed. If a previous version
10468: has been selected for display, submission data are only shown that pertain
10469: to that particular version, and the interface to submit grades is not shown.
10470: 
10471: =over 4
10472: 
10473: =item show_previous_task_version()
10474: 
10475: Displays a specified version of a student's Task, as the student sees it.
10476: 
10477: Inputs: 2
10478:         request - request object
10479:         symb    - unique symb for current instance of resource
10480: 
10481: Output: None.
10482: 
10483: Side Effects: calls &show_problem() to print version of Task, with
10484:               version contained in form item: $env{'form.previousversion'}
10485: 
10486: =item choose_task_version_form()
10487: 
10488: Displays a web form used to select which version of a student's view of a
10489: Task should be displayed.  Either launches a pop-up window, or replaces
10490: content in existing pop-up, or replaces page in main window.
10491: 
10492: Inputs: 4
10493:         symb    - unique symb for current instance of resource
10494:         uname   - username of student
10495:         udom    - domain of student
10496:         nomenu  - 1 if display is in a pop-up window, and hence no menu
10497:                   breadcrumbs etc., are displayed
10498: 
10499: Output: 4
10500:         current   - student's current version
10501:         displayed - student's version being displayed
10502:         result    - scalar containing HTML for web form used to switch to
10503:                     a different version (or a link to close window, if pop-up).
10504:         js        - javascript for processing selection in versions web form
10505: 
10506: Side Effects: None.
10507: 
10508: =item previous_display_javascript()
10509: 
10510: Inputs: 2
10511:         nomenu  - 1 if display is in a pop-up window, and hence no menu
10512:                   breadcrumbs etc., are displayed.
10513:         current - student's current version number.
10514: 
10515: Output: 1
10516:         js      - javascript for processing selection in versions web form.
10517: 
10518: Side Effects: None.
10519: 
10520: =back
10521: 
10522: =head1 Routines to process bubblesheet data.
10523: 
10524: =over 4
10525: 
10526: =item scantron_get_correction() : 
10527: 
10528:    Builds the interface screen to interact with the operator to fix a
10529:    specific error condition in a specific scanline
10530: 
10531:  Arguments:
10532:     $r           - Apache request object
10533:     $i           - number of the current scanline
10534:     $scan_record - hash ref as returned from &scantron_parse_scanline()
10535:     $scan_config - hash ref as returned from &get_scantron_config()
10536:     $line        - full contents of the current scanline
10537:     $error       - error condition, valid values are
10538:                    'incorrectCODE', 'duplicateCODE',
10539:                    'doublebubble', 'missingbubble',
10540:                    'duplicateID', 'incorrectID'
10541:     $arg         - extra information needed
10542:        For errors:
10543:          - duplicateID   - paper number that this studentID was seen before on
10544:          - duplicateCODE - array ref of the paper numbers this CODE was
10545:                            seen on before
10546:          - incorrectCODE - current incorrect CODE 
10547:          - doublebubble  - array ref of the bubble lines that have double
10548:                            bubble errors
10549:          - missingbubble - array ref of the bubble lines that have missing
10550:                            bubble errors
10551: 
10552:    $randomorder - True if exam folder has randomorder set
10553:    $randompick  - True if exam folder has randompick set
10554:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
10555:                      for current line to question number used for same question
10556:                      in "Master Seqence" (as seen by Course Coordinator).
10557:    $startline   - Reference to hash where key is question number (0 is first)
10558:                   and value is number of first bubble line for current student
10559:                   or code-based randompick and/or randomorder.
10560: 
10561: 
10562: 
10563: =item  scantron_get_maxbubble() : 
10564: 
10565:    Arguments:
10566:        $nav_error  - Reference to scalar which is a flag to indicate a
10567:                       failure to retrieve a navmap object.
10568:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
10569:        calling routine should trap the error condition and display the warning
10570:        found in &navmap_errormsg().
10571: 
10572:        $scantron_config - Reference to bubblesheet format configuration hash.
10573: 
10574:    Returns the maximum number of bubble lines that are expected to
10575:    occur. Does this by walking the selected sequence rendering the
10576:    resource and then checking &Apache::lonxml::get_problem_counter()
10577:    for what the current value of the problem counter is.
10578: 
10579:    Caches the results to $env{'form.scantron_maxbubble'},
10580:    $env{'form.scantron.bubble_lines.n'}, 
10581:    $env{'form.scantron.first_bubble_line.n'} and
10582:    $env{"form.scantron.sub_bubblelines.n"}
10583:    which are the total number of bubble lines, the number of bubble
10584:    lines for response n and number of the first bubble line for response n,
10585:    and a comma separated list of numbers of bubble lines for sub-questions
10586:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
10587: 
10588: 
10589: =item  scantron_validate_missingbubbles() : 
10590: 
10591:    Validates all scanlines in the selected file to not have any
10592:     answers that don't have bubbles that have not been verified
10593:     to be bubble free.
10594: 
10595: =item  scantron_process_students() : 
10596: 
10597:    Routine that does the actual grading of the bubblesheet information.
10598: 
10599:    The parsed scanline hash is added to %env 
10600: 
10601:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
10602:    foreach resource , with the form data of
10603: 
10604: 	'submitted'     =>'scantron' 
10605: 	'grade_target'  =>'grade',
10606: 	'grade_username'=> username of student
10607: 	'grade_domain'  => domain of student
10608: 	'grade_courseid'=> of course
10609: 	'grade_symb'    => symb of resource to grade
10610: 
10611:     This triggers a grading pass. The problem grading code takes care
10612:     of converting the bubbled letter information (now in %env) into a
10613:     valid submission.
10614: 
10615: =item  scantron_upload_scantron_data() :
10616: 
10617:     Creates the screen for adding a new bubblesheet data file to a course.
10618: 
10619: =item  scantron_upload_scantron_data_save() : 
10620: 
10621:    Adds a provided bubble information data file to the course if user
10622:    has the correct privileges to do so. 
10623: 
10624: =item  valid_file() :
10625: 
10626:    Validates that the requested bubble data file exists in the course.
10627: 
10628: =item  scantron_download_scantron_data() : 
10629: 
10630:    Shows a list of the three internal files (original, corrected,
10631:    skipped) for a specific bubblesheet data file that exists in the
10632:    course.
10633: 
10634: =item  scantron_validate_ID() : 
10635: 
10636:    Validates all scanlines in the selected file to not have any
10637:    invalid or underspecified student/employee IDs
10638: 
10639: =item navmap_errormsg() :
10640: 
10641:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
10642:    Should be called whenever the request to instantiate a navmap object fails.
10643: 
10644: =back
10645: 
10646: =back
10647: 
10648: =cut

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