File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.728: download - view: text, annotated - select for diffs
Mon Nov 24 02:36:26 2014 UTC (9 years, 5 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6740 Out-of-order recording of submissions (by time).
  - Check for new transactions made immediately before call to lonnet::cstore()
    &Apache::inputtags::hidealldata() called if correct then incorrect,
    where awarded >= 1 when correct (feedback on correctness enabled).
  - Check for transactions made immediately after call to lonnet::cstore()
    if reply from lond::store_handler() is delay:N (where N s the number of
    transactions between the last retrieved in &initialize_storage() and the
    last stored immediately before permanent storage of the current transaction.
    &Apache::grades::makehidden() called if correct then incorrect,
    where awarded >= 1 when correct (feedback on correctness enabled).

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.728 2014/11/24 02:36:26 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(&HTML::Entities::encode($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) = &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:                     $rndseed = $record{"resource.$partid.rndseed"};
 2235:                 }
 2236: 	        if ($env{'form.checkPlag'}) {
 2237:     		    my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2238: 		        &most_similar($uname,$udom,$symb,$subval);
 2239: 		    if ($osim) {
 2240: 			$osim=int($osim*100.0);
 2241: 			my %old_course_desc = 
 2242: 			    &Apache::lonnet::coursedescription($ocrsid,
 2243: 							{'one_time' => 1});
 2244: 
 2245:                         if ($hide eq 'anon') {
 2246:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2247:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2248:                         } else {
 2249: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
 2250: 				&mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2251: 				    $osim,
 2252: 				    &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2253: 				        $old_course_desc{'description'},
 2254: 				        $old_course_desc{'num'},
 2255: 				        $old_course_desc{'domain'}).
 2256: 				    '</span></h3><blockquote><i>'.
 2257: 				    &keywords_highlight($oessay).
 2258: 				    '</i></blockquote><hr />';
 2259:                         }
 2260: 	            }
 2261: 		}
 2262: 		my $order=&get_order($partid,$respid,$symb,$uname,$udom,
 2263:                                      undef,$type,$trial,$rndseed);
 2264:                 if ($env{'form.lastSub'} eq 'lastonly' || $env{'form.lastSub'} eq 'datesub' || $env{'form.lastSub'} =~ /^(last|all)$/ || ($env{'form.lastSub'} eq 'hdgrade' && 
 2265: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2266: 		    my $display_part=&get_display_part($partid,$symb);
 2267:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
 2268:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2269:                         ' <span class="LC_internal_info">'.
 2270:                         '('.&mt('Response ID: [_1]',$respid).')'.
 2271:                         '</span>&nbsp; &nbsp;';
 2272: 		    my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2273:                         
 2274: 		    if (@$files) {
 2275:                         if ($hide eq 'anon') {
 2276:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2277:                         } else {
 2278:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
 2279:                                         .'<br /><span class="LC_warning">';
 2280:                             if(@$files == 1) {
 2281:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
 2282:                             } else {
 2283:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
 2284:                             }
 2285:                             $lastsubonly .= '</span>';                         
 2286:                             foreach my $file (@$files) {
 2287:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2288:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
 2289:                             }
 2290:                         }
 2291: 			$lastsubonly.='<br />';
 2292:                     }
 2293:                     if ($hide eq 'anon') {
 2294:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
 2295:                     } else {
 2296:              	        $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
 2297:                         if ($draft) {
 2298:                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
 2299:                         }
 2300:                         $subval =
 2301: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
 2302: 					 $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
 2303:                         if ($responsetype eq 'essay') {
 2304:                             $subval =~ s{\n}{<br />}g;
 2305:                         }
 2306:                         $lastsubonly.=$subval."\n";
 2307:                     }
 2308: 	            if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2309: 		    $lastsubonly.='</div>';
 2310: 		}
 2311:             }
 2312: 	}
 2313: 	$lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2314:     }
 2315:     $request->print($lastsubonly);
 2316:     if ($env{'form.lastSub'} eq 'datesub') {
 2317:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2318: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2319:   
 2320:     } 
 2321:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2322:         my $identifier = (&canmodify($usec)? $counter : '');
 2323:         $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2324: 								 $env{'request.course.id'},
 2325: 								 $last,'.submission',
 2326: 								 'Apache::grades::keywords_highlight',
 2327:                                                                  $usec,$identifier));
 2328:     }
 2329:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2330: 	.$udom.'" />'."\n");
 2331:     # return if view submission with no grading option
 2332:     if (!&canmodify($usec)) {
 2333: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
 2334: 	return;
 2335:     } else {
 2336: 	$request->print('</div>'."\n");
 2337:     }
 2338: 
 2339:     # essay grading message center
 2340: #    if ($env{'form.handgrade'} eq 'yes') {
 2341:     if (1) {
 2342: 	my $result='<div class="LC_grade_message_center">';
 2343:     
 2344: 	$result.='<div class="LC_grade_message_center_header">'.
 2345: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2346: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2347: 	my $msgfor = $givenn.' '.$lastname;
 2348: 	if (scalar(@$col_fullnames) > 0) {
 2349: 	    my $lastone = pop(@$col_fullnames);
 2350: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2351: 	}
 2352: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2353: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2354: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2355: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2356: 	    ',\''.$msgfor.'\');" target="_self">'.
 2357: 	    &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
 2358: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2359: 	    ' <img src="'.$request->dir_config('lonIconsURL').
 2360: 	    '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
 2361: 	    '<br />&nbsp;('.
 2362: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2363: 	$result.='</div></div>';
 2364: 	$request->print($result);
 2365:     }
 2366: 
 2367:     my %seen = ();
 2368:     my @partlist;
 2369:     my @gradePartRespid;
 2370:     my @part_response_id = &flatten_responseType($responseType);
 2371:     $request->print(
 2372:         '<div class="LC_Box">'
 2373:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2374:     );
 2375:     $request->print(&gradeBox_start());
 2376:     foreach my $part_response_id (@part_response_id) {
 2377:     	my ($partid,$respid) = @{ $part_response_id };
 2378: 	my $part_resp = join('_',@{ $part_response_id });
 2379: 	next if ($seen{$partid} > 0);
 2380: 	$seen{$partid}++;
 2381: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2382: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2383: 	push(@partlist,$partid);
 2384: 	push(@gradePartRespid,$partid.'.'.$respid);
 2385: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2386:     }
 2387:     $request->print(&gradeBox_end()); # </div>
 2388:     $request->print('</div>');
 2389: 
 2390:     $request->print('<div class="LC_grade_info_links">');
 2391:     $request->print('</div>');
 2392: 
 2393:     $result='<input type="hidden" name="partlist'.$counter.
 2394: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2395:     $result.='<input type="hidden" name="gradePartRespid'.
 2396: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2397:     my $ctr = 0;
 2398:     while ($ctr < scalar(@partlist)) {
 2399: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2400: 	    $partlist[$ctr].'" />'."\n";
 2401: 	$ctr++;
 2402:     }
 2403:     $request->print($result.''."\n");
 2404: 
 2405: # Done with printing info for one student
 2406: 
 2407:     $request->print('</div>');#LC_grade_show_user
 2408: 
 2409: 
 2410:     # print end of form
 2411:     if ($counter == $total) {
 2412:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2413: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2414: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2415: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2416: 	my $ntstu ='<select name="NTSTU">'.
 2417: 	    '<option>1</option><option>2</option>'.
 2418: 	    '<option>3</option><option>5</option>'.
 2419: 	    '<option>7</option><option>10</option></select>'."\n";
 2420: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2421: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2422:         $endform.=&mt('[_1]student(s)',$ntstu);
 2423: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2424: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2425: 	    '<input type="button" value="'.&mt('Next').'" '.
 2426: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2427:         $endform.='<span class="LC_warning">'.
 2428:                   &mt('(Next and Previous (student) do not save the scores.)').
 2429:                   '</span>'."\n" ;
 2430:         $endform.="<input type='hidden' value='".&get_increment().
 2431:             "' name='increment' />";
 2432: 	$endform.='</td></tr></table></form>';
 2433: 	$request->print($endform);
 2434:     }
 2435:     return '';
 2436: }
 2437: 
 2438: sub check_collaborators {
 2439:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2440:     my ($result,@col_fullnames);
 2441:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2442:     foreach my $part (keys(%$handgrade)) {
 2443: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2444: 					'.maxcollaborators',
 2445: 					$symb,$udom,$uname);
 2446: 	next if ($ncol <= 0);
 2447: 	$part =~ s/\_/\./g;
 2448: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2449: 	my (@good_collaborators, @bad_collaborators);
 2450: 	foreach my $possible_collaborator
 2451: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2452: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2453: 	    next if ($possible_collaborator eq '');
 2454: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
 2455: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2456: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2457: 	    # Doing this grep allows 'fuzzy' specification
 2458: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2459: 			       keys(%$classlist));
 2460: 	    if (! scalar(@matches)) {
 2461: 		push(@bad_collaborators, $possible_collaborator);
 2462: 	    } else {
 2463: 		push(@good_collaborators, @matches);
 2464: 	    }
 2465: 	}
 2466: 	if (scalar(@good_collaborators) != 0) {
 2467: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
 2468: 	    foreach my $name (@good_collaborators) {
 2469: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2470: 		push(@col_fullnames, $givenn.' '.$lastname);
 2471: 		$result.='<li>'.$fullname->{$name}.'</li>';
 2472: 	    }
 2473: 	    $result.='</ol><br />'."\n";
 2474: 	    my ($part)=split(/\./,$part);
 2475: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2476: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2477: 		"\n";
 2478: 	}
 2479: 	if (scalar(@bad_collaborators) > 0) {
 2480: 	    $result.='<div class="LC_warning">';
 2481: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2482: 	    $result .= '</div>';
 2483: 	}         
 2484: 	if (scalar(@bad_collaborators > $ncol)) {
 2485: 	    $result .= '<div class="LC_warning">';
 2486: 	    $result .= &mt('This student has submitted too many '.
 2487: 		'collaborators.  Maximum is [_1].',$ncol);
 2488: 	    $result .= '</div>';
 2489: 	}
 2490:     }
 2491:     return ($result,$fullname,\@col_fullnames);
 2492: }
 2493: 
 2494: #--- Retrieve the last submission for all the parts
 2495: sub get_last_submission {
 2496:     my ($returnhash)=@_;
 2497:     my (@string,$timestamp,%lasthidden);
 2498:     if ($$returnhash{'version'}) {
 2499: 	my %lasthash=();
 2500: 	my ($version);
 2501: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2502: 	    foreach my $key (sort(split(/\:/,
 2503: 					$$returnhash{$version.':keys'}))) {
 2504: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2505: 		$timestamp = 
 2506: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2507: 	    }
 2508: 	}
 2509:         my (%typeparts,%randombytry);
 2510:         my $showsurv = 
 2511:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2512:         foreach my $key (sort(keys(%lasthash))) {
 2513:             if ($key =~ /\.type$/) {
 2514:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2515:                     ($lasthash{$key} eq 'anonsurveycred') ||
 2516:                     ($lasthash{$key} eq 'randomizetry')) {
 2517:                     my ($ign,@parts) = split(/\./,$key);
 2518:                     pop(@parts);
 2519:                     my $id = join('.',@parts);
 2520:                     if ($lasthash{$key} eq 'randomizetry') {
 2521:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
 2522:                     } else {
 2523:                         unless ($showsurv) {
 2524:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2525:                         }
 2526:                     }
 2527:                     delete($lasthash{$key});
 2528:                 }
 2529:             }
 2530:         }
 2531:         my @hidden = keys(%typeparts);
 2532:         my @randomize = keys(%randombytry);
 2533: 	foreach my $key (keys(%lasthash)) {
 2534: 	    next if ($key !~ /\.submission$/);
 2535:             my $hide;
 2536:             if (@hidden) {
 2537:                 foreach my $id (@hidden) {
 2538:                     if ($key =~ /^\Q$id\E/) {
 2539:                         $hide = 'anon';
 2540:                         last;
 2541:                     }
 2542:                 }
 2543:             }
 2544:             unless ($hide) {
 2545:                 if (@randomize) {
 2546:                     foreach my $id (@hidden) {
 2547:                         if ($key =~ /^\Q$id\E/) {
 2548:                             $hide = 'rand';
 2549:                             last;
 2550:                         }
 2551:                     }
 2552:                 }
 2553:             }
 2554: 	    my ($partid,$foo) = split(/submission$/,$key);
 2555: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
 2556:             push(@string, join(':', $key, $hide, $draft, (
 2557:                 ref($lasthash{$key}) eq 'ARRAY' ?
 2558:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
 2559: 	}
 2560:     }
 2561:     if (!@string) {
 2562: 	$string[0] =
 2563: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2564:     }
 2565:     return (\@string,\$timestamp);
 2566: }
 2567: 
 2568: #--- High light keywords, with style choosen by user.
 2569: sub keywords_highlight {
 2570:     my $string    = shift;
 2571:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2572:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2573:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2574:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2575:     foreach my $keyword (@keylist) {
 2576: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2577:     }
 2578:     return $string;
 2579: }
 2580: 
 2581: # For Tasks provide a mechanism to display previous version for one specific student
 2582: 
 2583: sub show_previous_task_version {
 2584:     my ($request,$symb) = @_;
 2585:     if ($symb eq '') {
 2586:         $request->print(
 2587:             '<span class="LC_error">'.
 2588:             &mt('Unable to handle ambiguous references.').
 2589:             '</span>');
 2590:         return '';
 2591:     }
 2592:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
 2593:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2594:     if (!&canview($usec)) {
 2595:         $request->print(
 2596:             '<span class="LC_warning">'.
 2597:             &mt('Unable to view previous version for requested student.').
 2598:             ' '.&mt('([_1] in section [_2] in course id [_3])',
 2599:                     $uname.':'.$udom,$usec,$env{'request.course.id'}).
 2600:             '</span>');
 2601:         return;
 2602:     }
 2603:     my $mode = 'both';
 2604:     my $isTask = ($symb =~/\.task$/);
 2605:     if ($isTask) {
 2606:         if ($env{'form.previousversion'} =~ /^\d+$/) {
 2607:             if ($env{'form.fullname'} eq '') {
 2608:                 $env{'form.fullname'} =
 2609:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
 2610:             }
 2611:             my $probtitle=&Apache::lonnet::gettitle($symb);
 2612:             $request->print("\n\n".
 2613:                             '<div class="LC_grade_show_user">'.
 2614:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 2615:                             '</h2>'."\n");
 2616:             &Apache::lonxml::clear_problem_counter();
 2617:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
 2618:                             {'previousversion' => $env{'form.previousversion'} }));
 2619:             $request->print("\n</div>");
 2620:         }
 2621:     }
 2622:     return;
 2623: }
 2624: 
 2625: sub choose_task_version_form {
 2626:     my ($symb,$uname,$udom,$nomenu) = @_;
 2627:     my $isTask = ($symb =~/\.task$/);
 2628:     my ($current,$version,$result,$js,$displayed,$rowtitle);
 2629:     if ($isTask) {
 2630:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 2631:                                               $udom,$uname);
 2632:         if (($record{'resource.0.version'} eq '') ||
 2633:             ($record{'resource.0.version'} < 2)) {
 2634:             return ($record{'resource.0.version'},
 2635:                     $record{'resource.0.version'},$result,$js);
 2636:         } else {
 2637:             $current = $record{'resource.0.version'};
 2638:         }
 2639:         if ($env{'form.previousversion'}) {
 2640:             $displayed = $env{'form.previousversion'};
 2641:             $rowtitle = &mt('Choose another version:')
 2642:         } else {
 2643:             $displayed = $current;
 2644:             $rowtitle = &mt('Show earlier version:');
 2645:         }
 2646:         $result = '<div class="LC_left_float">';
 2647:         my $list;
 2648:         my $numversions = 0;
 2649:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
 2650:             if ($i == $current) {
 2651:                 if (!$env{'form.previousversion'} || $nomenu) {
 2652:                     next;
 2653:                 } else {
 2654:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
 2655:                     $numversions ++;
 2656:                 }
 2657:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
 2658:                 unless ($i == $env{'form.previousversion'}) {
 2659:                     $numversions ++;
 2660:                 }
 2661:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
 2662:             }
 2663:         }
 2664:         if ($numversions) {
 2665:             $symb = &HTML::Entities::encode($symb,'<>"&');
 2666:             $result .=
 2667:                 '<form name="getprev" method="post" action=""'.
 2668:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
 2669:                 &Apache::loncommon::start_data_table().
 2670:                 &Apache::loncommon::start_data_table_row().
 2671:                 '<th align="left">'.$rowtitle.'</th>'.
 2672:                 '<td><select name="version">'.
 2673:                 '<option>'.&mt('Select').'</option>'.
 2674:                 $list.
 2675:                 '</select></td>'.
 2676:                 &Apache::loncommon::end_data_table_row();
 2677:             unless ($nomenu) {
 2678:                 $result .= &Apache::loncommon::start_data_table_row().
 2679:                 '<th align="left">'.&mt('Open in new window').'</th>'.
 2680:                 '<td><span class="LC_nobreak">'.
 2681:                 '<label><input type="radio" name="prevwin" value="1" />'.
 2682:                 &mt('Yes').'</label>'.
 2683:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
 2684:                 '</span></td>'.
 2685:                 &Apache::loncommon::end_data_table_row();
 2686:             }
 2687:             $result .=
 2688:                 &Apache::loncommon::start_data_table_row().
 2689:                 '<th align="left">&nbsp;</th>'.
 2690:                 '<td>'.
 2691:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
 2692:                 '</td>'.
 2693:                 &Apache::loncommon::end_data_table_row().
 2694:                 &Apache::loncommon::end_data_table().
 2695:                 '</form>';
 2696:             $js = &previous_display_javascript($nomenu,$current);
 2697:         } elsif ($displayed && $nomenu) {
 2698:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
 2699:         } else {
 2700:             $result .= &mt('No previous versions to show for this student');
 2701:         }
 2702:         $result .= '</div>';
 2703:     }
 2704:     return ($current,$displayed,$result,$js);
 2705: }
 2706: 
 2707: sub previous_display_javascript {
 2708:     my ($nomenu,$current) = @_;
 2709:     my $js = <<"JSONE";
 2710: <script type="text/javascript">
 2711: // <![CDATA[
 2712: function previousVersion(uname,udom,symb) {
 2713:     var current = '$current';
 2714:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
 2715:     var prevstr = new RegExp("^\\\\d+\$");
 2716:     if (!prevstr.test(version)) {
 2717:         return false;
 2718:     }
 2719:     var url = '';
 2720:     if (version == current) {
 2721:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
 2722:     } else {
 2723:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
 2724:     }
 2725: JSONE
 2726:     if ($nomenu) {
 2727:         $js .= <<"JSTWO";
 2728:     document.location.href = url;
 2729: JSTWO
 2730:     } else {
 2731:         $js .= <<"JSTHREE";
 2732:     var newwin = 0;
 2733:     for (var i=0; i<document.getprev.prevwin.length; i++) {
 2734:         if (document.getprev.prevwin[i].checked == true) {
 2735:             newwin = document.getprev.prevwin[i].value;
 2736:         }
 2737:     }
 2738:     if (newwin == 1) {
 2739:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
 2740:         url = url+'&inhibitmenu=yes';
 2741:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
 2742:             previousWin = window.open(url,'',options,1);
 2743:         } else {
 2744:             previousWin.location.href = url;
 2745:         }
 2746:         previousWin.focus();
 2747:         return false;
 2748:     } else {
 2749:         document.location.href = url;
 2750:         return false;
 2751:     }
 2752: JSTHREE
 2753:     }
 2754:     $js .= <<"ENDJS";
 2755:     return false;
 2756: }
 2757: // ]]>
 2758: </script>
 2759: ENDJS
 2760: 
 2761: }
 2762: 
 2763: #--- Called from submission routine
 2764: sub processHandGrade {
 2765:     my ($request,$symb) = @_;
 2766:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2767:     my $button = $env{'form.gradeOpt'};
 2768:     my $ngrade = $env{'form.NCT'};
 2769:     my $ntstu  = $env{'form.NTSTU'};
 2770:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2771:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2772: 
 2773:     if ($button eq 'Save & Next') {
 2774: 	my $ctr = 0;
 2775: 	while ($ctr < $ngrade) {
 2776: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2777: 	    my ($errorflag,$pts,$wgt,$numhidden) = 
 2778:                 &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2779: 	    if ($errorflag eq 'no_score') {
 2780: 		$ctr++;
 2781: 		next;
 2782: 	    }
 2783: 	    if ($errorflag eq 'not_allowed') {
 2784: 		$request->print(
 2785:                     '<span class="LC_error">'
 2786:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
 2787:                    .'</span>');
 2788: 		$ctr++;
 2789: 		next;
 2790: 	    }
 2791:             if ($numhidden) {
 2792:                 $request->print(
 2793:                     '<span class="LC_info">'
 2794:                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
 2795:                    .'</span><br />');
 2796:             }
 2797: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2798: 	    my ($subject,$message,$msgstatus) = ('','','');
 2799: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2800:             my ($feedurl,$showsymb) =
 2801: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2802: 	    my $messagetail;
 2803: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2804: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2805: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2806: 		$subject.=' ['.$restitle.']';
 2807: 		my (@msgnum) = split(/,/,$includemsg);
 2808: 		foreach (@msgnum) {
 2809: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2810: 		}
 2811: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2812: 		if ($env{'form.withgrades'.$ctr}) {
 2813: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2814: 		    $messagetail = " for <a href=\"".
 2815: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
 2816: 		}
 2817: 		$msgstatus = 
 2818:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2819: 						     $message.$messagetail,
 2820:                                                      undef,$feedurl,undef,
 2821:                                                      undef,undef,$showsymb,
 2822:                                                      $restitle);
 2823: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 2824: 				$msgstatus.'<br />');
 2825: 	    }
 2826: 	    if ($env{'form.collaborator'.$ctr}) {
 2827: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2828: 		foreach my $collabstr (@collabstrs) {
 2829: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2830: 		    foreach my $collaborator (@collaborators) {
 2831: 			my ($errorflag,$pts,$wgt) = 
 2832: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2833: 					   $env{'form.unamedom'.$ctr},$part);
 2834: 			if ($errorflag eq 'not_allowed') {
 2835: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2836: 			    next;
 2837: 			} elsif ($message ne '') {
 2838: 			    my ($baseurl,$showsymb) = 
 2839: 				&get_feedurl_and_symb($symb,$collaborator,
 2840: 						      $udom);
 2841: 			    if ($env{'form.withgrades'.$ctr}) {
 2842: 				$messagetail = " for <a href=\"".
 2843:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
 2844: 			    }
 2845: 			    $msgstatus = 
 2846: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2847: 			}
 2848: 		    }
 2849: 		}
 2850: 	    }
 2851: 	    $ctr++;
 2852: 	}
 2853:     }
 2854: 
 2855: #    if ($env{'form.handgrade'} eq 'yes') {
 2856:     if (1) {
 2857: 	# Keywords sorted in alphabatical order
 2858: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2859: 	my %keyhash = ();
 2860: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2861: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2862: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2863: 	$env{'form.keywords'} = join(' ',@keywords);
 2864: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2865: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2866: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2867: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2868: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2869: 
 2870: 	# message center - Order of message gets changed. Blank line is eliminated.
 2871: 	# New messages are saved in env for the next student.
 2872: 	# All messages are saved in nohist_handgrade.db
 2873: 	my ($ctr,$idx) = (1,1);
 2874: 	while ($ctr <= $env{'form.savemsgN'}) {
 2875: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2876: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2877: 		$idx++;
 2878: 	    }
 2879: 	    $ctr++;
 2880: 	}
 2881: 	$ctr = 0;
 2882: 	while ($ctr < $ngrade) {
 2883: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2884: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2885: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2886: 		$idx++;
 2887: 	    }
 2888: 	    $ctr++;
 2889: 	}
 2890: 	$env{'form.savemsgN'} = --$idx;
 2891: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2892: 	my $putresult = &Apache::lonnet::put
 2893: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2894:     }
 2895:     # Called by Save & Refresh from Highlight Attribute Window
 2896:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2897:     if ($env{'form.refresh'} eq 'on') {
 2898: 	my ($ctr,$total) = (0,0);
 2899: 	while ($ctr < $ngrade) {
 2900: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2901: 	    $ctr++;
 2902: 	}
 2903: 	$env{'form.NTSTU'}=$ngrade;
 2904: 	$ctr = 0;
 2905: 	while ($ctr < $total) {
 2906: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2907: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2908: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2909: 	    &submission($request,$ctr,$total-1,$symb);
 2910: 	    $ctr++;
 2911: 	}
 2912: 	return '';
 2913:     }
 2914: 
 2915:     # Get the next/previous one or group of students
 2916:     my $firststu = $env{'form.unamedom0'};
 2917:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2918:     my $ctr = 2;
 2919:     while ($laststu eq '') {
 2920: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2921: 	$ctr++;
 2922: 	$laststu = $firststu if ($ctr > $ngrade);
 2923:     }
 2924: 
 2925:     my (@parsedlist,@nextlist);
 2926:     my ($nextflg) = 0;
 2927:     foreach my $item (sort 
 2928: 	     {
 2929: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2930: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2931: 		 }
 2932: 		 return $a cmp $b;
 2933: 	     } (keys(%$fullname))) {
 2934: # FIXME: this is fishy, looks like the button label
 2935: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2936: 	    push(@parsedlist,$item);
 2937: 	}
 2938: 	$nextflg = 1 if ($item eq $laststu);
 2939: 	if ($button eq 'Previous') {
 2940: 	    last if ($item eq $firststu);
 2941: 	    push(@parsedlist,$item);
 2942: 	}
 2943:     }
 2944:     $ctr = 0;
 2945: # FIXME: this is fishy, looks like the button label
 2946:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2947:     my $res_error;
 2948:     my ($partlist) = &response_type($symb,\$res_error);
 2949:     if ($res_error) {
 2950:         $request->print(&navmap_errormsg());
 2951:         return;
 2952:     }
 2953:     foreach my $student (@parsedlist) {
 2954: 	my $submitonly=$env{'form.submitonly'};
 2955: 	my ($uname,$udom) = split(/:/,$student);
 2956: 	
 2957: 	if ($submitonly eq 'queued') {
 2958: 	    my %queue_status = 
 2959: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2960: 							$udom,$uname);
 2961: 	    next if (!defined($queue_status{'gradingqueue'}));
 2962: 	}
 2963: 
 2964: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2965: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2966: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2967: 	    my $submitted = 0;
 2968: 	    my $ungraded = 0;
 2969: 	    my $incorrect = 0;
 2970: 	    foreach my $item (keys(%status)) {
 2971: 		$submitted = 1 if ($status{$item} ne 'nothing');
 2972: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 2973: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 2974: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 2975: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2976: 		    $submitted = 0;
 2977: 		}
 2978: 	    }
 2979: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2980: 				     $submitonly eq 'incorrect' ||
 2981: 				     $submitonly eq 'graded'));
 2982: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2983: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2984: 	}
 2985: 	push(@nextlist,$student) if ($ctr < $ntstu);
 2986: 	last if ($ctr == $ntstu);
 2987: 	$ctr++;
 2988:     }
 2989: 
 2990:     $ctr = 0;
 2991:     my $total = scalar(@nextlist)-1;
 2992: 
 2993:     foreach (sort(@nextlist)) {
 2994: 	my ($uname,$udom,$submitter) = split(/:/);
 2995: 	$env{'form.student'}  = $uname;
 2996: 	$env{'form.userdom'}  = $udom;
 2997: 	$env{'form.fullname'} = $$fullname{$_};
 2998: 	&submission($request,$ctr,$total,$symb);
 2999: 	$ctr++;
 3000:     }
 3001:     if ($total < 0) {
 3002: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
 3003: 	$request->print($the_end);
 3004:     }
 3005:     return '';
 3006: }
 3007: 
 3008: #---- Save the score and award for each student, if changed
 3009: sub saveHandGrade {
 3010:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 3011:     my @version_parts;
 3012:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 3013: 					   $env{'request.course.id'});
 3014:     if (!&canmodify($usec)) { return('not_allowed'); }
 3015:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 3016:     my @parts_graded;
 3017:     my %newrecord  = ();
 3018:     my ($pts,$wgt,$totchg) = ('','',0);
 3019:     my %aggregate = ();
 3020:     my $aggregateflag = 0;
 3021:     if ($env{'form.HIDE'.$newflg}) {
 3022:         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
 3023:         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
 3024:         $totchg += $numchgs;
 3025:     }
 3026:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 3027:     foreach my $new_part (@parts) {
 3028: 	#collaborator ($submi may vary for different parts
 3029: 	if ($submitter && $new_part ne $part) { next; }
 3030: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 3031: 	if ($dropMenu eq 'excused') {
 3032: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 3033: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 3034: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 3035: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 3036: 		}
 3037: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3038: 	    }
 3039: 	} elsif ($dropMenu eq 'reset status'
 3040: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 3041: 	    foreach my $key (keys(%record)) {
 3042: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 3043: 	    }
 3044: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3045: 		"$env{'user.name'}:$env{'user.domain'}";
 3046:             my $totaltries = $record{'resource.'.$part.'.tries'};
 3047: 
 3048:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 3049: 					       [$new_part]);
 3050:             my $aggtries =$totaltries;
 3051:             if ($last_resets{$new_part}) {
 3052:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 3053: 					   $new_part);
 3054:             }
 3055: 
 3056:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 3057:             if ($aggtries > 0) {
 3058:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3059:                 $aggregateflag = 1;
 3060:             }
 3061: 	} elsif ($dropMenu eq '') {
 3062: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 3063: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 3064: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 3065: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 3066: 		next;
 3067: 	    }
 3068: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 3069: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 3070: 	    my $partial= $pts/$wgt;
 3071: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 3072: 		#do not update score for part if not changed.
 3073:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 3074: 		next;
 3075: 	    } else {
 3076: 	        push(@parts_graded,$new_part);
 3077: 	    }
 3078: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 3079: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 3080: 	    }
 3081: 	    my $reckey = 'resource.'.$new_part.'.solved';
 3082: 	    if ($partial == 0) {
 3083: 		if ($record{$reckey} ne 'incorrect_by_override') {
 3084: 		    $newrecord{$reckey} = 'incorrect_by_override';
 3085: 		}
 3086: 	    } else {
 3087: 		if ($record{$reckey} ne 'correct_by_override') {
 3088: 		    $newrecord{$reckey} = 'correct_by_override';
 3089: 		}
 3090: 	    }	    
 3091: 	    if ($submitter && 
 3092: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 3093: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 3094: 	    }
 3095: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3096: 		"$env{'user.name'}:$env{'user.domain'}";
 3097: 	}
 3098: 	# unless problem has been graded, set flag to version the submitted files
 3099: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 3100: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 3101: 	        $dropMenu eq 'reset status')
 3102: 	   {
 3103: 	    push(@version_parts,$new_part);
 3104: 	}
 3105:     }
 3106:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3107:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3108: 
 3109:     if (%newrecord) {
 3110:         if (@version_parts) {
 3111:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 3112:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 3113: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 3114: 	    foreach my $new_part (@version_parts) {
 3115: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 3116: 				$new_part,\%newrecord);
 3117: 	    }
 3118:         }
 3119: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 3120: 				$env{'request.course.id'},$domain,$stuname);
 3121: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 3122: 				     $cdom,$cnum,$domain,$stuname);
 3123:     }
 3124:     if ($aggregateflag) {
 3125:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3126: 			      $cdom,$cnum);
 3127:     }
 3128:     return ('',$pts,$wgt,$totchg);
 3129: }
 3130: 
 3131: sub makehidden {
 3132:     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
 3133:     return unless (ref($record) eq 'HASH');
 3134:     my %modified;
 3135:     my $numchanged = 0;
 3136:     if (exists($record->{$version.':keys'})) {
 3137:         my $partsregexp = $parts;
 3138:         $partsregexp =~ s/,/|/g;
 3139:         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
 3140:             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
 3141:                  my $item = $1;
 3142:                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
 3143:                      $modified{$key} = $record->{$version.':'.$key};
 3144:                  }
 3145:             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
 3146:                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
 3147:             } elsif ($key =~ /^(ip|timestamp|host)$/) {
 3148:                 $modified{$key} = $record->{$version.':'.$key};
 3149:             }
 3150:         }
 3151:         if (keys(%modified)) {
 3152:             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
 3153:                                           $domain,$stuname,$tolog) eq 'ok') {
 3154:                 $numchanged ++;
 3155:             }
 3156:         }
 3157:     }
 3158:     return $numchanged;
 3159: }
 3160: 
 3161: sub check_and_remove_from_queue {
 3162:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 3163:     my @ungraded_parts;
 3164:     foreach my $part (@{$parts}) {
 3165: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 3166: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 3167: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 3168: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 3169: 		) {
 3170: 	    push(@ungraded_parts, $part);
 3171: 	}
 3172:     }
 3173:     if ( !@ungraded_parts ) {
 3174: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 3175: 					       $cnum,$domain,$stuname);
 3176:     }
 3177: }
 3178: 
 3179: sub handback_files {
 3180:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 3181:     my $portfolio_root = '/userfiles/portfolio';
 3182:     my $res_error;
 3183:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3184:     if ($res_error) {
 3185:         $request->print('<br />'.&navmap_errormsg().'<br />');
 3186:         return;
 3187:     }
 3188:     my @handedback;
 3189:     my $file_msg;
 3190:     my @part_response_id = &flatten_responseType($responseType);
 3191:     foreach my $part_response_id (@part_response_id) {
 3192:     	my ($part_id,$resp_id) = @{ $part_response_id };
 3193: 	my $part_resp = join('_',@{ $part_response_id });
 3194:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
 3195:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
 3196:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
 3197:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
 3198:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
 3199:                     my ($directory,$answer_file) = 
 3200:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
 3201:                     my ($answer_name,$answer_ver,$answer_ext) =
 3202: 		        &file_name_version_ext($answer_file);
 3203: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 3204:                     my $getpropath = 1;
 3205:                     my ($dir_list,$listerror) = 
 3206:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
 3207:                                                  $domain,$stuname,$getpropath);
 3208: 		    my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 3209:                     # fix filename
 3210:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 3211:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 3212:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
 3213:             	                                $save_file_name);
 3214:                     if ($result !~ m|^/uploaded/|) {
 3215:                         $request->print('<br /><span class="LC_error">'.
 3216:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 3217:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
 3218:                                         '</span>');
 3219:                     } else {
 3220:                         # mark the file as read only
 3221:                         push(@handedback,$save_file_name);
 3222: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 3223: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 3224: 			}
 3225:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 3226: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
 3227:                     }
 3228:                     $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>'));
 3229:                 }
 3230:             }
 3231:         }
 3232:     }
 3233:     if (@handedback > 0) {
 3234:         $request->print('<br />');
 3235:         my @what = ($symb,$env{'request.course.id'},'handback');
 3236:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
 3237:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
 3238:         my ($subject,$message);
 3239:         if (scalar(@handedback) == 1) {
 3240:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
 3241:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
 3242:         } else {
 3243:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
 3244:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
 3245:         }
 3246:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
 3247:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
 3248:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
 3249:         my ($feedurl,$showsymb) =
 3250:             &get_feedurl_and_symb($symb,$domain,$stuname);
 3251:         my $restitle = &Apache::lonnet::gettitle($symb);
 3252:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
 3253:         my $msgstatus =
 3254:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
 3255:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
 3256:                  $restitle);
 3257:         if ($msgstatus) {
 3258:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
 3259:         }
 3260:     }
 3261:     return;
 3262: }
 3263: 
 3264: sub get_feedurl_and_symb {
 3265:     my ($symb,$uname,$udom) = @_;
 3266:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3267:     $url = &Apache::lonnet::clutter($url);
 3268:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 3269: 					$symb,$udom,$uname);
 3270:     if ($encrypturl =~ /^yes$/i) {
 3271: 	&Apache::lonenc::encrypted(\$url,1);
 3272: 	&Apache::lonenc::encrypted(\$symb,1);
 3273:     }
 3274:     return ($url,$symb);
 3275: }
 3276: 
 3277: sub get_submitted_files {
 3278:     my ($udom,$uname,$partid,$respid,$record) = @_;
 3279:     my @files;
 3280:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 3281:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 3282:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 3283:     	    push(@files,$file_url.$file);
 3284:         }
 3285:     }
 3286:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 3287:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 3288:     }
 3289:     return (\@files);
 3290: }
 3291: 
 3292: # ----------- Provides number of tries since last reset.
 3293: sub get_num_tries {
 3294:     my ($record,$last_reset,$part) = @_;
 3295:     my $timestamp = '';
 3296:     my $num_tries = 0;
 3297:     if ($$record{'version'}) {
 3298:         for (my $version=$$record{'version'};$version>=1;$version--) {
 3299:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 3300:                 $timestamp = $$record{$version.':timestamp'};
 3301:                 if ($timestamp > $last_reset) {
 3302:                     $num_tries ++;
 3303:                 } else {
 3304:                     last;
 3305:                 }
 3306:             }
 3307:         }
 3308:     }
 3309:     return $num_tries;
 3310: }
 3311: 
 3312: # ----------- Determine decrements required in aggregate totals 
 3313: sub decrement_aggs {
 3314:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 3315:     my %decrement = (
 3316:                         attempts => 0,
 3317:                         users => 0,
 3318:                         correct => 0
 3319:                     );
 3320:     $decrement{'attempts'} = $aggtries;
 3321:     if ($solvedstatus =~ /^correct/) {
 3322:         $decrement{'correct'} = 1;
 3323:     }
 3324:     if ($aggtries == $totaltries) {
 3325:         $decrement{'users'} = 1;
 3326:     }
 3327:     foreach my $type (keys(%decrement)) {
 3328:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 3329:     }
 3330:     return;
 3331: }
 3332: 
 3333: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3334: sub get_last_resets {
 3335:     my ($symb,$courseid,$partids) =@_;
 3336:     my %last_resets;
 3337:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3338:     my $cname = $env{'course.'.$courseid.'.num'};
 3339:     my @keys;
 3340:     foreach my $part (@{$partids}) {
 3341: 	push(@keys,"$symb\0$part\0resettime");
 3342:     }
 3343:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3344: 				     $cdom,$cname);
 3345:     foreach my $part (@{$partids}) {
 3346: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3347:     }
 3348:     return %last_resets;
 3349: }
 3350: 
 3351: # ----------- Handles creating versions for portfolio files as answers
 3352: sub version_portfiles {
 3353:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3354:     my $version_parts = join('|',@$v_flag);
 3355:     my @returned_keys;
 3356:     my $parts = join('|', @$parts_graded);
 3357:     my $portfolio_root = '/userfiles/portfolio';
 3358:     foreach my $key (keys(%$record)) {
 3359:         my $new_portfiles;
 3360:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3361:             my @versioned_portfiles;
 3362:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3363:             foreach my $file (@portfiles) {
 3364:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 3365:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 3366: 		my ($answer_name,$answer_ver,$answer_ext) =
 3367: 		    &file_name_version_ext($answer_file);
 3368:                 my $getpropath = 1;    
 3369:                 my ($dir_list,$listerror) = 
 3370:                     &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
 3371:                                              $stu_name,$getpropath);
 3372:                 my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 3373:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 3374:                 if ($new_answer ne 'problem getting file') {
 3375:                     push(@versioned_portfiles, $directory.$new_answer);
 3376:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 3377:                         [$directory.$new_answer],
 3378:                         [$symb,$env{'request.course.id'},'graded']);
 3379:                 }
 3380:             }
 3381:             $$record{$key} = join(',',@versioned_portfiles);
 3382:             push(@returned_keys,$key);
 3383:         }
 3384:     } 
 3385:     return (@returned_keys);   
 3386: }
 3387: 
 3388: sub get_next_version {
 3389:     my ($answer_name, $answer_ext, $dir_list) = @_;
 3390:     my $version;
 3391:     if (ref($dir_list) eq 'ARRAY') {
 3392:         foreach my $row (@{$dir_list}) {
 3393:             my ($file) = split(/\&/,$row,2);
 3394:             my ($file_name,$file_version,$file_ext) =
 3395: 	        &file_name_version_ext($file);
 3396:             if (($file_name eq $answer_name) && 
 3397: 	        ($file_ext eq $answer_ext)) {
 3398:                      # gets here if filename and extension match, 
 3399:                      # regardless of version
 3400:                 if ($file_version ne '') {
 3401:                     # a versioned file is found  so save it for later
 3402:                     if ($file_version > $version) {
 3403: 		        $version = $file_version;
 3404: 	            }
 3405:                 }
 3406:             }
 3407:         }
 3408:     }
 3409:     $version ++;
 3410:     return($version);
 3411: }
 3412: 
 3413: sub version_selected_portfile {
 3414:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3415:     my ($answer_name,$answer_ver,$answer_ext) =
 3416:         &file_name_version_ext($file_name);
 3417:     my $new_answer;
 3418:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3419:     if($env{'form.copy'} eq '-1') {
 3420:         $new_answer = 'problem getting file';
 3421:     } else {
 3422:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3423:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3424:                             $stu_name,$domain,'copy',
 3425: 		        '/portfolio'.$directory.$new_answer);
 3426:     }    
 3427:     return ($new_answer);
 3428: }
 3429: 
 3430: sub file_name_version_ext {
 3431:     my ($file)=@_;
 3432:     my @file_parts = split(/\./, $file);
 3433:     my ($name,$version,$ext);
 3434:     if (@file_parts > 1) {
 3435: 	$ext=pop(@file_parts);
 3436: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3437: 	    $version=pop(@file_parts);
 3438: 	}
 3439: 	$name=join('.',@file_parts);
 3440:     } else {
 3441: 	$name=join('.',@file_parts);
 3442:     }
 3443:     return($name,$version,$ext);
 3444: }
 3445: 
 3446: #--------------------------------------------------------------------------------------
 3447: #
 3448: #-------------------------- Next few routines handles grading by section or whole class
 3449: #
 3450: #--- Javascript to handle grading by section or whole class
 3451: sub viewgrades_js {
 3452:     my ($request) = shift;
 3453: 
 3454:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3455:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
 3456:    function writePoint(partid,weight,point) {
 3457: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3458: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3459: 	if (point == "textval") {
 3460: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3461: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3462: 		alert("$alertmsg"+parseFloat(point));
 3463: 		var resetbox = false;
 3464: 		for (var i=0; i<radioButton.length; i++) {
 3465: 		    if (radioButton[i].checked) {
 3466: 			textbox.value = i;
 3467: 			resetbox = true;
 3468: 		    }
 3469: 		}
 3470: 		if (!resetbox) {
 3471: 		    textbox.value = "";
 3472: 		}
 3473: 		return;
 3474: 	    }
 3475: 	    if (parseFloat(point) > parseFloat(weight)) {
 3476: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3477: 				   ") greater than the weight for the part. Accept?");
 3478: 		if (resp == false) {
 3479: 		    textbox.value = "";
 3480: 		    return;
 3481: 		}
 3482: 	    }
 3483: 	    for (var i=0; i<radioButton.length; i++) {
 3484: 		radioButton[i].checked=false;
 3485: 		if (parseFloat(point) == i) {
 3486: 		    radioButton[i].checked=true;
 3487: 		}
 3488: 	    }
 3489: 
 3490: 	} else {
 3491: 	    textbox.value = parseFloat(point);
 3492: 	}
 3493: 	for (i=0;i<document.classgrade.total.value;i++) {
 3494: 	    var user = document.classgrade["ctr"+i].value;
 3495: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3496: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3497: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3498: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3499: 	    if (saveval != "correct") {
 3500: 		scorename.value = point;
 3501: 		if (selname[0].selected != true) {
 3502: 		    selname[0].selected = true;
 3503: 		}
 3504: 	    }
 3505: 	}
 3506: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3507:     }
 3508: 
 3509:     function writeRadText(partid,weight) {
 3510: 	var selval   = document.classgrade["SELVAL_"+partid];
 3511: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3512:         var override = document.classgrade["FORCE_"+partid].checked;
 3513: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3514: 	if (selval[1].selected || selval[2].selected) {
 3515: 	    for (var i=0; i<radioButton.length; i++) {
 3516: 		radioButton[i].checked=false;
 3517: 
 3518: 	    }
 3519: 	    textbox.value = "";
 3520: 
 3521: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3522: 		var user = document.classgrade["ctr"+i].value;
 3523: 		user = user.replace(new RegExp(':', 'g'),"_");
 3524: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3525: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3526: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3527: 		if ((saveval != "correct") || override) {
 3528: 		    scorename.value = "";
 3529: 		    if (selval[1].selected) {
 3530: 			selname[1].selected = true;
 3531: 		    } else {
 3532: 			selname[2].selected = true;
 3533: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3534: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3535: 		    }
 3536: 		}
 3537: 	    }
 3538: 	} else {
 3539: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3540: 		var user = document.classgrade["ctr"+i].value;
 3541: 		user = user.replace(new RegExp(':', 'g'),"_");
 3542: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3543: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3544: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3545: 		if ((saveval != "correct") || override) {
 3546: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3547: 		    selname[0].selected = true;
 3548: 		}
 3549: 	    }
 3550: 	}	    
 3551:     }
 3552: 
 3553:     function changeSelect(partid,user) {
 3554: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3555: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3556: 	var point  = textbox.value;
 3557: 	var weight = document.classgrade["weight_"+partid].value;
 3558: 
 3559: 	if (isNaN(point) || parseFloat(point) < 0) {
 3560: 	    alert("$alertmsg"+parseFloat(point));
 3561: 	    textbox.value = "";
 3562: 	    return;
 3563: 	}
 3564: 	if (parseFloat(point) > parseFloat(weight)) {
 3565: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3566: 			       ") greater than the weight of the part. Accept?");
 3567: 	    if (resp == false) {
 3568: 		textbox.value = "";
 3569: 		return;
 3570: 	    }
 3571: 	}
 3572: 	selval[0].selected = true;
 3573:     }
 3574: 
 3575:     function changeOneScore(partid,user) {
 3576: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3577: 	if (selval[1].selected || selval[2].selected) {
 3578: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3579: 	    if (selval[2].selected) {
 3580: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3581: 	    }
 3582:         }
 3583:     }
 3584: 
 3585:     function resetEntry(numpart) {
 3586: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3587: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3588: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3589: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3590: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3591: 	    for (var i=0; i<radioButton.length; i++) {
 3592: 		radioButton[i].checked=false;
 3593: 
 3594: 	    }
 3595: 	    textbox.value = "";
 3596: 	    selval[0].selected = true;
 3597: 
 3598: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3599: 		var user = document.classgrade["ctr"+i].value;
 3600: 		user = user.replace(new RegExp(':', 'g'),"_");
 3601: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3602: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3603: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3604: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3605: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3606: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3607: 		if (saveselval == "excused") {
 3608: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3609: 		} else {
 3610: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3611: 		}
 3612: 	    }
 3613: 	}
 3614:     }
 3615: 
 3616: VIEWJAVASCRIPT
 3617: }
 3618: 
 3619: #--- show scores for a section or whole class w/ option to change/update a score
 3620: sub viewgrades {
 3621:     my ($request,$symb) = @_;
 3622:     &viewgrades_js($request);
 3623: 
 3624:     #need to make sure we have the correct data for later EXT calls, 
 3625:     #thus invalidate the cache
 3626:     &Apache::lonnet::devalidatecourseresdata(
 3627:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3628:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3629:     &Apache::lonnet::clear_EXT_cache_status();
 3630: 
 3631:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3632: 
 3633:     #view individual student submission form - called using Javascript viewOneStudent
 3634:     $result.=&jscriptNform($symb);
 3635: 
 3636:     #beginning of class grading form
 3637:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3638:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3639: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3640: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3641: 	&build_section_inputs().
 3642: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3643: 
 3644:     my ($common_header,$specific_header);
 3645:     if ($env{'form.section'} eq 'all') {
 3646: 	$common_header = &mt('Assign Common Grade to Class');
 3647:         $specific_header = &mt('Assign Grade to Specific Students in Class');
 3648:     } elsif ($env{'form.section'} eq 'none') {
 3649:         $common_header = &mt('Assign Common Grade to Students in no Section');
 3650: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
 3651:     } else {
 3652:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3653:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3654: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3655:     }
 3656:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
 3657:     #radio buttons/text box for assigning points for a section or class.
 3658:     #handles different parts of a problem
 3659:     my $res_error;
 3660:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3661:     if ($res_error) {
 3662:         return &navmap_errormsg();
 3663:     }
 3664:     my %weight = ();
 3665:     my $ctsparts = 0;
 3666:     my %seen = ();
 3667:     my @part_response_id = &flatten_responseType($responseType);
 3668:     foreach my $part_response_id (@part_response_id) {
 3669:     	my ($partid,$respid) = @{ $part_response_id };
 3670: 	my $part_resp = join('_',@{ $part_response_id });
 3671: 	next if $seen{$partid};
 3672: 	$seen{$partid}++;
 3673: 	my $handgrade=$$handgrade{$part_resp};
 3674: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3675: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3676: 
 3677: 	my $display_part=&get_display_part($partid,$symb);
 3678: 	my $radio.='<table border="0"><tr>';  
 3679: 	my $ctr = 0;
 3680: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3681: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3682: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3683: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3684: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3685: 	    $ctr++;
 3686: 	}
 3687: 	$radio.='</tr></table>';
 3688: 	my $line = '<input type="text" name="TEXTVAL_'.
 3689: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 3690: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3691: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3692:         $line.= '<td><b>'.&mt('Grade Status').':</b>'.
 3693:             '<select name="SELVAL_'.$partid.'" '.
 3694:             'onchange="javascript:writeRadText(\''.$partid.'\','.
 3695:                 $weight{$partid}.')"> '.
 3696: 	    '<option selected="selected"> </option>'.
 3697: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3698: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3699: 	    '</select></td>'.
 3700:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3701: 	$line.='<input type="hidden" name="partid_'.
 3702: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3703: 	$line.='<input type="hidden" name="weight_'.
 3704: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3705: 
 3706: 	$result.=
 3707: 	    &Apache::loncommon::start_data_table_row()."\n".
 3708: 	    '<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>'.
 3709: 	    &Apache::loncommon::end_data_table_row()."\n";
 3710: 	$ctsparts++;
 3711:     }
 3712:     $result.=&Apache::loncommon::end_data_table()."\n".
 3713: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3714:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3715: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 3716: 
 3717:     #table listing all the students in a section/class
 3718:     #header of table
 3719:     $result.= '<h3>'.$specific_header.'</h3>'.
 3720:               &Apache::loncommon::start_data_table().
 3721: 	      &Apache::loncommon::start_data_table_header_row().
 3722: 	      '<th>'.&mt('No.').'</th>'.
 3723: 	      '<th>'.&nameUserString('header')."</th>\n";
 3724:     my $partserror;
 3725:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3726:     if ($partserror) {
 3727:         return &navmap_errormsg();
 3728:     }
 3729:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3730:     my @partids = ();
 3731:     foreach my $part (@parts) {
 3732: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3733:         my $narrowtext = &mt('Tries');
 3734: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3735: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3736: 	my ($partid) = &split_part_type($part);
 3737:         push(@partids,$partid);
 3738: #
 3739: # FIXME: Looks like $display looks at English text
 3740: #
 3741: 	my $display_part=&get_display_part($partid,$symb);
 3742: 	if ($display =~ /^Partial Credit Factor/) {
 3743: 	    $result.='<th>'.
 3744: 		&mt('Score Part: [_1][_2](weight = [_3])',
 3745: 		    $display_part,'<br />',$weight{$partid}).'</th>'."\n";
 3746: 	    next;
 3747: 	    
 3748: 	} else {
 3749: 	    if ($display =~ /Problem Status/) {
 3750: 		my $grade_status_mt = &mt('Grade Status');
 3751: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3752: 	    }
 3753: 	    my $part_mt = &mt('Part:');
 3754: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3755: 	}
 3756: 
 3757: 	$result.='<th>'.$display.'</th>'."\n";
 3758:     }
 3759:     $result.=&Apache::loncommon::end_data_table_header_row();
 3760: 
 3761:     my %last_resets = 
 3762: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3763: 
 3764:     #get info for each student
 3765:     #list all the students - with points and grade status
 3766:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3767:     my $ctr = 0;
 3768:     foreach (sort 
 3769: 	     {
 3770: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3771: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3772: 		 }
 3773: 		 return $a cmp $b;
 3774: 	     } (keys(%$fullname))) {
 3775: 	$ctr++;
 3776: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3777: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3778:     }
 3779:     $result.=&Apache::loncommon::end_data_table();
 3780:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3781:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3782: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 3783:     if (scalar(%$fullname) eq 0) {
 3784: 	my $colspan=3+scalar(@parts);
 3785: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3786:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3787: 	$result='<span class="LC_warning">'.
 3788: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3789: 	        $section_display, $stu_status).
 3790: 	    '</span>';
 3791:     }
 3792:     return $result;
 3793: }
 3794: 
 3795: #--- call by previous routine to display each student
 3796: sub viewstudentgrade {
 3797:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3798:     my ($uname,$udom) = split(/:/,$student);
 3799:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3800:     my %aggregates = (); 
 3801:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3802: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3803: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3804: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3805: 	'\');" target="_self">'.$fullname.'</a> '.
 3806: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3807:     $student=~s/:/_/; # colon doen't work in javascript for names
 3808:     foreach my $apart (@$parts) {
 3809: 	my ($part,$type) = &split_part_type($apart);
 3810: 	my $score=$record{"resource.$part.$type"};
 3811:         $result.='<td align="center">';
 3812:         my ($aggtries,$totaltries);
 3813:         unless (exists($aggregates{$part})) {
 3814: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3815: 
 3816: 	    $aggtries = $totaltries;
 3817:             if ($$last_resets{$part}) {  
 3818:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3819: 					   $part);
 3820:             }
 3821:             $result.='<input type="hidden" name="'.
 3822:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3823:             $result.='<input type="hidden" name="'.
 3824:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3825:             $aggregates{$part} = 1;
 3826:         }
 3827: 	if ($type eq 'awarded') {
 3828: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3829: 	    $result.='<input type="hidden" name="'.
 3830: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3831: 	    $result.='<input type="text" name="'.
 3832: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3833:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3834: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3835: 	} elsif ($type eq 'solved') {
 3836: 	    my ($status,$foo)=split(/_/,$score,2);
 3837: 	    $status = 'nothing' if ($status eq '');
 3838: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3839: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3840: 	    $result.='&nbsp;<select name="'.
 3841: 		'GD_'.$student.'_'.$part.'_solved" '.
 3842:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3843: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3844: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3845: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3846: 	    $result.="</select>&nbsp;</td>\n";
 3847: 	} else {
 3848: 	    $result.='<input type="hidden" name="'.
 3849: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3850: 		    "\n";
 3851: 	    $result.='<input type="text" name="'.
 3852: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3853: 		'value="'.$score.'" size="4" /></td>'."\n";
 3854: 	}
 3855:     }
 3856:     $result.=&Apache::loncommon::end_data_table_row();
 3857:     return $result;
 3858: }
 3859: 
 3860: #--- change scores for all the students in a section/class
 3861: #    record does not get update if unchanged
 3862: sub editgrades {
 3863:     my ($request,$symb) = @_;
 3864: 
 3865:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3866:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3867:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3868: 
 3869:     my $result= &Apache::loncommon::start_data_table().
 3870: 	&Apache::loncommon::start_data_table_header_row().
 3871: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3872: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3873:     my %scoreptr = (
 3874: 		    'correct'  =>'correct_by_override',
 3875: 		    'incorrect'=>'incorrect_by_override',
 3876: 		    'excused'  =>'excused',
 3877: 		    'ungraded' =>'ungraded_attempted',
 3878:                     'credited' =>'credit_attempted',
 3879: 		    'nothing'  => '',
 3880: 		    );
 3881:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3882: 
 3883:     my (@partid);
 3884:     my %weight = ();
 3885:     my %columns = ();
 3886:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3887: 
 3888:     my $partserror;
 3889:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3890:     if ($partserror) {
 3891:         return &navmap_errormsg();
 3892:     }
 3893:     my $header;
 3894:     while ($ctr < $env{'form.totalparts'}) {
 3895: 	my $partid = $env{'form.partid_'.$ctr};
 3896: 	push(@partid,$partid);
 3897: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3898: 	$ctr++;
 3899:     }
 3900:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3901:     foreach my $partid (@partid) {
 3902: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3903: 	    '<th align="center">'.&mt('New Score').'</th>';
 3904: 	$columns{$partid}=2;
 3905: 	foreach my $stores (@parts) {
 3906: 	    my ($part,$type) = &split_part_type($stores);
 3907: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3908: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3909: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3910: 	    $display =~ s/\[Part: \Q$part\E\]//;
 3911:             my $narrowtext = &mt('Tries');
 3912: 	    $display =~ s/Number of Attempts/$narrowtext/;
 3913: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 3914: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 3915: 	    $columns{$partid}+=2;
 3916: 	}
 3917:     }
 3918:     foreach my $partid (@partid) {
 3919: 	my $display_part=&get_display_part($partid,$symb);
 3920: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3921: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3922: 	    '</th>';
 3923: 
 3924:     }
 3925:     $result .= &Apache::loncommon::end_data_table_header_row().
 3926: 	&Apache::loncommon::start_data_table_header_row().
 3927: 	$header.
 3928: 	&Apache::loncommon::end_data_table_header_row();
 3929:     my @noupdate;
 3930:     my ($updateCtr,$noupdateCtr) = (1,1);
 3931:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3932: 	my $line;
 3933: 	my $user = $env{'form.ctr'.$i};
 3934: 	my ($uname,$udom)=split(/:/,$user);
 3935: 	my %newrecord;
 3936: 	my $updateflag = 0;
 3937: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3938: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3939: 	if (!&canmodify($usec)) {
 3940: 	    my $numcols=scalar(@partid)*4+2;
 3941: 	    push(@noupdate,
 3942: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 3943: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 3944: 	    next;
 3945: 	}
 3946:         my %aggregate = ();
 3947:         my $aggregateflag = 0;
 3948: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3949: 	foreach (@partid) {
 3950: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3951: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3952: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3953: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3954: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3955: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3956: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3957: 	    my $score;
 3958: 	    if ($partial eq '') {
 3959: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3960: 	    } elsif ($partial > 0) {
 3961: 		$score = 'correct_by_override';
 3962: 	    } elsif ($partial == 0) {
 3963: 		$score = 'incorrect_by_override';
 3964: 	    }
 3965: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3966: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3967: 
 3968: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3969: 		"$env{'user.name'}:$env{'user.domain'}";
 3970: 	    if ($dropMenu eq 'reset status' &&
 3971: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3972: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3973: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3974: 		$newrecord{'resource.'.$_.'.award'} = '';
 3975: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3976: 		$updateflag = 1;
 3977:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3978:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3979:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3980:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3981:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3982:                     $aggregateflag = 1;
 3983:                 }
 3984: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3985: 		$updateflag = 1;
 3986: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3987: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3988: 		$rec_update++;
 3989: 	    }
 3990: 
 3991: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3992: 		'<td align="center">'.$awarded.
 3993: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3994: 
 3995: 
 3996: 	    my $partid=$_;
 3997: 	    foreach my $stores (@parts) {
 3998: 		my ($part,$type) = &split_part_type($stores);
 3999: 		if ($part !~ m/^\Q$partid\E/) { next;}
 4000: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 4001: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 4002: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 4003: 		if ($awarded ne '' && $awarded ne $old_aw) {
 4004: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 4005: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 4006: 		    $updateflag=1;
 4007: 		}
 4008: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4009: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 4010: 	    }
 4011: 	}
 4012: 	$line.="\n";
 4013: 
 4014: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4015: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4016: 
 4017: 	if ($updateflag) {
 4018: 	    $count++;
 4019: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 4020: 				    $udom,$uname);
 4021: 
 4022: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 4023: 					      $cnum,$udom,$uname)) {
 4024: 		# need to figure out if should be in queue.
 4025: 		my %record =  
 4026: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 4027: 					     $udom,$uname);
 4028: 		my $all_graded = 1;
 4029: 		my $none_graded = 1;
 4030: 		foreach my $part (@parts) {
 4031: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 4032: 			$all_graded = 0;
 4033: 		    } else {
 4034: 			$none_graded = 0;
 4035: 		    }
 4036: 		}
 4037: 
 4038: 		if ($all_graded || $none_graded) {
 4039: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 4040: 							   $symb,$cdom,$cnum,
 4041: 							   $udom,$uname);
 4042: 		}
 4043: 	    }
 4044: 
 4045: 	    $result.=&Apache::loncommon::start_data_table_row().
 4046: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 4047: 		&Apache::loncommon::end_data_table_row();
 4048: 	    $updateCtr++;
 4049: 	} else {
 4050: 	    push(@noupdate,
 4051: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 4052: 	    $noupdateCtr++;
 4053: 	}
 4054:         if ($aggregateflag) {
 4055:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4056: 				  $cdom,$cnum);
 4057:         }
 4058:     }
 4059:     if (@noupdate) {
 4060: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 4061: 	my $numcols=scalar(@partid)*4+2;
 4062: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 4063: 	    '<td align="center" colspan="'.$numcols.'">'.
 4064: 	    &mt('No Changes Occurred For the Students Below').
 4065: 	    '</td>'.
 4066: 	    &Apache::loncommon::end_data_table_row();
 4067: 	foreach my $line (@noupdate) {
 4068: 	    $result.=
 4069: 		&Apache::loncommon::start_data_table_row().
 4070: 		$line.
 4071: 		&Apache::loncommon::end_data_table_row();
 4072: 	}
 4073:     }
 4074:     $result .= &Apache::loncommon::end_data_table();
 4075:     my $msg = '<p><b>'.
 4076: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 4077: 	    $rec_update,$count).'</b><br />'.
 4078: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 4079: 	'</b></p>';
 4080:     return $title.$msg.$result;
 4081: }
 4082: 
 4083: sub split_part_type {
 4084:     my ($partstr) = @_;
 4085:     my ($temp,@allparts)=split(/_/,$partstr);
 4086:     my $type=pop(@allparts);
 4087:     my $part=join('_',@allparts);
 4088:     return ($part,$type);
 4089: }
 4090: 
 4091: #------------- end of section for handling grading by section/class ---------
 4092: #
 4093: #----------------------------------------------------------------------------
 4094: 
 4095: 
 4096: #----------------------------------------------------------------------------
 4097: #
 4098: #-------------------------- Next few routines handles grading by csv upload
 4099: #
 4100: #--- Javascript to handle csv upload
 4101: sub csvupload_javascript_reverse_associate {
 4102:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4103:     my $error2=&mt('You need to specify at least one grading field');
 4104:   return(<<ENDPICK);
 4105:   function verify(vf) {
 4106:     var foundsomething=0;
 4107:     var founduname=0;
 4108:     var foundID=0;
 4109:     for (i=0;i<=vf.nfields.value;i++) {
 4110:       tw=eval('vf.f'+i+'.selectedIndex');
 4111:       if (i==0 && tw!=0) { foundID=1; }
 4112:       if (i==1 && tw!=0) { founduname=1; }
 4113:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 4114:     }
 4115:     if (founduname==0 && foundID==0) {
 4116: 	alert('$error1');
 4117: 	return;
 4118:     }
 4119:     if (foundsomething==0) {
 4120: 	alert('$error2');
 4121: 	return;
 4122:     }
 4123:     vf.submit();
 4124:   }
 4125:   function flip(vf,tf) {
 4126:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4127:     var i;
 4128:     for (i=0;i<=vf.nfields.value;i++) {
 4129:       //can not pick the same destination field for both name and domain
 4130:       if (((i ==0)||(i ==1)) && 
 4131:           ((tf==0)||(tf==1)) && 
 4132:           (i!=tf) &&
 4133:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4134:         eval('vf.f'+i+'.selectedIndex=0;')
 4135:       }
 4136:     }
 4137:   }
 4138: ENDPICK
 4139: }
 4140: 
 4141: sub csvupload_javascript_forward_associate {
 4142:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4143:     my $error2=&mt('You need to specify at least one grading field');
 4144:   return(<<ENDPICK);
 4145:   function verify(vf) {
 4146:     var foundsomething=0;
 4147:     var founduname=0;
 4148:     var foundID=0;
 4149:     for (i=0;i<=vf.nfields.value;i++) {
 4150:       tw=eval('vf.f'+i+'.selectedIndex');
 4151:       if (tw==1) { foundID=1; }
 4152:       if (tw==2) { founduname=1; }
 4153:       if (tw>3) { foundsomething=1; }
 4154:     }
 4155:     if (founduname==0 && foundID==0) {
 4156: 	alert('$error1');
 4157: 	return;
 4158:     }
 4159:     if (foundsomething==0) {
 4160: 	alert('$error2');
 4161: 	return;
 4162:     }
 4163:     vf.submit();
 4164:   }
 4165:   function flip(vf,tf) {
 4166:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4167:     var i;
 4168:     //can not pick the same destination field twice
 4169:     for (i=0;i<=vf.nfields.value;i++) {
 4170:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4171:         eval('vf.f'+i+'.selectedIndex=0;')
 4172:       }
 4173:     }
 4174:   }
 4175: ENDPICK
 4176: }
 4177: 
 4178: sub csvuploadmap_header {
 4179:     my ($request,$symb,$datatoken,$distotal)= @_;
 4180:     my $javascript;
 4181:     if ($env{'form.upfile_associate'} eq 'reverse') {
 4182: 	$javascript=&csvupload_javascript_reverse_associate();
 4183:     } else {
 4184: 	$javascript=&csvupload_javascript_forward_associate();
 4185:     }
 4186: 
 4187:     $symb = &Apache::lonenc::check_encrypt($symb);
 4188:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
 4189:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
 4190:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
 4191:     my $reverse=&mt("Reverse Association");
 4192:     $request->print(<<ENDPICK);
 4193: <br />
 4194: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 4195: <input type="hidden" name="associate"  value="" />
 4196: <input type="hidden" name="phase"      value="three" />
 4197: <input type="hidden" name="datatoken"  value="$datatoken" />
 4198: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 4199: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 4200: <input type="hidden" name="upfile_associate" 
 4201:                                        value="$env{'form.upfile_associate'}" />
 4202: <input type="hidden" name="symb"       value="$symb" />
 4203: <input type="hidden" name="command"    value="csvuploadoptions" />
 4204: <hr />
 4205: ENDPICK
 4206:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
 4207:     return '';
 4208: 
 4209: }
 4210: 
 4211: sub csvupload_fields {
 4212:     my ($symb,$errorref) = @_;
 4213:     my (@parts) = &getpartlist($symb,$errorref);
 4214:     if (ref($errorref)) {
 4215:         if ($$errorref) {
 4216:             return;
 4217:         }
 4218:     }
 4219: 
 4220:     my @fields=(['ID','Student/Employee ID'],
 4221: 		['username','Student Username'],
 4222: 		['domain','Student Domain']);
 4223:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4224:     foreach my $part (sort(@parts)) {
 4225: 	my @datum;
 4226: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 4227: 	my $name=$part;
 4228: 	if  (!$display) { $display = $name; }
 4229: 	@datum=($name,$display);
 4230: 	if ($name=~/^stores_(.*)_awarded/) {
 4231: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 4232: 	}
 4233: 	push(@fields,\@datum);
 4234:     }
 4235:     return (@fields);
 4236: }
 4237: 
 4238: sub csvuploadmap_footer {
 4239:     my ($request,$i,$keyfields) =@_;
 4240:     my $buttontext = &mt('Assign Grades');
 4241:     $request->print(<<ENDPICK);
 4242: </table>
 4243: <input type="hidden" name="nfields" value="$i" />
 4244: <input type="hidden" name="keyfields" value="$keyfields" />
 4245: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
 4246: </form>
 4247: ENDPICK
 4248: }
 4249: 
 4250: sub checkforfile_js {
 4251:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 4252:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
 4253:     function checkUpload(formname) {
 4254: 	if (formname.upfile.value == "") {
 4255: 	    alert("$alertmsg");
 4256: 	    return false;
 4257: 	}
 4258: 	formname.submit();
 4259:     }
 4260: CSVFORMJS
 4261:     return $result;
 4262: }
 4263: 
 4264: sub upcsvScores_form {
 4265:     my ($request,$symb) = @_;
 4266:     if (!$symb) {return '';}
 4267:     my $result=&checkforfile_js();
 4268:     $result.=&Apache::loncommon::start_data_table().
 4269:              &Apache::loncommon::start_data_table_header_row().
 4270:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
 4271:              &Apache::loncommon::end_data_table_header_row().
 4272:              &Apache::loncommon::start_data_table_row().'<td>';
 4273:     my $upload=&mt("Upload Scores");
 4274:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 4275:     my $ignore=&mt('Ignore First Line');
 4276:     $symb = &Apache::lonenc::check_encrypt($symb);
 4277:     $result.=<<ENDUPFORM;
 4278: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4279: <input type="hidden" name="symb" value="$symb" />
 4280: <input type="hidden" name="command" value="csvuploadmap" />
 4281: $upfile_select
 4282: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 4283: </form>
 4284: ENDUPFORM
 4285:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 4286:                            &mt("How do I create a CSV file from a spreadsheet")).
 4287:              '</td>'.
 4288:             &Apache::loncommon::end_data_table_row().
 4289:             &Apache::loncommon::end_data_table();
 4290:     return $result;
 4291: }
 4292: 
 4293: 
 4294: sub csvuploadmap {
 4295:     my ($request,$symb)= @_;
 4296:     if (!$symb) {return '';}
 4297: 
 4298:     my $datatoken;
 4299:     if (!$env{'form.datatoken'}) {
 4300: 	$datatoken=&Apache::loncommon::upfile_store($request);
 4301:     } else {
 4302: 	$datatoken=$env{'form.datatoken'};
 4303: 	&Apache::loncommon::load_tmp_file($request);
 4304:     }
 4305:     my @records=&Apache::loncommon::upfile_record_sep();
 4306:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 4307:     my ($i,$keyfields);
 4308:     if (@records) {
 4309:         my $fieldserror;
 4310: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 4311:         if ($fieldserror) {
 4312:             $request->print(&navmap_errormsg());
 4313:             return;
 4314:         }
 4315: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 4316: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 4317: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 4318: 							  \@fields);
 4319: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 4320: 	    chop($keyfields);
 4321: 	} else {
 4322: 	    unshift(@fields,['none','']);
 4323: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 4324: 							    \@fields);
 4325:             foreach my $rec (@records) {
 4326:                 my %temp = &Apache::loncommon::record_sep($rec);
 4327:                 if (%temp) {
 4328:                     $keyfields=join(',',sort(keys(%temp)));
 4329:                     last;
 4330:                 }
 4331:             }
 4332: 	}
 4333:     }
 4334:     &csvuploadmap_footer($request,$i,$keyfields);
 4335: 
 4336:     return '';
 4337: }
 4338: 
 4339: sub csvuploadoptions {
 4340:     my ($request,$symb)= @_;
 4341:     my $overwrite=&mt('Overwrite any existing score');
 4342:     $request->print(<<ENDPICK);
 4343: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4344: <input type="hidden" name="command"    value="csvuploadassign" />
 4345: <p>
 4346: <label>
 4347:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4348:    $overwrite
 4349: </label>
 4350: </p>
 4351: ENDPICK
 4352:     my %fields=&get_fields();
 4353:     if (!defined($fields{'domain'})) {
 4354: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4355: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
 4356:     }
 4357:     foreach my $key (sort(keys(%env))) {
 4358: 	if ($key !~ /^form\.(.*)$/) { next; }
 4359: 	my $cleankey=$1;
 4360: 	if ($cleankey eq 'command') { next; }
 4361: 	$request->print('<input type="hidden" name="'.$cleankey.
 4362: 			'"  value="'.$env{$key}.'" />'."\n");
 4363:     }
 4364:     # FIXME do a check for any duplicated user ids...
 4365:     # FIXME do a check for any invalid user ids?...
 4366:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
 4367: <hr /></form>'."\n");
 4368:     return '';
 4369: }
 4370: 
 4371: sub get_fields {
 4372:     my %fields;
 4373:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4374:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4375: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4376: 	    if ($env{'form.f'.$i} ne 'none') {
 4377: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4378: 	    }
 4379: 	} else {
 4380: 	    if ($env{'form.f'.$i} ne 'none') {
 4381: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4382: 	    }
 4383: 	}
 4384:     }
 4385:     return %fields;
 4386: }
 4387: 
 4388: sub csvuploadassign {
 4389:     my ($request,$symb)= @_;
 4390:     if (!$symb) {return '';}
 4391:     my $error_msg = '';
 4392:     &Apache::loncommon::load_tmp_file($request);
 4393:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4394:     my %fields=&get_fields();
 4395:     my $courseid=$env{'request.course.id'};
 4396:     my ($classlist) = &getclasslist('all',0);
 4397:     my @notallowed;
 4398:     my @skipped;
 4399:     my @warnings;
 4400:     my $countdone=0;
 4401:     foreach my $grade (@gradedata) {
 4402: 	my %entries=&Apache::loncommon::record_sep($grade);
 4403: 	my $domain;
 4404: 	if ($entries{$fields{'domain'}}) {
 4405: 	    $domain=$entries{$fields{'domain'}};
 4406: 	} else {
 4407: 	    $domain=$env{'form.default_domain'};
 4408: 	}
 4409: 	$domain=~s/\s//g;
 4410: 	my $username=$entries{$fields{'username'}};
 4411: 	$username=~s/\s//g;
 4412: 	if (!$username) {
 4413: 	    my $id=$entries{$fields{'ID'}};
 4414: 	    $id=~s/\s//g;
 4415: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4416: 	    $username=$ids{$id};
 4417: 	}
 4418: 	if (!exists($$classlist{"$username:$domain"})) {
 4419: 	    my $id=$entries{$fields{'ID'}};
 4420: 	    $id=~s/\s//g;
 4421: 	    if ($id) {
 4422: 		push(@skipped,"$id:$domain");
 4423: 	    } else {
 4424: 		push(@skipped,"$username:$domain");
 4425: 	    }
 4426: 	    next;
 4427: 	}
 4428: 	my $usec=$classlist->{"$username:$domain"}[5];
 4429: 	if (!&canmodify($usec)) {
 4430: 	    push(@notallowed,"$username:$domain");
 4431: 	    next;
 4432: 	}
 4433: 	my %points;
 4434: 	my %grades;
 4435: 	foreach my $dest (keys(%fields)) {
 4436: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4437: 		$dest eq 'domain') { next; }
 4438: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4439: 	    if ($dest=~/stores_(.*)_points/) {
 4440: 		my $part=$1;
 4441: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4442: 					      $symb,$domain,$username);
 4443:                 if ($wgt) {
 4444:                     $entries{$fields{$dest}}=~s/\s//g;
 4445:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4446:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4447:                                           : 'correct_by_override';
 4448:                     if ($pcr>1) {
 4449:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
 4450:                     }
 4451:                     $grades{"resource.$part.awarded"}=$pcr;
 4452:                     $grades{"resource.$part.solved"}=$award;
 4453:                     $points{$part}=1;
 4454:                 } else {
 4455:                     $error_msg = "<br />" .
 4456:                         &mt("Some point values were assigned"
 4457:                             ." for problems with a weight "
 4458:                             ."of zero. These values were "
 4459:                             ."ignored.");
 4460:                 }
 4461: 	    } else {
 4462: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4463: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4464: 		my $store_key=$dest;
 4465: 		$store_key=~s/^stores/resource/;
 4466: 		$store_key=~s/_/\./g;
 4467: 		$grades{$store_key}=$entries{$fields{$dest}};
 4468: 	    }
 4469: 	}
 4470: 	if (! %grades) { 
 4471:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4472:         } else {
 4473: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4474: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4475: 					   $env{'request.course.id'},
 4476: 					   $domain,$username);
 4477: 	   if ($result eq 'ok') {
 4478: # Successfully stored
 4479: 	      $request->print('.');
 4480: # Remove from grading queue
 4481:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
 4482:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
 4483:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
 4484:                                              $domain,$username);
 4485:               $countdone++;
 4486:            } else {
 4487: 	      $request->print("<p><span class=\"LC_error\">".
 4488:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4489:                                   "$username:$domain",$result)."</span></p>");
 4490: 	   }
 4491: 	   $request->rflush();
 4492:         }
 4493:     }
 4494:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 4495:     if (@warnings) {
 4496:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
 4497:         $request->print(join(', ',@warnings));
 4498:     }
 4499:     if (@skipped) {
 4500: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 4501:         $request->print(join(', ',@skipped));
 4502:     }
 4503:     if (@notallowed) {
 4504: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 4505: 	$request->print(join(', ',@notallowed));
 4506:     }
 4507:     $request->print("<br />\n");
 4508:     return $error_msg;
 4509: }
 4510: #------------- end of section for handling csv file upload ---------
 4511: #
 4512: #-------------------------------------------------------------------
 4513: #
 4514: #-------------- Next few routines handle grading by page/sequence
 4515: #
 4516: #--- Select a page/sequence and a student to grade
 4517: sub pickStudentPage {
 4518:     my ($request,$symb) = @_;
 4519: 
 4520:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4521:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
 4522: 
 4523: function checkPickOne(formname) {
 4524:     if (radioSelection(formname.student) == null) {
 4525: 	alert("$alertmsg");
 4526: 	return;
 4527:     }
 4528:     ptr = pullDownSelection(formname.selectpage);
 4529:     formname.page.value = formname["page"+ptr].value;
 4530:     formname.title.value = formname["title"+ptr].value;
 4531:     formname.submit();
 4532: }
 4533: 
 4534: LISTJAVASCRIPT
 4535:     &commonJSfunctions($request);
 4536: 
 4537:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4538:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4539:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4540: 
 4541:     my $result='<h3><span class="LC_info">&nbsp;'.
 4542: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4543: 
 4544:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4545:     my $map_error;
 4546:     my ($titles,$symbx) = &getSymbMap($map_error);
 4547:     if ($map_error) {
 4548:         $request->print(&navmap_errormsg());
 4549:         return; 
 4550:     }
 4551:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4552: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4553: #    my $type=($curpage =~ /\.(page|sequence)/);
 4554: 
 4555:     # Collection of hidden fields
 4556:     my $ctr=0;
 4557:     foreach (@$titles) {
 4558:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4559:         $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4560:         $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4561:         $ctr++;
 4562:     }
 4563:     $result.='<input type="hidden" name="page" />'."\n".
 4564:         '<input type="hidden" name="title" />'."\n";
 4565: 
 4566:     $result.=&build_section_inputs();
 4567:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4568:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4569: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4570: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 4571: 
 4572:     # Show grading options
 4573:     $result.=&Apache::lonhtmlcommon::start_pick_box();
 4574:     my $select = '<select name="selectpage">'."\n";
 4575:     $ctr=0;
 4576:     foreach (@$titles) {
 4577: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4578: 	$select.='<option value="'.$ctr.'"'.
 4579: 	    ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
 4580: 	    '>'.$showtitle.'</option>'."\n";
 4581: 	$ctr++;
 4582:     }
 4583:     $select.= '</select>';
 4584: 
 4585:     $result.=
 4586:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
 4587:        .$select
 4588:        .&Apache::lonhtmlcommon::row_closure();
 4589: 
 4590:     $result.=
 4591:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
 4592:        .'<label><input type="radio" name="vProb" value="no"'
 4593:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
 4594:        .'<label><input type="radio" name="vProb" value="yes" />'
 4595:            .&mt('yes').'</label>'."\n"
 4596:        .&Apache::lonhtmlcommon::row_closure();
 4597: 
 4598:     $result.=
 4599:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
 4600:        .'<label><input type="radio" name="lastSub" value="none" /> '
 4601:            .&mt('none').' </label>'."\n"
 4602:        .'<label><input type="radio" name="lastSub" value="datesub"'
 4603:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
 4604:        .'<label><input type="radio" name="lastSub" value="all" /> '
 4605:            .&mt('all submissions with details').' </label>'
 4606:        .&Apache::lonhtmlcommon::row_closure();
 4607:     
 4608:     $result.=
 4609:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
 4610:        .'<input type="text" name="CODE" value="" />'
 4611:        .&Apache::lonhtmlcommon::row_closure(1)
 4612:        .&Apache::lonhtmlcommon::end_pick_box();
 4613: 
 4614:     # Show list of students to select for grading
 4615:     $result.='<br /><input type="button" '.
 4616:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4617: 
 4618:     $request->print($result);
 4619: 
 4620:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4621: 	&Apache::loncommon::start_data_table().
 4622: 	&Apache::loncommon::start_data_table_header_row().
 4623: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4624: 	'<th>'.&nameUserString('header').'</th>'.
 4625: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4626: 	'<th>'.&nameUserString('header').'</th>'.
 4627: 	&Apache::loncommon::end_data_table_header_row();
 4628:  
 4629:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4630:     my $ptr = 1;
 4631:     foreach my $student (sort 
 4632: 			 {
 4633: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4634: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4635: 			     }
 4636: 			     return $a cmp $b;
 4637: 			 } (keys(%$fullname))) {
 4638: 	my ($uname,$udom) = split(/:/,$student);
 4639: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4640:                                   : '</td>');
 4641: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4642: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4643: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4644: 	$studentTable.=
 4645: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4646:                          : '');
 4647: 	$ptr++;
 4648:     }
 4649:     if ($ptr%2 == 0) {
 4650: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4651: 	    &Apache::loncommon::end_data_table_row();
 4652:     }
 4653:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4654:     $studentTable.='<input type="button" '.
 4655:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4656: 
 4657:     $request->print($studentTable);
 4658: 
 4659:     return '';
 4660: }
 4661: 
 4662: sub getSymbMap {
 4663:     my ($map_error) = @_;
 4664:     my $navmap = Apache::lonnavmaps::navmap->new();
 4665:     unless (ref($navmap)) {
 4666:         if (ref($map_error)) {
 4667:             $$map_error = 'navmap';
 4668:         }
 4669:         return;
 4670:     }
 4671:     my %symbx = ();
 4672:     my @titles = ();
 4673:     my $minder = 0;
 4674: 
 4675:     # Gather every sequence that has problems.
 4676:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4677: 					       1,0,1);
 4678:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4679: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4680: 	    my $title = $minder.'.'.
 4681: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4682: 	    push(@titles, $title); # minder in case two titles are identical
 4683: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4684: 	    $minder++;
 4685: 	}
 4686:     }
 4687:     return \@titles,\%symbx;
 4688: }
 4689: 
 4690: #
 4691: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4692: sub displayPage {
 4693:     my ($request,$symb) = @_;
 4694:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4695:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4696:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4697:     my $pageTitle = $env{'form.page'};
 4698:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4699:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4700:     my $usec=$classlist->{$env{'form.student'}}[5];
 4701: 
 4702:     #need to make sure we have the correct data for later EXT calls, 
 4703:     #thus invalidate the cache
 4704:     &Apache::lonnet::devalidatecourseresdata(
 4705:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4706:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4707:     &Apache::lonnet::clear_EXT_cache_status();
 4708: 
 4709:     if (!&canview($usec)) {
 4710:         $request->print(
 4711:             '<span class="LC_warning">'.
 4712:             &mt('Unable to view requested student. ([_1])',
 4713:                     $env{'form.student'}).
 4714:             '</span>');
 4715:         return;
 4716:     }
 4717:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4718:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4719: 	'</h3>'."\n";
 4720:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4721:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4722: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4723:     } else {
 4724: 	delete($env{'form.CODE'});
 4725:     }
 4726:     &sub_page_js($request);
 4727:     $request->print($result);
 4728: 
 4729:     my $navmap = Apache::lonnavmaps::navmap->new();
 4730:     unless (ref($navmap)) {
 4731:         $request->print(&navmap_errormsg());
 4732:         return;
 4733:     }
 4734:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4735:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4736:     if (!$map) {
 4737: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4738: 	return; 
 4739:     }
 4740:     my $iterator = $navmap->getIterator($map->map_start(),
 4741: 					$map->map_finish());
 4742: 
 4743:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4744: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4745: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4746: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4747: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4748: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4749: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4750: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
 4751: 
 4752:     if (defined($env{'form.CODE'})) {
 4753: 	$studentTable.=
 4754: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4755:     }
 4756:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4757: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4758: 
 4759:     $studentTable.='&nbsp;<span class="LC_info">'.
 4760:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 4761:         '</span>'."\n".
 4762: 	&Apache::loncommon::start_data_table().
 4763: 	&Apache::loncommon::start_data_table_header_row().
 4764: 	'<th>'.&mt('Prob.').'</th>'.
 4765: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4766: 	&Apache::loncommon::end_data_table_header_row();
 4767: 
 4768:     &Apache::lonxml::clear_problem_counter();
 4769:     my ($depth,$question,$prob) = (1,1,1);
 4770:     $iterator->next(); # skip the first BEGIN_MAP
 4771:     my $curRes = $iterator->next(); # for "current resource"
 4772:     while ($depth > 0) {
 4773:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4774:         if($curRes == $iterator->END_MAP) { $depth--; }
 4775: 
 4776:         if (ref($curRes) && $curRes->is_problem()) {
 4777: 	    my $parts = $curRes->parts();
 4778:             my $title = $curRes->compTitle();
 4779: 	    my $symbx = $curRes->symb();
 4780: 	    $studentTable.=
 4781: 		&Apache::loncommon::start_data_table_row().
 4782: 		'<td align="center" valign="top" >'.$prob.
 4783: 		(scalar(@{$parts}) == 1 ? '' 
 4784: 		                        : '<br />('.&mt('[_1]parts',
 4785: 							scalar(@{$parts}).'&nbsp;').')'
 4786: 		 ).
 4787: 		 '</td>';
 4788: 	    $studentTable.='<td valign="top">';
 4789: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4790: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4791: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4792: 					     undef,'both',\%form);
 4793: 	    } else {
 4794: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4795: 		$companswer =~ s|<form(.*?)>||g;
 4796: 		$companswer =~ s|</form>||g;
 4797: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4798: #		    $companswer =~ s/$1/ /ms;
 4799: #		    $request->print('match='.$1."<br />\n");
 4800: #		}
 4801: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4802: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 4803: 	    }
 4804: 
 4805: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4806: 
 4807: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4808: 		if ($record{'version'} eq '') {
 4809: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4810: 		} else {
 4811: 		    my %responseType = ();
 4812: 		    foreach my $partid (@{$parts}) {
 4813: 			my @responseIds =$curRes->responseIds($partid);
 4814: 			my @responseType =$curRes->responseType($partid);
 4815: 			my %responseIds;
 4816: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4817: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4818: 			}
 4819: 			$responseType{$partid} = \%responseIds;
 4820: 		    }
 4821: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4822: 
 4823: 		}
 4824: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4825: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4826:                 my $identifier = (&canmodify($usec)? $prob : ''); 
 4827: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4828: 									$env{'request.course.id'},
 4829: 									'','.submission',undef,
 4830:                                                                         $usec,$identifier);
 4831:  
 4832: 	    }
 4833: 	    if (&canmodify($usec)) {
 4834:             $studentTable.=&gradeBox_start();
 4835: 		foreach my $partid (@{$parts}) {
 4836: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4837: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4838: 		    $question++;
 4839: 		}
 4840:             $studentTable.=&gradeBox_end();
 4841: 		$prob++;
 4842: 	    }
 4843: 	    $studentTable.='</td></tr>';
 4844: 
 4845: 	}
 4846:         $curRes = $iterator->next();
 4847:     }
 4848: 
 4849:     $studentTable.=
 4850:         '</table>'."\n".
 4851:         '<input type="button" value="'.&mt('Save').'" '.
 4852:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4853:         '</form>'."\n";
 4854:     $request->print($studentTable);
 4855: 
 4856:     return '';
 4857: }
 4858: 
 4859: sub displaySubByDates {
 4860:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4861:     my $isCODE=0;
 4862:     my $isTask = ($symb =~/\.task$/);
 4863:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4864:     my $studentTable=&Apache::loncommon::start_data_table().
 4865: 	&Apache::loncommon::start_data_table_header_row().
 4866: 	'<th>'.&mt('Date/Time').'</th>'.
 4867: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4868:         ($isTask?'<th>'.&mt('Version').'</th>':'').
 4869: 	'<th>'.&mt('Submission').'</th>'.
 4870: 	'<th>'.&mt('Status').'</th>'.
 4871: 	&Apache::loncommon::end_data_table_header_row();
 4872:     my ($version);
 4873:     my %mark;
 4874:     my %orders;
 4875:     $mark{'correct_by_student'} = $checkIcon;
 4876:     if (!exists($$record{'1:timestamp'})) {
 4877: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 4878:     }
 4879: 
 4880:     my $interaction;
 4881:     my $no_increment = 1;
 4882:     my %lastrndseed;
 4883:     for ($version=1;$version<=$$record{'version'};$version++) {
 4884: 	my $timestamp = 
 4885: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4886: 	if (exists($$record{$version.':resource.0.version'})) {
 4887: 	    $interaction = $$record{$version.':resource.0.version'};
 4888: 	}
 4889:         if ($isTask && $env{'form.previousversion'}) {
 4890:             next unless ($interaction == $env{'form.previousversion'});
 4891:         }
 4892: 	my $where = ($isTask ? "$version:resource.$interaction"
 4893: 		             : "$version:resource");
 4894: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4895: 	    '<td>'.$timestamp.'</td>';
 4896: 	if ($isCODE) {
 4897: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4898: 	}
 4899:         if ($isTask) {
 4900:             $studentTable.='<td>'.$interaction.'</td>';
 4901:         }
 4902: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4903: 	my @displaySub = ();
 4904: 	foreach my $partid (@{$parts}) {
 4905:             my ($hidden,$type);
 4906:             $type = $$record{$version.':resource.'.$partid.'.type'};
 4907:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
 4908:                 $hidden = 1;
 4909:             }
 4910: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4911: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4912: 	    
 4913: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4914: 	    my $display_part=&get_display_part($partid,$symb);
 4915: 	    foreach my $matchKey (@matchKey) {
 4916: 		if (exists($$record{$version.':'.$matchKey}) &&
 4917: 		    $$record{$version.':'.$matchKey} ne '') {
 4918:                     
 4919: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4920: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4921:                     $displaySub[0].='<span class="LC_nobreak">';
 4922:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 4923:                                    .' <span class="LC_internal_info">'
 4924:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
 4925:                                    .'</span>'
 4926:                                    .' <b>';
 4927:                     if ($hidden) {
 4928:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
 4929:                     } else {
 4930:                         my ($trial,$rndseed,$newvariation);
 4931:                         if ($type eq 'randomizetry') {
 4932:                             $trial = $$record{"$where.$partid.tries"};
 4933:                             $rndseed = $$record{"$where.$partid.rndseed"};
 4934:                         }
 4935: 		        if ($$record{"$where.$partid.tries"} eq '') {
 4936: 			    $displaySub[0].=&mt('Trial not counted');
 4937: 		        } else {
 4938: 			    $displaySub[0].=&mt('Trial: [_1]',
 4939: 					    $$record{"$where.$partid.tries"});
 4940:                             if ($rndseed || $lastrndseed{$partid}) {
 4941:                                 if ($rndseed ne $lastrndseed{$partid}) {
 4942:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
 4943:                                 }
 4944:                             }
 4945:                             $lastrndseed{$partid} = $rndseed;
 4946: 		        }
 4947: 		        my $responseType=($isTask ? 'Task'
 4948:                                               : $responseType->{$partid}->{$responseId});
 4949: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4950: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
 4951: 			    $orders{$partid}->{$responseId}=
 4952: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
 4953:                                            $no_increment,$type,$trial,$rndseed);
 4954: 		        }
 4955: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
 4956: 		        $displaySub[0].='&nbsp; '.
 4957: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
 4958:                     }
 4959: 		}
 4960: 	    }
 4961: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4962: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 4963: 				    $$record{"$where.$partid.checkedin"},
 4964: 				    $$record{"$where.$partid.checkedin.slot"}).
 4965: 					'<br />';
 4966: 	    }
 4967: 	    if (exists $$record{"$where.$partid.award"}) {
 4968: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 4969: 		    lc($$record{"$where.$partid.award"}).' '.
 4970: 		    $mark{$$record{"$where.$partid.solved"}}.
 4971: 		    '<br />';
 4972: 	    }
 4973: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4974: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4975: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4976: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4977: 		$displaySub[2].=
 4978: 		    $$record{"$version:resource.$partid.regrader"}.
 4979: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4980: 	    }
 4981: 	}
 4982: 	# needed because old essay regrader has not parts info
 4983: 	if (exists $$record{"$version:resource.regrader"}) {
 4984: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 4985: 	}
 4986: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 4987: 	if ($displaySub[2]) {
 4988: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 4989: 	}
 4990: 	$studentTable.='&nbsp;</td>'.
 4991: 	    &Apache::loncommon::end_data_table_row();
 4992:     }
 4993:     $studentTable.=&Apache::loncommon::end_data_table();
 4994:     return $studentTable;
 4995: }
 4996: 
 4997: sub updateGradeByPage {
 4998:     my ($request,$symb) = @_;
 4999: 
 5000:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5001:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5002:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5003:     my $pageTitle = $env{'form.page'};
 5004:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5005:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5006:     my $usec=$classlist->{$env{'form.student'}}[5];
 5007:     if (!&canmodify($usec)) {
 5008: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 5009: 	return;
 5010:     }
 5011:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5012:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 5013: 	'</h3>'."\n";
 5014: 
 5015:     $request->print($result);
 5016: 
 5017: 
 5018:     my $navmap = Apache::lonnavmaps::navmap->new();
 5019:     unless (ref($navmap)) {
 5020:         $request->print(&navmap_errormsg());
 5021:         return;
 5022:     }
 5023:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 5024:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5025:     if (!$map) {
 5026: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 5027: 	return; 
 5028:     }
 5029:     my $iterator = $navmap->getIterator($map->map_start(),
 5030: 					$map->map_finish());
 5031: 
 5032:     my $studentTable=
 5033: 	&Apache::loncommon::start_data_table().
 5034: 	&Apache::loncommon::start_data_table_header_row().
 5035: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 5036: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 5037: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 5038: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 5039: 	&Apache::loncommon::end_data_table_header_row();
 5040: 
 5041:     $iterator->next(); # skip the first BEGIN_MAP
 5042:     my $curRes = $iterator->next(); # for "current resource"
 5043:     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
 5044:     while ($depth > 0) {
 5045:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5046:         if($curRes == $iterator->END_MAP) { $depth--; }
 5047: 
 5048:         if (ref($curRes) && $curRes->is_problem()) {
 5049: 	    my $parts = $curRes->parts();
 5050:             my $title = $curRes->compTitle();
 5051: 	    my $symbx = $curRes->symb();
 5052: 	    $studentTable.=
 5053: 		&Apache::loncommon::start_data_table_row().
 5054: 		'<td align="center" valign="top" >'.$prob.
 5055: 		(scalar(@{$parts}) == 1 ? '' 
 5056:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
 5057: 		.')').'</td>';
 5058: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 5059: 
 5060: 	    my %newrecord=();
 5061: 	    my @displayPts=();
 5062:             my %aggregate = ();
 5063:             my $aggregateflag = 0;
 5064:             if ($env{'form.HIDE'.$prob}) {
 5065:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 5066:                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
 5067:                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
 5068:                 $hideflag += $numchgs;
 5069:             }
 5070: 	    foreach my $partid (@{$parts}) {
 5071: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 5072: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 5073: 
 5074: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 5075: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 5076: 		my $partial = $newpts/$wgt;
 5077: 		my $score;
 5078: 		if ($partial > 0) {
 5079: 		    $score = 'correct_by_override';
 5080: 		} elsif ($newpts ne '') { #empty is taken as 0
 5081: 		    $score = 'incorrect_by_override';
 5082: 		}
 5083: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 5084: 		if ($dropMenu eq 'excused') {
 5085: 		    $partial = '';
 5086: 		    $score = 'excused';
 5087: 		} elsif ($dropMenu eq 'reset status'
 5088: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 5089: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 5090: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 5091: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 5092: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 5093: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 5094: 		    $changeflag++;
 5095: 		    $newpts = '';
 5096:                     
 5097:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 5098:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 5099:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 5100:                     if ($aggtries > 0) {
 5101:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 5102:                         $aggregateflag = 1;
 5103:                     }
 5104: 		}
 5105: 		my $display_part=&get_display_part($partid,$curRes->symb());
 5106: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 5107: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5108: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 5109: 		    '&nbsp;<br />';
 5110: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5111: 		     (($score eq 'excused') ? 'excused' : $newpts).
 5112: 		    '&nbsp;<br />';
 5113: 		$question++;
 5114: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 5115: 
 5116: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 5117: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 5118: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 5119: 		    if (scalar(keys(%newrecord)) > 0);
 5120: 
 5121: 		$changeflag++;
 5122: 	    }
 5123: 	    if (scalar(keys(%newrecord)) > 0) {
 5124: 		my %record = 
 5125: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 5126: 					     $udom,$uname);
 5127: 
 5128: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 5129: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 5130: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 5131: 		    $newrecord{'resource.CODE'} = '';
 5132: 		}
 5133: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 5134: 					$udom,$uname);
 5135: 		%record = &Apache::lonnet::restore($symbx,
 5136: 						   $env{'request.course.id'},
 5137: 						   $udom,$uname);
 5138: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 5139: 					     $cdom,$cnum,$udom,$uname);
 5140: 	    }
 5141: 	    
 5142:             if ($aggregateflag) {
 5143:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 5144:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 5145:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 5146:             }
 5147: 
 5148: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 5149: 		'<td valign="top">'.$displayPts[1].'</td>'.
 5150: 		&Apache::loncommon::end_data_table_row();
 5151: 
 5152: 	    $prob++;
 5153: 	}
 5154:         $curRes = $iterator->next();
 5155:     }
 5156: 
 5157:     $studentTable.=&Apache::loncommon::end_data_table();
 5158:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 5159: 		  &mt('The scores were changed for [quant,_1,problem].',
 5160: 		  $changeflag).'<br />');
 5161:     my $hidemsg=($hideflag == 0 ? '' :
 5162:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
 5163:                      $hideflag).'<br />');
 5164:     $request->print($hidemsg.$grademsg.$studentTable);
 5165: 
 5166:     return '';
 5167: }
 5168: 
 5169: #-------- end of section for handling grading by page/sequence ---------
 5170: #
 5171: #-------------------------------------------------------------------
 5172: 
 5173: #-------------------- Bubblesheet (Scantron) Grading -------------------
 5174: #
 5175: #------ start of section for handling grading by page/sequence ---------
 5176: 
 5177: =pod
 5178: 
 5179: =head1 Bubble sheet grading routines
 5180: 
 5181:   For this documentation:
 5182: 
 5183:    'scanline' refers to the full line of characters
 5184:    from the file that we are parsing that represents one entire sheet
 5185: 
 5186:    'bubble line' refers to the data
 5187:    representing the line of bubbles that are on the physical bubblesheet
 5188: 
 5189: 
 5190: The overall process is that a scanned in bubblesheet data is uploaded
 5191: into a course. When a user wants to grade, they select a
 5192: sequence/folder of resources, a file of bubblesheet info, and pick
 5193: one of the predefined configurations for what each scanline looks
 5194: like.
 5195: 
 5196: Next each scanline is checked for any errors of either 'missing
 5197: bubbles' (it's an error because it may have been mis-scanned
 5198: because too light bubbling), 'double bubble' (each bubble line should
 5199: have no more than one letter picked), invalid or duplicated CODE,
 5200: invalid student/employee ID
 5201: 
 5202: If the CODE option is used that determines the randomization of the
 5203: homework problems, either way the student/employee ID is looked up into a
 5204: username:domain.
 5205: 
 5206: During the validation phase the instructor can choose to skip scanlines. 
 5207: 
 5208: After the validation phase, there are now 3 bubblesheet files
 5209: 
 5210:   scantron_original_filename (unmodified original file)
 5211:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 5212:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 5213: 
 5214: Also there is a separate hash nohist_scantrondata that contains extra
 5215: correction information that isn't representable in the bubblesheet
 5216: file (see &scantron_getfile() for more information)
 5217: 
 5218: After all scanlines are either valid, marked as valid or skipped, then
 5219: foreach line foreach problem in the picked sequence, an ssi request is
 5220: made that simulates a user submitting their selected letter(s) against
 5221: the homework problem.
 5222: 
 5223: =over 4
 5224: 
 5225: 
 5226: 
 5227: =item defaultFormData
 5228: 
 5229:   Returns html hidden inputs used to hold context/default values.
 5230: 
 5231:  Arguments:
 5232:   $symb - $symb of the current resource 
 5233: 
 5234: =cut
 5235: 
 5236: sub defaultFormData {
 5237:     my ($symb)=@_;
 5238:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
 5239: }
 5240: 
 5241: 
 5242: =pod 
 5243: 
 5244: =item getSequenceDropDown
 5245: 
 5246:    Return html dropdown of possible sequences to grade
 5247:  
 5248:  Arguments:
 5249:    $symb - $symb of the current resource
 5250:    $map_error - ref to scalar which will container error if
 5251:                 $navmap object is unavailable in &getSymbMap().
 5252: 
 5253: =cut
 5254: 
 5255: sub getSequenceDropDown {
 5256:     my ($symb,$map_error)=@_;
 5257:     my $result='<select name="selectpage">'."\n";
 5258:     my ($titles,$symbx) = &getSymbMap($map_error);
 5259:     if (ref($map_error)) {
 5260:         return if ($$map_error);
 5261:     }
 5262:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 5263:     my $ctr=0;
 5264:     foreach (@$titles) {
 5265: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5266: 	$result.='<option value="'.$$symbx{$_}.'" '.
 5267: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 5268: 	    '>'.$showtitle.'</option>'."\n";
 5269: 	$ctr++;
 5270:     }
 5271:     $result.= '</select>';
 5272:     return $result;
 5273: }
 5274: 
 5275: my %bubble_lines_per_response;     # no. bubble lines for each response.
 5276:                                    # key is zero-based index - 0, 1, 2 ...
 5277: 
 5278: my %first_bubble_line;             # First bubble line no. for each bubble.
 5279: 
 5280: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 5281:                                    # matchresponse or rankresponse, where 
 5282:                                    # an individual response can have multiple 
 5283:                                    # lines
 5284: 
 5285: my %responsetype_per_response;     # responsetype for each response
 5286: 
 5287: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
 5288:                                    # numbered response. Needed when randomorder
 5289:                                    # or randompick are in use. Key is ID, value 
 5290:                                    # is response number.
 5291: 
 5292: # Save and restore the bubble lines array to the form env.
 5293: 
 5294: 
 5295: sub save_bubble_lines {
 5296:     foreach my $line (keys(%bubble_lines_per_response)) {
 5297: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 5298: 	$env{"form.scantron.first_bubble_line.$line"} =
 5299: 	    $first_bubble_line{$line};
 5300:         $env{"form.scantron.sub_bubblelines.$line"} = 
 5301:             $subdivided_bubble_lines{$line};
 5302:         $env{"form.scantron.responsetype.$line"} =
 5303:             $responsetype_per_response{$line};
 5304:     }
 5305:     foreach my $resid (keys(%masterseq_id_responsenum)) {
 5306:         my $line = $masterseq_id_responsenum{$resid};
 5307:         $env{"form.scantron.residpart.$line"} = $resid;
 5308:     }
 5309: }
 5310: 
 5311: 
 5312: sub restore_bubble_lines {
 5313:     my $line = 0;
 5314:     %bubble_lines_per_response = ();
 5315:     %masterseq_id_responsenum = ();
 5316:     while ($env{"form.scantron.bubblelines.$line"}) {
 5317: 	my $value = $env{"form.scantron.bubblelines.$line"};
 5318: 	$bubble_lines_per_response{$line} = $value;
 5319: 	$first_bubble_line{$line}  =
 5320: 	    $env{"form.scantron.first_bubble_line.$line"};
 5321:         $subdivided_bubble_lines{$line} =
 5322:             $env{"form.scantron.sub_bubblelines.$line"};
 5323:         $responsetype_per_response{$line} =
 5324:             $env{"form.scantron.responsetype.$line"};
 5325:         my $id = $env{"form.scantron.residpart.$line"};
 5326:         $masterseq_id_responsenum{$id} = $line;
 5327: 	$line++;
 5328:     }
 5329: }
 5330: 
 5331: =pod 
 5332: 
 5333: =item scantron_filenames
 5334: 
 5335:    Returns a list of the scantron files in the current course 
 5336: 
 5337: =cut
 5338: 
 5339: sub scantron_filenames {
 5340:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5341:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5342:     my $getpropath = 1;
 5343:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
 5344:                                                         $cname,$getpropath);
 5345:     my @possiblenames;
 5346:     if (ref($dirlist) eq 'ARRAY') {
 5347:         foreach my $filename (sort(@{$dirlist})) {
 5348: 	    ($filename)=split(/&/,$filename);
 5349: 	    if ($filename!~/^scantron_orig_/) { next ; }
 5350: 	    $filename=~s/^scantron_orig_//;
 5351: 	    push(@possiblenames,$filename);
 5352:         }
 5353:     }
 5354:     return @possiblenames;
 5355: }
 5356: 
 5357: =pod 
 5358: 
 5359: =item scantron_uploads
 5360: 
 5361:    Returns  html drop-down list of scantron files in current course.
 5362: 
 5363:  Arguments:
 5364:    $file2grade - filename to set as selected in the dropdown
 5365: 
 5366: =cut
 5367: 
 5368: sub scantron_uploads {
 5369:     my ($file2grade) = @_;
 5370:     my $result=	'<select name="scantron_selectfile">';
 5371:     $result.="<option></option>";
 5372:     foreach my $filename (sort(&scantron_filenames())) {
 5373: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 5374:     }
 5375:     $result.="</select>";
 5376:     return $result;
 5377: }
 5378: 
 5379: =pod 
 5380: 
 5381: =item scantron_scantab
 5382: 
 5383:   Returns html drop down of the scantron formats in the scantronformat.tab
 5384:   file.
 5385: 
 5386: =cut
 5387: 
 5388: sub scantron_scantab {
 5389:     my $result='<select name="scantron_format">'."\n";
 5390:     $result.='<option></option>'."\n";
 5391:     my @lines = &get_scantronformat_file();
 5392:     if (@lines > 0) {
 5393:         foreach my $line (@lines) {
 5394:             next if (($line =~ /^\#/) || ($line eq ''));
 5395: 	    my ($name,$descrip)=split(/:/,$line);
 5396: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 5397:         }
 5398:     }
 5399:     $result.='</select>'."\n";
 5400:     return $result;
 5401: }
 5402: 
 5403: =pod
 5404: 
 5405: =item get_scantronformat_file
 5406: 
 5407:   Returns an array containing lines from the scantron format file for
 5408:   the domain of the course.
 5409: 
 5410:   If a url for a custom.tab file is listed in domain's configuration.db, 
 5411:   lines are from this file.
 5412: 
 5413:   Otherwise, if a default.tab has been published in RES space by the 
 5414:   domainconfig user, lines are from this file.
 5415: 
 5416:   Otherwise, fall back to getting lines from the legacy file on the
 5417:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 5418: 
 5419: =cut
 5420: 
 5421: sub get_scantronformat_file {
 5422:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5423:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 5424:     my $gottab = 0;
 5425:     my @lines;
 5426:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5427:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5428:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5429:             if ($formatfile ne '-1') {
 5430:                 @lines = split("\n",$formatfile,-1);
 5431:                 $gottab = 1;
 5432:             }
 5433:         }
 5434:     }
 5435:     if (!$gottab) {
 5436:         my $confname = $cdom.'-domainconfig';
 5437:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5438:         my $formatfile =  &Apache::lonnet::getfile($default);
 5439:         if ($formatfile ne '-1') {
 5440:             @lines = split("\n",$formatfile,-1);
 5441:             $gottab = 1;
 5442:         }
 5443:     }
 5444:     if (!$gottab) {
 5445:         my @domains = &Apache::lonnet::current_machine_domains();
 5446:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5447:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5448:             @lines = <$fh>;
 5449:             close($fh);
 5450:         } else {
 5451:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 5452:             @lines = <$fh>;
 5453:             close($fh);
 5454:         }
 5455:     }
 5456:     return @lines;
 5457: }
 5458: 
 5459: =pod 
 5460: 
 5461: =item scantron_CODElist
 5462: 
 5463:   Returns html drop down of the saved CODE lists from current course,
 5464:   generated from earlier printings.
 5465: 
 5466: =cut
 5467: 
 5468: sub scantron_CODElist {
 5469:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5470:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5471:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5472:     my $namechoice='<option></option>';
 5473:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5474: 	if ($name =~ /^error: 2 /) { next; }
 5475: 	if ($name =~ /^type\0/) { next; }
 5476: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5477:     }
 5478:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5479:     return $namechoice;
 5480: }
 5481: 
 5482: =pod 
 5483: 
 5484: =item scantron_CODEunique
 5485: 
 5486:   Returns the html for "Each CODE to be used once" radio.
 5487: 
 5488: =cut
 5489: 
 5490: sub scantron_CODEunique {
 5491:     my $result='<span class="LC_nobreak">
 5492:                  <label><input type="radio" name="scantron_CODEunique"
 5493:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5494:                 </span>
 5495:                 <span class="LC_nobreak">
 5496:                  <label><input type="radio" name="scantron_CODEunique"
 5497:                         value="no" />'.&mt('No').' </label>
 5498:                 </span>';
 5499:     return $result;
 5500: }
 5501: 
 5502: =pod 
 5503: 
 5504: =item scantron_selectphase
 5505: 
 5506:   Generates the initial screen to start the bubblesheet process.
 5507:   Allows for - starting a grading run.
 5508:              - downloading existing scan data (original, corrected
 5509:                                                 or skipped info)
 5510: 
 5511:              - uploading new scan data
 5512: 
 5513:  Arguments:
 5514:   $r          - The Apache request object
 5515:   $file2grade - name of the file that contain the scanned data to score
 5516: 
 5517: =cut
 5518: 
 5519: sub scantron_selectphase {
 5520:     my ($r,$file2grade,$symb) = @_;
 5521:     if (!$symb) {return '';}
 5522:     my $map_error;
 5523:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 5524:     if ($map_error) {
 5525:         $r->print('<br />'.&navmap_errormsg().'<br />');
 5526:         return;
 5527:     }
 5528:     my $default_form_data=&defaultFormData($symb);
 5529:     my $file_selector=&scantron_uploads($file2grade);
 5530:     my $format_selector=&scantron_scantab();
 5531:     my $CODE_selector=&scantron_CODElist();
 5532:     my $CODE_unique=&scantron_CODEunique();
 5533:     my $result;
 5534: 
 5535:     $ssi_error = 0;
 5536: 
 5537:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5538:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5539: 
 5540: 	# Chunk of form to prompt for a scantron file upload.
 5541: 
 5542:         $r->print('
 5543:     <br />
 5544:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5545:        '.&Apache::loncommon::start_data_table_header_row().'
 5546:             <th>
 5547:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 5548:             </th>
 5549:        '.&Apache::loncommon::end_data_table_header_row().'
 5550:        '.&Apache::loncommon::start_data_table_row().'
 5551:             <td>
 5552: ');
 5553:     my $default_form_data=&defaultFormData($symb);
 5554:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5555:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5556:     $r->print(&Apache::lonhtmlcommon::scripttag('
 5557:     function checkUpload(formname) {
 5558: 	if (formname.upfile.value == "") {
 5559: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 5560: 	    return false;
 5561: 	}
 5562: 	formname.submit();
 5563:     }'));
 5564:     $r->print('
 5565:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5566:                 '.$default_form_data.'
 5567:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5568:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5569:                 <input name="command" value="scantronupload_save" type="hidden" />
 5570:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5571:                 <br />
 5572:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 5573:               </form>
 5574: ');
 5575: 
 5576:         $r->print('
 5577:             </td>
 5578:        '.&Apache::loncommon::end_data_table_row().'
 5579:        '.&Apache::loncommon::end_data_table().'
 5580: ');
 5581:     }
 5582: 
 5583:     # Chunk of form to prompt for a file to grade and how:
 5584: 
 5585:     $result.= '
 5586:     <br />
 5587:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5588:     <input type="hidden" name="command" value="scantron_warning" />
 5589:     '.$default_form_data.'
 5590:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5591:        '.&Apache::loncommon::start_data_table_header_row().'
 5592:             <th colspan="2">
 5593:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5594:             </th>
 5595:        '.&Apache::loncommon::end_data_table_header_row().'
 5596:        '.&Apache::loncommon::start_data_table_row().'
 5597:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5598:        '.&Apache::loncommon::end_data_table_row().'
 5599:        '.&Apache::loncommon::start_data_table_row().'
 5600:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 5601:        '.&Apache::loncommon::end_data_table_row().'
 5602:        '.&Apache::loncommon::start_data_table_row().'
 5603:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 5604:        '.&Apache::loncommon::end_data_table_row().'
 5605:        '.&Apache::loncommon::start_data_table_row().'
 5606:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5607:        '.&Apache::loncommon::end_data_table_row().'
 5608:        '.&Apache::loncommon::start_data_table_row().'
 5609:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5610:        '.&Apache::loncommon::end_data_table_row().'
 5611:        '.&Apache::loncommon::start_data_table_row().'
 5612: 	    <td> '.&mt('Options:').' </td>
 5613:             <td>
 5614: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5615:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5616:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5617: 	    </td>
 5618:        '.&Apache::loncommon::end_data_table_row().'
 5619:        '.&Apache::loncommon::start_data_table_row().'
 5620:             <td colspan="2">
 5621:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 5622:             </td>
 5623:        '.&Apache::loncommon::end_data_table_row().'
 5624:     '.&Apache::loncommon::end_data_table().'
 5625:     </form>
 5626: ';
 5627:    
 5628:     $r->print($result);
 5629: 
 5630: 
 5631: 
 5632:     # Chunk of the form that prompts to view a scoring office file,
 5633:     # corrected file, skipped records in a file.
 5634: 
 5635:     $r->print('
 5636:    <br />
 5637:    <form action="/adm/grades" name="scantron_download">
 5638:      '.$default_form_data.'
 5639:      <input type="hidden" name="command" value="scantron_download" />
 5640:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5641:        '.&Apache::loncommon::start_data_table_header_row().'
 5642:               <th>
 5643:                 &nbsp;'.&mt('Download a scoring office file').'
 5644:               </th>
 5645:        '.&Apache::loncommon::end_data_table_header_row().'
 5646:        '.&Apache::loncommon::start_data_table_row().'
 5647:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5648:                 <br />
 5649:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5650:        '.&Apache::loncommon::end_data_table_row().'
 5651:      '.&Apache::loncommon::end_data_table().'
 5652:    </form>
 5653:    <br />
 5654: ');
 5655: 
 5656:     &Apache::lonpickcode::code_list($r,2);
 5657: 
 5658:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
 5659:              $default_form_data."\n".
 5660:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5661:              &Apache::loncommon::start_data_table_header_row()."\n".
 5662:              '<th colspan="2">
 5663:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 5664:              '</th>'."\n".
 5665:               &Apache::loncommon::end_data_table_header_row()."\n".
 5666:               &Apache::loncommon::start_data_table_row()."\n".
 5667:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5668:               '<td> '.$sequence_selector.' </td>'.
 5669:               &Apache::loncommon::end_data_table_row()."\n".
 5670:               &Apache::loncommon::start_data_table_row()."\n".
 5671:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5672:               '<td> '.$file_selector.' </td>'."\n".
 5673:               &Apache::loncommon::end_data_table_row()."\n".
 5674:               &Apache::loncommon::start_data_table_row()."\n".
 5675:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5676:               '<td> '.$format_selector.' </td>'."\n".
 5677:               &Apache::loncommon::end_data_table_row()."\n".
 5678:               &Apache::loncommon::start_data_table_row()."\n".
 5679:               '<td> '.&mt('Options').' </td>'."\n".
 5680:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 5681:               &Apache::loncommon::end_data_table_row()."\n".
 5682:               &Apache::loncommon::start_data_table_row()."\n".
 5683:               '<td colspan="2">'."\n".
 5684:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5685:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 5686:               '</td>'."\n".
 5687:               &Apache::loncommon::end_data_table_row()."\n".
 5688:               &Apache::loncommon::end_data_table()."\n".
 5689:               '</form><br />');
 5690:     return;
 5691: }
 5692: 
 5693: =pod
 5694: 
 5695: =item get_scantron_config
 5696: 
 5697:    Parse and return the bubblesheet configuration line selected as a
 5698:    hash of configuration file fields.
 5699: 
 5700:  Arguments:
 5701:     which - the name of the configuration to parse from the file.
 5702: 
 5703: 
 5704:  Returns:
 5705:             If the named configuration is not in the file, an empty
 5706:             hash is returned.
 5707:     a hash with the fields
 5708:       name         - internal name for the this configuration setup
 5709:       description  - text to display to operator that describes this config
 5710:       CODElocation - if 0 or the string 'none'
 5711:                           - no CODE exists for this config
 5712:                      if -1 || the string 'letter'
 5713:                           - a CODE exists for this config and is
 5714:                             a string of letters
 5715:                      Unsupported value (but planned for future support)
 5716:                           if a positive integer
 5717:                                - The CODE exists as the first n items from
 5718:                                  the question section of the form
 5719:                           if the string 'number'
 5720:                                - The CODE exists for this config and is
 5721:                                  a string of numbers
 5722:       CODEstart   - (only matter if a CODE exists) column in the line where
 5723:                      the CODE starts
 5724:       CODElength  - length of the CODE
 5725:       IDstart     - column where the student/employee ID starts
 5726:       IDlength    - length of the student/employee ID info
 5727:       Qstart      - column where the information from the bubbled
 5728:                     'questions' start
 5729:       Qlength     - number of columns comprising a single bubble line from
 5730:                     the sheet. (usually either 1 or 10)
 5731:       Qon         - either a single character representing the character used
 5732:                     to signal a bubble was chosen in the positional setup, or
 5733:                     the string 'letter' if the letter of the chosen bubble is
 5734:                     in the final, or 'number' if a number representing the
 5735:                     chosen bubble is in the file (1->A 0->J)
 5736:       Qoff        - the character used to represent that a bubble was
 5737:                     left blank
 5738:       PaperID     - if the scanning process generates a unique number for each
 5739:                     sheet scanned the column that this ID number starts in
 5740:       PaperIDlength - number of columns that comprise the unique ID number
 5741:                       for the sheet of paper
 5742:       FirstName   - column that the first name starts in
 5743:       FirstNameLength - number of columns that the first name spans
 5744:  
 5745:       LastName    - column that the last name starts in
 5746:       LastNameLength - number of columns that the last name spans
 5747:       BubblesPerRow - number of bubbles available in each row used to 
 5748:                       bubble an answer. (If not specified, 10 assumed).
 5749: 
 5750: =cut
 5751: 
 5752: sub get_scantron_config {
 5753:     my ($which) = @_;
 5754:     my @lines = &get_scantronformat_file();
 5755:     my %config;
 5756:     #FIXME probably should move to XML it has already gotten a bit much now
 5757:     foreach my $line (@lines) {
 5758: 	my ($name,$descrip)=split(/:/,$line);
 5759: 	if ($name ne $which ) { next; }
 5760: 	chomp($line);
 5761: 	my @config=split(/:/,$line);
 5762: 	$config{'name'}=$config[0];
 5763: 	$config{'description'}=$config[1];
 5764: 	$config{'CODElocation'}=$config[2];
 5765: 	$config{'CODEstart'}=$config[3];
 5766: 	$config{'CODElength'}=$config[4];
 5767: 	$config{'IDstart'}=$config[5];
 5768: 	$config{'IDlength'}=$config[6];
 5769: 	$config{'Qstart'}=$config[7];
 5770:  	$config{'Qlength'}=$config[8];
 5771: 	$config{'Qoff'}=$config[9];
 5772: 	$config{'Qon'}=$config[10];
 5773: 	$config{'PaperID'}=$config[11];
 5774: 	$config{'PaperIDlength'}=$config[12];
 5775: 	$config{'FirstName'}=$config[13];
 5776: 	$config{'FirstNamelength'}=$config[14];
 5777: 	$config{'LastName'}=$config[15];
 5778: 	$config{'LastNamelength'}=$config[16];
 5779:         $config{'BubblesPerRow'}=$config[17];
 5780: 	last;
 5781:     }
 5782:     return %config;
 5783: }
 5784: 
 5785: =pod 
 5786: 
 5787: =item username_to_idmap
 5788: 
 5789:     creates a hash keyed by student/employee ID with values of the corresponding
 5790:     student username:domain.
 5791: 
 5792:   Arguments:
 5793: 
 5794:     $classlist - reference to the class list hash. This is a hash
 5795:                  keyed by student name:domain  whose elements are references
 5796:                  to arrays containing various chunks of information
 5797:                  about the student. (See loncoursedata for more info).
 5798: 
 5799:   Returns
 5800:     %idmap - the constructed hash
 5801: 
 5802: =cut
 5803: 
 5804: sub username_to_idmap {
 5805:     my ($classlist)= @_;
 5806:     my %idmap;
 5807:     foreach my $student (keys(%$classlist)) {
 5808: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5809: 	    $student;
 5810:     }
 5811:     return %idmap;
 5812: }
 5813: 
 5814: =pod
 5815: 
 5816: =item scantron_fixup_scanline
 5817: 
 5818:    Process a requested correction to a scanline.
 5819: 
 5820:   Arguments:
 5821:     $scantron_config   - hash from &get_scantron_config()
 5822:     $scan_data         - hash of correction information 
 5823:                           (see &scantron_getfile())
 5824:     $line              - existing scanline
 5825:     $whichline         - line number of the passed in scanline
 5826:     $field             - type of change to process 
 5827:                          (either 
 5828:                           'ID'     -> correct the student/employee ID
 5829:                           'CODE'   -> correct the CODE
 5830:                           'answer' -> fixup the submitted answers)
 5831:     
 5832:    $args               - hash of additional info,
 5833:                           - 'ID' 
 5834:                                'newid' -> studentID to use in replacement
 5835:                                           of existing one
 5836:                           - 'CODE' 
 5837:                                'CODE_ignore_dup' - set to true if duplicates
 5838:                                                    should be ignored.
 5839: 	                       'CODE' - is new code or 'use_unfound'
 5840:                                         if the existing unfound code should
 5841:                                         be used as is
 5842:                           - 'answer'
 5843:                                'response' - new answer or 'none' if blank
 5844:                                'question' - the bubble line to change
 5845:                                'questionnum' - the question identifier,
 5846:                                                may include subquestion. 
 5847: 
 5848:   Returns:
 5849:     $line - the modified scanline
 5850: 
 5851:   Side effects: 
 5852:     $scan_data - may be updated
 5853: 
 5854: =cut
 5855: 
 5856: 
 5857: sub scantron_fixup_scanline {
 5858:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5859:     if ($field eq 'ID') {
 5860: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5861: 	    return ($line,1,'New value too large');
 5862: 	}
 5863: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5864: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5865: 				     $args->{'newid'});
 5866: 	}
 5867: 	substr($line,$$scantron_config{'IDstart'}-1,
 5868: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5869: 	if ($args->{'newid'}=~/^\s*$/) {
 5870: 	    &scan_data($scan_data,"$whichline.user",
 5871: 		       $args->{'username'}.':'.$args->{'domain'});
 5872: 	}
 5873:     } elsif ($field eq 'CODE') {
 5874: 	if ($args->{'CODE_ignore_dup'}) {
 5875: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5876: 	}
 5877: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5878: 	if ($args->{'CODE'} ne 'use_unfound') {
 5879: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5880: 		return ($line,1,'New CODE value too large');
 5881: 	    }
 5882: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5883: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5884: 	    }
 5885: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5886: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5887: 	}
 5888:     } elsif ($field eq 'answer') {
 5889: 	my $length=$scantron_config->{'Qlength'};
 5890: 	my $off=$scantron_config->{'Qoff'};
 5891: 	my $on=$scantron_config->{'Qon'};
 5892: 	my $answer=${off}x$length;
 5893: 	if ($args->{'response'} eq 'none') {
 5894: 	    &scan_data($scan_data,
 5895: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5896: 	} else {
 5897: 	    if ($on eq 'letter') {
 5898: 		my @alphabet=('A'..'Z');
 5899: 		$answer=$alphabet[$args->{'response'}];
 5900: 	    } elsif ($on eq 'number') {
 5901: 		$answer=$args->{'response'}+1;
 5902: 		if ($answer == 10) { $answer = '0'; }
 5903: 	    } else {
 5904: 		substr($answer,$args->{'response'},1)=$on;
 5905: 	    }
 5906: 	    &scan_data($scan_data,
 5907: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5908: 	}
 5909: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5910: 	substr($line,$where-1,$length)=$answer;
 5911:     }
 5912:     return $line;
 5913: }
 5914: 
 5915: =pod
 5916: 
 5917: =item scan_data
 5918: 
 5919:     Edit or look up  an item in the scan_data hash.
 5920: 
 5921:   Arguments:
 5922:     $scan_data  - The hash (see scantron_getfile)
 5923:     $key        - shorthand of the key to edit (actual key is
 5924:                   scantronfilename_key).
 5925:     $data        - New value of the hash entry.
 5926:     $delete      - If true, the entry is removed from the hash.
 5927: 
 5928:   Returns:
 5929:     The new value of the hash table field (undefined if deleted).
 5930: 
 5931: =cut
 5932: 
 5933: 
 5934: sub scan_data {
 5935:     my ($scan_data,$key,$value,$delete)=@_;
 5936:     my $filename=$env{'form.scantron_selectfile'};
 5937:     if (defined($value)) {
 5938: 	$scan_data->{$filename.'_'.$key} = $value;
 5939:     }
 5940:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5941:     return $scan_data->{$filename.'_'.$key};
 5942: }
 5943: 
 5944: # ----- These first few routines are general use routines.----
 5945: 
 5946: # Return the number of occurences of a pattern in a string.
 5947: 
 5948: sub occurence_count {
 5949:     my ($string, $pattern) = @_;
 5950: 
 5951:     my @matches = ($string =~ /$pattern/g);
 5952: 
 5953:     return scalar(@matches);
 5954: }
 5955: 
 5956: 
 5957: # Take a string known to have digits and convert all the
 5958: # digits into letters in the range J,A..I.
 5959: 
 5960: sub digits_to_letters {
 5961:     my ($input) = @_;
 5962: 
 5963:     my @alphabet = ('J', 'A'..'I');
 5964: 
 5965:     my @input    = split(//, $input);
 5966:     my $output ='';
 5967:     for (my $i = 0; $i < scalar(@input); $i++) {
 5968: 	if ($input[$i] =~ /\d/) {
 5969: 	    $output .= $alphabet[$input[$i]];
 5970: 	} else {
 5971: 	    $output .= $input[$i];
 5972: 	}
 5973:     }
 5974:     return $output;
 5975: }
 5976: 
 5977: =pod 
 5978: 
 5979: =item scantron_parse_scanline
 5980: 
 5981:   Decodes a scanline from the selected bubblesheet file
 5982: 
 5983:  Arguments:
 5984:     line             - The text of the bubblesheet file line to process
 5985:     whichline        - Line number
 5986:     scantron_config  - Hash describing the format of the bubblesheet lines.
 5987:     scan_data        - Hash of extra information about the scanline
 5988:                        (see scantron_getfile for more information)
 5989:     just_header      - True if should not process question answers but only
 5990:                        the stuff to the left of the answers.
 5991:     randomorder      - True if randomorder in use
 5992:     randompick       - True if randompick in use
 5993:     sequence         - Exam folder URL
 5994:     master_seq       - Ref to array containing symbs in exam folder
 5995:     symb_to_resource - Ref to hash of symbs for resources in exam folder
 5996:                        (corresponding values are resource objects)
 5997:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
 5998:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
 5999:                        are refs to an array of resource objects, ordered
 6000:                        according to order used for CODE, when randomorder
 6001:                        and or randompick are in use.
 6002:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
 6003:                        for current line to question number used for same question
 6004:                         in "Master Sequence" (as seen by Course Coordinator).
 6005:     startline        - Ref to hash where key is question number (0 is first)
 6006:                        and value is number of first bubble line for current 
 6007:                        student or code-based randompick and/or randomorder.
 6008:     totalref         - Ref of scalar used to score total number of bubble
 6009:                        lines needed for responses in a scan line (used when
 6010:                        randompick in use. 
 6011:     
 6012:  Returns:
 6013:    Hash containing the result of parsing the scanline
 6014: 
 6015:    Keys are all proceeded by the string 'scantron.'
 6016: 
 6017:        CODE    - the CODE in use for this scanline
 6018:        useCODE - 1 if the CODE is invalid but it usage has been forced
 6019:                  by the operator
 6020:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 6021:                             CODEs were selected, but the usage has been
 6022:                             forced by the operator
 6023:        ID  - student/employee ID
 6024:        PaperID - if used, the ID number printed on the sheet when the 
 6025:                  paper was scanned
 6026:        FirstName - first name from the sheet
 6027:        LastName  - last name from the sheet
 6028: 
 6029:      if just_header was not true these key may also exist
 6030: 
 6031:        missingerror - a list of bubble ranges that are considered to be answers
 6032:                       to a single question that don't have any bubbles filled in.
 6033:                       Of the form questionnumber:firstbubblenumber:count.
 6034:        doubleerror  - a list of bubble ranges that are considered to be answers
 6035:                       to a single question that have more than one bubble filled in.
 6036:                       Of the form questionnumber::firstbubblenumber:count
 6037:    
 6038:                 In the above, count is the number of bubble responses in the
 6039:                 input line needed to represent the possible answers to the question.
 6040:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 6041:                 per line would have count = 2.
 6042: 
 6043:        maxquest     - the number of the last bubble line that was parsed
 6044: 
 6045:        (<number> starts at 1)
 6046:        <number>.answer - zero or more letters representing the selected
 6047:                          letters from the scanline for the bubble line 
 6048:                          <number>.
 6049:                          if blank there was either no bubble or there where
 6050:                          multiple bubbles, (consult the keys missingerror and
 6051:                          doubleerror if this is an error condition)
 6052: 
 6053: =cut
 6054: 
 6055: sub scantron_parse_scanline {
 6056:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
 6057:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
 6058:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
 6059: 
 6060:     my %record;
 6061:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
 6062:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 6063: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 6064: 	if ($$scantron_config{'CODElocation'} < 0 ||
 6065: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 6066: 	    $$scantron_config{'CODElocation'} eq 'number') {
 6067: 	    $record{'scantron.CODE'}=substr($data,
 6068: 					    $$scantron_config{'CODEstart'}-1,
 6069: 					    $$scantron_config{'CODElength'});
 6070: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 6071: 		$record{'scantron.useCODE'}=1;
 6072: 	    }
 6073: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 6074: 		$record{'scantron.CODE_ignore_dup'}=1;
 6075: 	    }
 6076: 	} else {
 6077: 	    #FIXME interpret first N questions
 6078: 	}
 6079:     }
 6080:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 6081: 				  $$scantron_config{'IDlength'});
 6082:     $record{'scantron.PaperID'}=
 6083: 	substr($data,$$scantron_config{'PaperID'}-1,
 6084: 	       $$scantron_config{'PaperIDlength'});
 6085:     $record{'scantron.FirstName'}=
 6086: 	substr($data,$$scantron_config{'FirstName'}-1,
 6087: 	       $$scantron_config{'FirstNamelength'});
 6088:     $record{'scantron.LastName'}=
 6089: 	substr($data,$$scantron_config{'LastName'}-1,
 6090: 	       $$scantron_config{'LastNamelength'});
 6091:     if ($just_header) { return \%record; }
 6092: 
 6093:     my @alphabet=('A'..'Z');
 6094:     my $questnum=0;
 6095:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 6096: 
 6097:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 6098:     if ($randompick || $randomorder) {
 6099:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
 6100:                                          $master_seq,$symb_to_resource,
 6101:                                          $partids_by_symb,$orderedforcode,
 6102:                                          $respnumlookup,$startline);
 6103:         if ($total) {
 6104:             $lastpos = $total*$$scantron_config{'Qlength'}; 
 6105:         }
 6106:         if (ref($totalref)) {
 6107:             $$totalref = $total;
 6108:         }
 6109:     }
 6110:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 6111:     chomp($questions);		# Get rid of any trailing \n.
 6112:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 6113:     while (length($questions)) {
 6114:         my $answers_needed;
 6115:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6116:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
 6117:         } else {
 6118: 	    $answers_needed = $bubble_lines_per_response{$questnum};
 6119:         }
 6120:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 6121:                              || 1;
 6122:         $questnum++;
 6123:         my $quest_id = $questnum;
 6124:         my $currentquest = substr($questions,0,$answer_length);
 6125:         $questions       = substr($questions,$answer_length);
 6126:         if (length($currentquest) < $answer_length) { next; }
 6127: 
 6128:         my $subdivided;
 6129:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6130:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
 6131:         } else {
 6132:             $subdivided = $subdivided_bubble_lines{$questnum-1};
 6133:         }
 6134:         if ($subdivided =~ /,/) {
 6135:             my $subquestnum = 1;
 6136:             my $subquestions = $currentquest;
 6137:             my @subanswers_needed = split(/,/,$subdivided);
 6138:             foreach my $subans (@subanswers_needed) {
 6139:                 my $subans_length =
 6140:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 6141:                 my $currsubquest = substr($subquestions,0,$subans_length);
 6142:                 $subquestions   = substr($subquestions,$subans_length);
 6143:                 $quest_id = "$questnum.$subquestnum";
 6144:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 6145:                     ($$scantron_config{'Qon'} eq 'number')) {
 6146:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 6147:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6148:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6149:                         $randomorder,$randompick,$respnumlookup);
 6150:                 } else {
 6151:                     $ansnum = &scantron_validator_positional($ansnum,
 6152:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6153:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6154:                         $randomorder,$randompick,$respnumlookup);
 6155:                 }
 6156:                 $subquestnum ++;
 6157:             }
 6158:         } else {
 6159:             if (($$scantron_config{'Qon'} eq 'letter') ||
 6160:                 ($$scantron_config{'Qon'} eq 'number')) {
 6161:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 6162:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6163:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6164:                     $randomorder,$randompick,$respnumlookup);
 6165:             } else {
 6166:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 6167:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6168:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6169:                     $randomorder,$randompick,$respnumlookup);
 6170:             }
 6171:         }
 6172:     }
 6173:     $record{'scantron.maxquest'}=$questnum;
 6174:     return \%record;
 6175: }
 6176: 
 6177: sub get_master_seq {
 6178:     my ($resources,$master_seq,$symb_to_resource) = @_;
 6179:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') && 
 6180:                    (ref($symb_to_resource) eq 'HASH'));
 6181:     my $resource_error;
 6182:     foreach my $resource (@{$resources}) {
 6183:         my $ressymb;
 6184:         if (ref($resource)) {
 6185:             $ressymb = $resource->symb();
 6186:             push(@{$master_seq},$ressymb);
 6187:             $symb_to_resource->{$ressymb} = $resource;
 6188:         } else {
 6189:             $resource_error = 1;
 6190:             last;
 6191:         }
 6192:     }
 6193:     return $resource_error;
 6194: }
 6195: 
 6196: sub get_respnum_lookups {
 6197:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
 6198:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
 6199:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
 6200:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
 6201:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
 6202:                    (ref($startline) eq 'HASH'));
 6203:     my ($user,$scancode);
 6204:     if ((exists($record->{'scantron.CODE'})) &&
 6205:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
 6206:         $scancode = $record->{'scantron.CODE'};
 6207:     } else {
 6208:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
 6209:     }
 6210:     my @mapresources =
 6211:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
 6212:                      $orderedforcode);
 6213:     my $total = 0;
 6214:     my $count = 0;
 6215:     foreach my $resource (@mapresources) {
 6216:         my $id = $resource->id();
 6217:         my $symb = $resource->symb();
 6218:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
 6219:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
 6220:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
 6221:                 if ($respnum ne '') {
 6222:                     $respnumlookup->{$count} = $respnum;
 6223:                     $startline->{$count} = $total;
 6224:                     $total += $bubble_lines_per_response{$respnum};
 6225:                     $count ++;
 6226:                 }
 6227:             }
 6228:         }
 6229:     }
 6230:     return $total;
 6231: }
 6232: 
 6233: sub scantron_validator_lettnum {
 6234:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 6235:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
 6236:         $randompick,$respnumlookup) = @_;
 6237: 
 6238:     # Qon 'letter' implies for each slot in currquest we have:
 6239:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 6240:     #    about anything else (esp. a value of Qoff) for missing
 6241:     #    bubbles.
 6242:     #
 6243:     # Qon 'number' implies each slot gives a digit that indexes the
 6244:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 6245:     #    and * or ? for double bubbles on a single line.
 6246:     #
 6247: 
 6248:     my $matchon;
 6249:     if ($$scantron_config{'Qon'} eq 'letter') {
 6250:         $matchon = '[A-Z]';
 6251:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 6252:         $matchon = '\d';
 6253:     }
 6254:     my $occurrences = 0;
 6255:     my $responsenum = $questnum-1;
 6256:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6257:        $responsenum = $respnumlookup->{$questnum-1} 
 6258:     }
 6259:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6260:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6261:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6262:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6263:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6264:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6265:         my @singlelines = split('',$currquest);
 6266:         foreach my $entry (@singlelines) {
 6267:             $occurrences = &occurence_count($entry,$matchon);
 6268:             if ($occurrences > 1) {
 6269:                 last;
 6270:             }
 6271:         }
 6272:     } else {
 6273:         $occurrences = &occurence_count($currquest,$matchon); 
 6274:     }
 6275:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 6276:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6277:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6278:             my $bubble = substr($currquest,$ans,1);
 6279:             if ($bubble =~ /$matchon/ ) {
 6280:                 if ($$scantron_config{'Qon'} eq 'number') {
 6281:                     if ($bubble == 0) {
 6282:                         $bubble = 10; 
 6283:                     }
 6284:                     $record->{"scantron.$ansnum.answer"} = 
 6285:                         $alphabet->[$bubble-1];
 6286:                 } else {
 6287:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 6288:                 }
 6289:             } else {
 6290:                 $record->{"scantron.$ansnum.answer"}='';
 6291:             }
 6292:             $ansnum++;
 6293:         }
 6294:     } elsif (!defined($currquest)
 6295:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 6296:             || (&occurence_count($currquest,$matchon) == 0)) {
 6297:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6298:             $record->{"scantron.$ansnum.answer"}='';
 6299:             $ansnum++;
 6300:         }
 6301:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6302:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 6303:         }
 6304:     } else {
 6305:         if ($$scantron_config{'Qon'} eq 'number') {
 6306:             $currquest = &digits_to_letters($currquest);            
 6307:         }
 6308:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6309:             my $bubble = substr($currquest,$ans,1);
 6310:             $record->{"scantron.$ansnum.answer"} = $bubble;
 6311:             $ansnum++;
 6312:         }
 6313:     }
 6314:     return $ansnum;
 6315: }
 6316: 
 6317: sub scantron_validator_positional {
 6318:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 6319:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
 6320:         $randomorder,$randompick,$respnumlookup) = @_;
 6321: 
 6322:     # Otherwise there's a positional notation;
 6323:     # each bubble line requires Qlength items, and there are filled in
 6324:     # bubbles for each case where there 'Qon' characters.
 6325:     #
 6326: 
 6327:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 6328: 
 6329:     # If the split only gives us one element.. the full length of the
 6330:     # answer string, no bubbles are filled in:
 6331: 
 6332:     if ($answers_needed eq '') {
 6333:         return;
 6334:     }
 6335: 
 6336:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 6337:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6338:             $record->{"scantron.$ansnum.answer"}='';
 6339:             $ansnum++;
 6340:         }
 6341:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6342:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 6343:         }
 6344:     } elsif (scalar(@array) == 2) {
 6345:         my $location = length($array[0]);
 6346:         my $line_num = int($location / $$scantron_config{'Qlength'});
 6347:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 6348:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6349:             if ($ans eq $line_num) {
 6350:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 6351:             } else {
 6352:                 $record->{"scantron.$ansnum.answer"} = ' ';
 6353:             }
 6354:             $ansnum++;
 6355:          }
 6356:     } else {
 6357:         #  If there's more than one instance of a bubble character
 6358:         #  That's a double bubble; with positional notation we can
 6359:         #  record all the bubbles filled in as well as the
 6360:         #  fact this response consists of multiple bubbles.
 6361:         #
 6362:         my $responsenum = $questnum-1;
 6363:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6364:             $responsenum = $respnumlookup->{$questnum-1}
 6365:         }
 6366:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6367:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6368:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6369:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6370:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6371:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6372:             my $doubleerror = 0;
 6373:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 6374:                    (!$doubleerror)) {
 6375:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 6376:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 6377:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 6378:                if (length(@currarray) > 2) {
 6379:                    $doubleerror = 1;
 6380:                } 
 6381:             }
 6382:             if ($doubleerror) {
 6383:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6384:             }
 6385:         } else {
 6386:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6387:         }
 6388:         my $item = $ansnum;
 6389:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6390:             $record->{"scantron.$item.answer"} = '';
 6391:             $item ++;
 6392:         }
 6393: 
 6394:         my @ans=@array;
 6395:         my $i=0;
 6396:         my $increment = 0;
 6397:         while ($#ans) {
 6398:             $i+=length($ans[0]) + $increment;
 6399:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 6400:             my $bubble = $i%$$scantron_config{'Qlength'};
 6401:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 6402:             shift(@ans);
 6403:             $increment = 1;
 6404:         }
 6405:         $ansnum += $answers_needed;
 6406:     }
 6407:     return $ansnum;
 6408: }
 6409: 
 6410: =pod
 6411: 
 6412: =item scantron_add_delay
 6413: 
 6414:    Adds an error message that occurred during the grading phase to a
 6415:    queue of messages to be shown after grading pass is complete
 6416: 
 6417:  Arguments:
 6418:    $delayqueue  - arrary ref of hash ref of error messages
 6419:    $scanline    - the scanline that caused the error
 6420:    $errormesage - the error message
 6421:    $errorcode   - a numeric code for the error
 6422: 
 6423:  Side Effects:
 6424:    updates the $delayqueue to have a new hash ref of the error
 6425: 
 6426: =cut
 6427: 
 6428: sub scantron_add_delay {
 6429:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 6430:     push(@$delayqueue,
 6431: 	 {'line' => $scanline, 'emsg' => $errormessage,
 6432: 	  'ecode' => $errorcode }
 6433: 	 );
 6434: }
 6435: 
 6436: =pod
 6437: 
 6438: =item scantron_find_student
 6439: 
 6440:    Finds the username for the current scanline
 6441: 
 6442:   Arguments:
 6443:    $scantron_record - hash result from scantron_parse_scanline
 6444:    $scan_data       - hash of correction information 
 6445:                       (see &scantron_getfile() form more information)
 6446:    $idmap           - hash from &username_to_idmap()
 6447:    $line            - number of current scanline
 6448:  
 6449:   Returns:
 6450:    Either 'username:domain' or undef if unknown
 6451: 
 6452: =cut
 6453: 
 6454: sub scantron_find_student {
 6455:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 6456:     my $scanID=$$scantron_record{'scantron.ID'};
 6457:     if ($scanID =~ /^\s*$/) {
 6458:  	return &scan_data($scan_data,"$line.user");
 6459:     }
 6460:     foreach my $id (keys(%$idmap)) {
 6461:  	if (lc($id) eq lc($scanID)) {
 6462:  	    return $$idmap{$id};
 6463:  	}
 6464:     }
 6465:     return undef;
 6466: }
 6467: 
 6468: =pod
 6469: 
 6470: =item scantron_filter
 6471: 
 6472:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 6473:    hidden resources was selected
 6474: 
 6475: =cut
 6476: 
 6477: sub scantron_filter {
 6478:     my ($curres)=@_;
 6479: 
 6480:     if (ref($curres) && $curres->is_problem()) {
 6481: 	# if the user has asked to not have either hidden
 6482: 	# or 'randomout' controlled resources to be graded
 6483: 	# don't include them
 6484: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6485: 	    && $curres->randomout) {
 6486: 	    return 0;
 6487: 	}
 6488: 	return 1;
 6489:     }
 6490:     return 0;
 6491: }
 6492: 
 6493: =pod
 6494: 
 6495: =item scantron_process_corrections
 6496: 
 6497:    Gets correction information out of submitted form data and corrects
 6498:    the scanline
 6499: 
 6500: =cut
 6501: 
 6502: sub scantron_process_corrections {
 6503:     my ($r) = @_;
 6504:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6505:     my ($scanlines,$scan_data)=&scantron_getfile();
 6506:     my $classlist=&Apache::loncoursedata::get_classlist();
 6507:     my $which=$env{'form.scantron_line'};
 6508:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 6509:     my ($skip,$err,$errmsg);
 6510:     if ($env{'form.scantron_skip_record'}) {
 6511: 	$skip=1;
 6512:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 6513: 	my $newstudent=$env{'form.scantron_username'}.':'.
 6514: 	    $env{'form.scantron_domain'};
 6515: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 6516: 	($line,$err,$errmsg)=
 6517: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6518: 				     'ID',{'newid'=>$newid,
 6519: 				    'username'=>$env{'form.scantron_username'},
 6520: 				    'domain'=>$env{'form.scantron_domain'}});
 6521:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 6522: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 6523: 	my $newCODE;
 6524: 	my %args;
 6525: 	if      ($resolution eq 'use_unfound') {
 6526: 	    $newCODE='use_unfound';
 6527: 	} elsif ($resolution eq 'use_found') {
 6528: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6529: 	} elsif ($resolution eq 'use_typed') {
 6530: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6531: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6532: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6533: 	}
 6534: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6535: 	    $args{'CODE_ignore_dup'}=1;
 6536: 	}
 6537: 	$args{'CODE'}=$newCODE;
 6538: 	($line,$err,$errmsg)=
 6539: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6540: 				     'CODE',\%args);
 6541:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6542: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6543: 	    ($line,$err,$errmsg)=
 6544: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6545: 					 $which,'answer',
 6546: 					 { 'question'=>$question,
 6547: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6548:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6549: 	    if ($err) { last; }
 6550: 	}
 6551:     }
 6552:     if ($err) {
 6553:         $r->print(
 6554:             '<p class="LC_error">'
 6555:            .&mt('Unable to accept last correction, an error occurred: [_1]',
 6556:                 $errmsg)
 6557:            .'</p>');
 6558:     } else {
 6559: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 6560: 	&scantron_putfile($scanlines,$scan_data);
 6561:     }
 6562: }
 6563: 
 6564: =pod
 6565: 
 6566: =item reset_skipping_status
 6567: 
 6568:    Forgets the current set of remember skipped scanlines (and thus
 6569:    reverts back to considering all lines in the
 6570:    scantron_skipped_<filename> file)
 6571: 
 6572: =cut
 6573: 
 6574: sub reset_skipping_status {
 6575:     my ($scanlines,$scan_data)=&scantron_getfile();
 6576:     &scan_data($scan_data,'remember_skipping',undef,1);
 6577:     &scantron_putfile(undef,$scan_data);
 6578: }
 6579: 
 6580: =pod
 6581: 
 6582: =item start_skipping
 6583: 
 6584:    Marks a scanline to be skipped. 
 6585: 
 6586: =cut
 6587: 
 6588: sub start_skipping {
 6589:     my ($scan_data,$i)=@_;
 6590:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6591:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6592: 	$remembered{$i}=2;
 6593:     } else {
 6594: 	$remembered{$i}=1;
 6595:     }
 6596:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6597: }
 6598: 
 6599: =pod
 6600: 
 6601: =item should_be_skipped
 6602: 
 6603:    Checks whether a scanline should be skipped.
 6604: 
 6605: =cut
 6606: 
 6607: sub should_be_skipped {
 6608:     my ($scanlines,$scan_data,$i)=@_;
 6609:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6610: 	# not redoing old skips
 6611: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6612: 	return 0;
 6613:     }
 6614:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6615: 
 6616:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6617: 	return 0;
 6618:     }
 6619:     return 1;
 6620: }
 6621: 
 6622: =pod
 6623: 
 6624: =item remember_current_skipped
 6625: 
 6626:    Discovers what scanlines are in the scantron_skipped_<filename>
 6627:    file and remembers them into scan_data for later use.
 6628: 
 6629: =cut
 6630: 
 6631: sub remember_current_skipped {
 6632:     my ($scanlines,$scan_data)=&scantron_getfile();
 6633:     my %to_remember;
 6634:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6635: 	if ($scanlines->{'skipped'}[$i]) {
 6636: 	    $to_remember{$i}=1;
 6637: 	}
 6638:     }
 6639: 
 6640:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6641:     &scantron_putfile(undef,$scan_data);
 6642: }
 6643: 
 6644: =pod
 6645: 
 6646: =item check_for_error
 6647: 
 6648:     Checks if there was an error when attempting to remove a specific
 6649:     scantron_.. bubblesheet data file. Prints out an error if
 6650:     something went wrong.
 6651: 
 6652: =cut
 6653: 
 6654: sub check_for_error {
 6655:     my ($r,$result)=@_;
 6656:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6657: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6658:     }
 6659: }
 6660: 
 6661: =pod
 6662: 
 6663: =item scantron_warning_screen
 6664: 
 6665:    Interstitial screen to make sure the operator has selected the
 6666:    correct options before we start the validation phase.
 6667: 
 6668: =cut
 6669: 
 6670: sub scantron_warning_screen {
 6671:     my ($button_text,$symb)=@_;
 6672:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6673:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6674:     my $CODElist;
 6675:     if ($scantron_config{'CODElocation'} &&
 6676: 	$scantron_config{'CODEstart'} &&
 6677: 	$scantron_config{'CODElength'}) {
 6678: 	$CODElist=$env{'form.scantron_CODElist'};
 6679: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
 6680: 	$CODElist=
 6681: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6682: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6683:     }
 6684:     my $lastbubblepoints;
 6685:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 6686:         $lastbubblepoints =
 6687:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
 6688:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
 6689:     }
 6690:     return ('
 6691: <p>
 6692: <span class="LC_warning">
 6693: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
 6694: </p>
 6695: <table>
 6696: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6697: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6698: '.$CODElist.$lastbubblepoints.'
 6699: </table>
 6700: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
 6701: '.&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>
 6702: 
 6703: <br />
 6704: ');
 6705: }
 6706: 
 6707: =pod
 6708: 
 6709: =item scantron_do_warning
 6710: 
 6711:    Check if the operator has picked something for all required
 6712:    fields. Error out if something is missing.
 6713: 
 6714: =cut
 6715: 
 6716: sub scantron_do_warning {
 6717:     my ($r,$symb)=@_;
 6718:     if (!$symb) {return '';}
 6719:     my $default_form_data=&defaultFormData($symb);
 6720:     $r->print(&scantron_form_start().$default_form_data);
 6721:     if ( $env{'form.selectpage'} eq '' ||
 6722: 	 $env{'form.scantron_selectfile'} eq '' ||
 6723: 	 $env{'form.scantron_format'} eq '' ) {
 6724: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
 6725: 	if ( $env{'form.selectpage'} eq '') {
 6726: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6727: 	} 
 6728: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6729: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
 6730: 	} 
 6731: 	if ( $env{'form.scantron_format'} eq '') {
 6732: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
 6733: 	} 
 6734:     } else {
 6735: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
 6736:         my $bubbledbyhand=&hand_bubble_option();
 6737: 	$r->print('
 6738: '.$warning.$bubbledbyhand.'
 6739: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6740: <input type="hidden" name="command" value="scantron_validate" />
 6741: ');
 6742:     }
 6743:     $r->print("</form><br />");
 6744:     return '';
 6745: }
 6746: 
 6747: =pod
 6748: 
 6749: =item scantron_form_start
 6750: 
 6751:     html hidden input for remembering all selected grading options
 6752: 
 6753: =cut
 6754: 
 6755: sub scantron_form_start {
 6756:     my ($max_bubble)=@_;
 6757:     my $result= <<SCANTRONFORM;
 6758: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6759:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6760:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6761:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6762:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6763:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6764:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6765:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6766:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6767:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6768: SCANTRONFORM
 6769: 
 6770:   my $line = 0;
 6771:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6772:        my $chunk =
 6773: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6774:        $chunk .=
 6775: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6776:        $chunk .= 
 6777:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6778:        $chunk .=
 6779:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6780:        $chunk .=
 6781:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
 6782:        $result .= $chunk;
 6783:        $line++;
 6784:     }
 6785:     return $result;
 6786: }
 6787: 
 6788: =pod
 6789: 
 6790: =item scantron_validate_file
 6791: 
 6792:     Dispatch routine for doing validation of a bubblesheet data file.
 6793: 
 6794:     Also processes any necessary information resets that need to
 6795:     occur before validation begins (ignore previous corrections,
 6796:     restarting the skipped records processing)
 6797: 
 6798: =cut
 6799: 
 6800: sub scantron_validate_file {
 6801:     my ($r,$symb) = @_;
 6802:     if (!$symb) {return '';}
 6803:     my $default_form_data=&defaultFormData($symb);
 6804:     
 6805:     # do the detection of only doing skipped records first before we delete
 6806:     # them when doing the corrections reset
 6807:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6808: 	&reset_skipping_status();
 6809:     }
 6810:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6811: 	&remember_current_skipped();
 6812: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6813:     }
 6814: 
 6815:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6816: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6817: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6818: 	&check_for_error($r,&scantron_remove_scan_data());
 6819: 	$env{'form.scantron_options_ignore'}='done';
 6820:     }
 6821: 
 6822:     if ($env{'form.scantron_corrections'}) {
 6823: 	&scantron_process_corrections($r);
 6824:     }
 6825:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6826:     #get the student pick code ready
 6827:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6828:     my $nav_error;
 6829:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6830:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 6831:     if ($nav_error) {
 6832:         $r->print(&navmap_errormsg());
 6833:         return '';
 6834:     }
 6835:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6836:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 6837:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
 6838:     }
 6839:     $r->print($result);
 6840:     
 6841:     my @validate_phases=( 'sequence',
 6842: 			  'ID',
 6843: 			  'CODE',
 6844: 			  'doublebubble',
 6845: 			  'missingbubbles');
 6846:     if (!$env{'form.validatepass'}) {
 6847: 	$env{'form.validatepass'} = 0;
 6848:     }
 6849:     my $currentphase=$env{'form.validatepass'};
 6850: 
 6851: 
 6852:     my $stop=0;
 6853:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6854: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6855: 	$r->rflush();
 6856:      
 6857: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6858: 	{
 6859: 	    no strict 'refs';
 6860: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6861: 	}
 6862:     }
 6863:     if (!$stop) {
 6864: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
 6865: 	$r->print(&mt('Validation process complete.').'<br />'.
 6866:                   $warning.
 6867:                   &mt('Perform verification for each student after storage of submissions?').
 6868:                   '&nbsp;<span class="LC_nobreak"><label>'.
 6869:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 6870:                   ('&nbsp;'x3).'<label>'.
 6871:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 6872:                   '</label></span><br />'.
 6873:                   &mt('Grading will take longer if you use verification.').'<br />'.
 6874:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
 6875:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 6876:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 6877:     } else {
 6878: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6879: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6880:     }
 6881:     if ($stop) {
 6882: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6883: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 6884: 	    $r->print(' '.&mt('this error').' <br />');
 6885: 
 6886: 	    $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>');
 6887: 	} else {
 6888:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6889: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 6890:             } else {
 6891:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 6892:             }
 6893: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6894: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6895: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6896: 	}
 6897:     }
 6898:     $r->print(" </form><br />");
 6899:     return '';
 6900: }
 6901: 
 6902: 
 6903: =pod
 6904: 
 6905: =item scantron_remove_file
 6906: 
 6907:    Removes the requested bubblesheet data file, makes sure that
 6908:    scantron_original_<filename> is never removed
 6909: 
 6910: 
 6911: =cut
 6912: 
 6913: sub scantron_remove_file {
 6914:     my ($which)=@_;
 6915:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6916:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6917:     my $file='scantron_';
 6918:     if ($which eq 'corrected' || $which eq 'skipped') {
 6919: 	$file.=$which.'_';
 6920:     } else {
 6921: 	return 'refused';
 6922:     }
 6923:     $file.=$env{'form.scantron_selectfile'};
 6924:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6925: }
 6926: 
 6927: 
 6928: =pod
 6929: 
 6930: =item scantron_remove_scan_data
 6931: 
 6932:    Removes all scan_data correction for the requested bubblesheet
 6933:    data file.  (In the case that both the are doing skipped records we need
 6934:    to remember the old skipped lines for the time being so that element
 6935:    persists for a while.)
 6936: 
 6937: =cut
 6938: 
 6939: sub scantron_remove_scan_data {
 6940:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6941:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6942:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6943:     my @todelete;
 6944:     my $filename=$env{'form.scantron_selectfile'};
 6945:     foreach my $key (@keys) {
 6946: 	if ($key=~/^\Q$filename\E_/) {
 6947: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6948: 		$key=~/remember_skipping/) {
 6949: 		next;
 6950: 	    }
 6951: 	    push(@todelete,$key);
 6952: 	}
 6953:     }
 6954:     my $result;
 6955:     if (@todelete) {
 6956: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6957: 				       \@todelete,$cdom,$cname);
 6958:     } else {
 6959: 	$result = 'ok';
 6960:     }
 6961:     return $result;
 6962: }
 6963: 
 6964: 
 6965: =pod
 6966: 
 6967: =item scantron_getfile
 6968: 
 6969:     Fetches the requested bubblesheet data file (all 3 versions), and
 6970:     the scan_data hash
 6971:   
 6972:   Arguments:
 6973:     None
 6974: 
 6975:   Returns:
 6976:     2 hash references
 6977: 
 6978:      - first one has 
 6979:          orig      -
 6980:          corrected -
 6981:          skipped   -  each of which points to an array ref of the specified
 6982:                       file broken up into individual lines
 6983:          count     - number of scanlines
 6984:  
 6985:      - second is the scan_data hash possible keys are
 6986:        ($number refers to scanline numbered $number and thus the key affects
 6987:         only that scanline
 6988:         $bubline refers to the specific bubble line element and the aspects
 6989:         refers to that specific bubble line element)
 6990: 
 6991:        $number.user - username:domain to use
 6992:        $number.CODE_ignore_dup 
 6993:                     - ignore the duplicate CODE error 
 6994:        $number.useCODE
 6995:                     - use the CODE in the scanline as is
 6996:        $number.no_bubble.$bubline
 6997:                     - it is valid that there is no bubbled in bubble
 6998:                       at $number $bubline
 6999:        remember_skipping
 7000:                     - a frozen hash containing keys of $number and values
 7001:                       of either 
 7002:                         1 - we are on a 'do skipped records pass' and plan
 7003:                             on processing this line
 7004:                         2 - we are on a 'do skipped records pass' and this
 7005:                             scanline has been marked to skip yet again
 7006: 
 7007: =cut
 7008: 
 7009: sub scantron_getfile {
 7010:     #FIXME really would prefer a scantron directory
 7011:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7012:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7013:     my $lines;
 7014:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7015: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 7016:     my %scanlines;
 7017:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 7018:     my $temp=$scanlines{'orig'};
 7019:     $scanlines{'count'}=$#$temp;
 7020: 
 7021:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7022: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 7023:     if ($lines eq '-1') {
 7024: 	$scanlines{'corrected'}=[];
 7025:     } else {
 7026: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 7027:     }
 7028:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7029: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 7030:     if ($lines eq '-1') {
 7031: 	$scanlines{'skipped'}=[];
 7032:     } else {
 7033: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 7034:     }
 7035:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 7036:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 7037:     my %scan_data = @tmp;
 7038:     return (\%scanlines,\%scan_data);
 7039: }
 7040: 
 7041: =pod
 7042: 
 7043: =item lonnet_putfile
 7044: 
 7045:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 7046: 
 7047:  Arguments:
 7048:    $contents - data to store
 7049:    $filename - filename to store $contents into
 7050: 
 7051:  Returns:
 7052:    result value from &Apache::lonnet::finishuserfileupload
 7053: 
 7054: =cut
 7055: 
 7056: sub lonnet_putfile {
 7057:     my ($contents,$filename)=@_;
 7058:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7059:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7060:     $env{'form.sillywaytopassafilearound'}=$contents;
 7061:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 7062: 
 7063: }
 7064: 
 7065: =pod
 7066: 
 7067: =item scantron_putfile
 7068: 
 7069:     Stores the current version of the bubblesheet data files, and the
 7070:     scan_data hash. (Does not modify the original version only the
 7071:     corrected and skipped versions.
 7072: 
 7073:  Arguments:
 7074:     $scanlines - hash ref that looks like the first return value from
 7075:                  &scantron_getfile()
 7076:     $scan_data - hash ref that looks like the second return value from
 7077:                  &scantron_getfile()
 7078: 
 7079: =cut
 7080: 
 7081: sub scantron_putfile {
 7082:     my ($scanlines,$scan_data) = @_;
 7083:     #FIXME really would prefer a scantron directory
 7084:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7085:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7086:     if ($scanlines) {
 7087: 	my $prefix='scantron_';
 7088: # no need to update orig, shouldn't change
 7089: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 7090: #		    $env{'form.scantron_selectfile'});
 7091: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 7092: 			$prefix.'corrected_'.
 7093: 			$env{'form.scantron_selectfile'});
 7094: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 7095: 			$prefix.'skipped_'.
 7096: 			$env{'form.scantron_selectfile'});
 7097:     }
 7098:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 7099: }
 7100: 
 7101: =pod
 7102: 
 7103: =item scantron_get_line
 7104: 
 7105:    Returns the correct version of the scanline
 7106: 
 7107:  Arguments:
 7108:     $scanlines - hash ref that looks like the first return value from
 7109:                  &scantron_getfile()
 7110:     $scan_data - hash ref that looks like the second return value from
 7111:                  &scantron_getfile()
 7112:     $i         - number of the requested line (starts at 0)
 7113: 
 7114:  Returns:
 7115:    A scanline, (either the original or the corrected one if it
 7116:    exists), or undef if the requested scanline should be
 7117:    skipped. (Either because it's an skipped scanline, or it's an
 7118:    unskipped scanline and we are not doing a 'do skipped scanlines'
 7119:    pass.
 7120: 
 7121: =cut
 7122: 
 7123: sub scantron_get_line {
 7124:     my ($scanlines,$scan_data,$i)=@_;
 7125:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 7126:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 7127:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 7128:     return $scanlines->{'orig'}[$i]; 
 7129: }
 7130: 
 7131: =pod
 7132: 
 7133: =item scantron_todo_count
 7134: 
 7135:     Counts the number of scanlines that need processing.
 7136: 
 7137:  Arguments:
 7138:     $scanlines - hash ref that looks like the first return value from
 7139:                  &scantron_getfile()
 7140:     $scan_data - hash ref that looks like the second return value from
 7141:                  &scantron_getfile()
 7142: 
 7143:  Returns:
 7144:     $count - number of scanlines to process
 7145: 
 7146: =cut
 7147: 
 7148: sub get_todo_count {
 7149:     my ($scanlines,$scan_data)=@_;
 7150:     my $count=0;
 7151:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7152: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7153: 	if ($line=~/^[\s\cz]*$/) { next; }
 7154: 	$count++;
 7155:     }
 7156:     return $count;
 7157: }
 7158: 
 7159: =pod
 7160: 
 7161: =item scantron_put_line
 7162: 
 7163:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
 7164:     data file.
 7165: 
 7166:  Arguments:
 7167:     $scanlines - hash ref that looks like the first return value from
 7168:                  &scantron_getfile()
 7169:     $scan_data - hash ref that looks like the second return value from
 7170:                  &scantron_getfile()
 7171:     $i         - line number to update
 7172:     $newline   - contents of the updated scanline
 7173:     $skip      - if true make the line for skipping and update the
 7174:                  'skipped' file
 7175: 
 7176: =cut
 7177: 
 7178: sub scantron_put_line {
 7179:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 7180:     if ($skip) {
 7181: 	$scanlines->{'skipped'}[$i]=$newline;
 7182: 	&start_skipping($scan_data,$i);
 7183: 	return;
 7184:     }
 7185:     $scanlines->{'corrected'}[$i]=$newline;
 7186: }
 7187: 
 7188: =pod
 7189: 
 7190: =item scantron_clear_skip
 7191: 
 7192:    Remove a line from the 'skipped' file
 7193: 
 7194:  Arguments:
 7195:     $scanlines - hash ref that looks like the first return value from
 7196:                  &scantron_getfile()
 7197:     $scan_data - hash ref that looks like the second return value from
 7198:                  &scantron_getfile()
 7199:     $i         - line number to update
 7200: 
 7201: =cut
 7202: 
 7203: sub scantron_clear_skip {
 7204:     my ($scanlines,$scan_data,$i)=@_;
 7205:     if (exists($scanlines->{'skipped'}[$i])) {
 7206: 	undef($scanlines->{'skipped'}[$i]);
 7207: 	return 1;
 7208:     }
 7209:     return 0;
 7210: }
 7211: 
 7212: =pod
 7213: 
 7214: =item scantron_filter_not_exam
 7215: 
 7216:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 7217:    filter out resources that are not marked as 'exam' mode
 7218: 
 7219: =cut
 7220: 
 7221: sub scantron_filter_not_exam {
 7222:     my ($curres)=@_;
 7223:     
 7224:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 7225: 	# if the user has asked to not have either hidden
 7226: 	# or 'randomout' controlled resources to be graded
 7227: 	# don't include them
 7228: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 7229: 	    && $curres->randomout) {
 7230: 	    return 0;
 7231: 	}
 7232: 	return 1;
 7233:     }
 7234:     return 0;
 7235: }
 7236: 
 7237: =pod
 7238: 
 7239: =item scantron_validate_sequence
 7240: 
 7241:     Validates the selected sequence, checking for resource that are
 7242:     not set to exam mode.
 7243: 
 7244: =cut
 7245: 
 7246: sub scantron_validate_sequence {
 7247:     my ($r,$currentphase) = @_;
 7248: 
 7249:     my $navmap=Apache::lonnavmaps::navmap->new();
 7250:     unless (ref($navmap)) {
 7251:         $r->print(&navmap_errormsg());
 7252:         return (1,$currentphase);
 7253:     }
 7254:     my (undef,undef,$sequence)=
 7255: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7256: 
 7257:     my $map=$navmap->getResourceByUrl($sequence);
 7258: 
 7259:     $r->print('<input type="hidden" name="validate_sequence_exam"
 7260:                                     value="ignore" />');
 7261:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 7262: 	my @resources=
 7263: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 7264: 	if (@resources) {
 7265: 	    $r->print(
 7266:                 '<p class="LC_warning">'
 7267:                .&mt('Some resources in the sequence currently are not set to'
 7268:                    .' bubblesheet exam mode. Grading these resources currently may not'
 7269:                    .' work correctly.')
 7270:                .'</p>'
 7271:             );
 7272: 	    return (1,$currentphase);
 7273: 	}
 7274:     }
 7275: 
 7276:     return (0,$currentphase+1);
 7277: }
 7278: 
 7279: 
 7280: 
 7281: sub scantron_validate_ID {
 7282:     my ($r,$currentphase) = @_;
 7283:     
 7284:     #get student info
 7285:     my $classlist=&Apache::loncoursedata::get_classlist();
 7286:     my %idmap=&username_to_idmap($classlist);
 7287: 
 7288:     #get scantron line setup
 7289:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7290:     my ($scanlines,$scan_data)=&scantron_getfile();
 7291: 
 7292:     my $nav_error;
 7293:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
 7294:     if ($nav_error) {
 7295:         $r->print(&navmap_errormsg());
 7296:         return(1,$currentphase);
 7297:     }
 7298: 
 7299:     my %found=('ids'=>{},'usernames'=>{});
 7300:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7301: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7302: 	if ($line=~/^[\s\cz]*$/) { next; }
 7303: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7304: 						 $scan_data);
 7305: 	my $id=$$scan_record{'scantron.ID'};
 7306: 	my $found;
 7307: 	foreach my $checkid (keys(%idmap)) {
 7308: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 7309: 	}
 7310: 	if ($found) {
 7311: 	    my $username=$idmap{$found};
 7312: 	    if ($found{'ids'}{$found}) {
 7313: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7314: 					 $line,'duplicateID',$found);
 7315: 		return(1,$currentphase);
 7316: 	    } elsif ($found{'usernames'}{$username}) {
 7317: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7318: 					 $line,'duplicateID',$username);
 7319: 		return(1,$currentphase);
 7320: 	    }
 7321: 	    #FIXME store away line we previously saw the ID on to use above
 7322: 	    $found{'ids'}{$found}++;
 7323: 	    $found{'usernames'}{$username}++;
 7324: 	} else {
 7325: 	    if ($id =~ /^\s*$/) {
 7326: 		my $username=&scan_data($scan_data,"$i.user");
 7327: 		if (defined($username) && $found{'usernames'}{$username}) {
 7328: 		    &scantron_get_correction($r,$i,$scan_record,
 7329: 					     \%scantron_config,
 7330: 					     $line,'duplicateID',$username);
 7331: 		    return(1,$currentphase);
 7332: 		} elsif (!defined($username)) {
 7333: 		    &scantron_get_correction($r,$i,$scan_record,
 7334: 					     \%scantron_config,
 7335: 					     $line,'incorrectID');
 7336: 		    return(1,$currentphase);
 7337: 		}
 7338: 		$found{'usernames'}{$username}++;
 7339: 	    } else {
 7340: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7341: 					 $line,'incorrectID');
 7342: 		return(1,$currentphase);
 7343: 	    }
 7344: 	}
 7345:     }
 7346: 
 7347:     return (0,$currentphase+1);
 7348: }
 7349: 
 7350: 
 7351: sub scantron_get_correction {
 7352:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
 7353:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
 7354: #FIXME in the case of a duplicated ID the previous line, probably need
 7355: #to show both the current line and the previous one and allow skipping
 7356: #the previous one or the current one
 7357: 
 7358:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 7359:         $r->print(
 7360:             '<p class="LC_warning">'
 7361:            .&mt('An error was detected ([_1]) for PaperID [_2]',
 7362:                 "<b>$error</b>",
 7363:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
 7364:            ."</p> \n");
 7365:     } else {
 7366:         $r->print(
 7367:             '<p class="LC_warning">'
 7368:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
 7369:                 "<b>$error</b>", $i, "<pre>$line</pre>")
 7370:            ."</p> \n");
 7371:     }
 7372:     my $message =
 7373:         '<p>'
 7374:        .&mt('The ID on the form is [_1]',
 7375:             "<tt>$$scan_record{'scantron.ID'}</tt>")
 7376:        .'<br />'
 7377:        .&mt('The name on the paper is [_1], [_2]',
 7378:             $$scan_record{'scantron.LastName'},
 7379:             $$scan_record{'scantron.FirstName'})
 7380:        .'</p>';
 7381: 
 7382:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 7383:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 7384:                            # Array populated for doublebubble or
 7385:     my @lines_to_correct;  # missingbubble errors to build javascript
 7386:                            # to validate radio button checking   
 7387: 
 7388:     if ($error =~ /ID$/) {
 7389: 	if ($error eq 'incorrectID') {
 7390:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
 7391: 		      "</p>\n");
 7392: 	} elsif ($error eq 'duplicateID') {
 7393:             $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 7394: 	}
 7395: 	$r->print($message);
 7396: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 7397: 	$r->print("\n<ul><li> ");
 7398: 	#FIXME it would be nice if this sent back the user ID and
 7399: 	#could do partial userID matches
 7400: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 7401: 				       'scantron_username','scantron_domain'));
 7402: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 7403: 	$r->print("\n:\n".
 7404: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 7405: 
 7406: 	$r->print('</li>');
 7407:     } elsif ($error =~ /CODE$/) {
 7408: 	if ($error eq 'incorrectCODE') {
 7409: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 7410: 	} elsif ($error eq 'duplicateCODE') {
 7411: 	    $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");
 7412: 	}
 7413: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
 7414: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
 7415:                  ."</p>\n");
 7416: 	$r->print($message);
 7417: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
 7418: 	$r->print("\n<br /> ");
 7419: 	my $i=0;
 7420: 	if ($error eq 'incorrectCODE' 
 7421: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 7422: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 7423: 	    if ($closest > 0) {
 7424: 		foreach my $testcode (@{$closest}) {
 7425: 		    my $checked='';
 7426: 		    if (!$i) { $checked=' checked="checked"'; }
 7427: 		    $r->print("
 7428:    <label>
 7429:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 7430:        ".&mt("Use the similar CODE [_1] instead.",
 7431: 	    "<b><tt>".$testcode."</tt></b>")."
 7432:     </label>
 7433:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 7434: 		    $r->print("\n<br />");
 7435: 		    $i++;
 7436: 		}
 7437: 	    }
 7438: 	}
 7439: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 7440: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 7441: 	    $r->print("
 7442:     <label>
 7443:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 7444:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
 7445: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 7446:     </label>");
 7447: 	    $r->print("\n<br />");
 7448: 	}
 7449: 
 7450: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
 7451: function change_radio(field) {
 7452:     var slct=document.scantronupload.scantron_CODE_resolution;
 7453:     var i;
 7454:     for (i=0;i<slct.length;i++) {
 7455:         if (slct[i].value==field) { slct[i].checked=true; }
 7456:     }
 7457: }
 7458: ENDSCRIPT
 7459: 	my $href="/adm/pickcode?".
 7460: 	   "form=".&escape("scantronupload").
 7461: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 7462: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 7463: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 7464: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 7465: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 7466: 	    $r->print("
 7467:     <label>
 7468:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 7469:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 7470: 	     "<a target='_blank' href='$href'>","</a>")."
 7471:     </label> 
 7472:     ".&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\')" />'));
 7473: 	    $r->print("\n<br />");
 7474: 	}
 7475: 	$r->print("
 7476:     <label>
 7477:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 7478:        ".&mt("Use [_1] as the CODE.",
 7479: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 7480: 	$r->print("\n<br /><br />");
 7481:     } elsif ($error eq 'doublebubble') {
 7482: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 7483: 
 7484: 	# The form field scantron_questions is acutally a list of line numbers.
 7485: 	# represented by this form so:
 7486: 
 7487: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7488:                                                 $respnumlookup,$startline);
 7489: 
 7490: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7491: 		  $line_list.'" />');
 7492: 	$r->print($message);
 7493: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 7494: 	foreach my $question (@{$arg}) {
 7495: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7496:                                                    $scan_record, $error,
 7497:                                                    $randomorder,$randompick,
 7498:                                                    $respnumlookup,$startline);
 7499:             push(@lines_to_correct,@linenums);
 7500: 	}
 7501:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7502:     } elsif ($error eq 'missingbubble') {
 7503: 	$r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
 7504: 	$r->print($message);
 7505: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 7506: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 7507: 
 7508: 	# The form field scantron_questions is actually a list of line numbers not
 7509: 	# a list of question numbers. Therefore:
 7510: 	#
 7511: 
 7512: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7513:                                                 $respnumlookup,$startline);
 7514: 
 7515: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7516: 		  $line_list.'" />');
 7517: 	foreach my $question (@{$arg}) {
 7518: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7519:                                                    $scan_record, $error,
 7520:                                                    $randomorder,$randompick,
 7521:                                                    $respnumlookup,$startline);
 7522:             push(@lines_to_correct,@linenums);
 7523: 	}
 7524:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7525:     } else {
 7526: 	$r->print("\n<ul>");
 7527:     }
 7528:     $r->print("\n</li></ul>");
 7529: }
 7530: 
 7531: sub verify_bubbles_checked {
 7532:     my (@ansnums) = @_;
 7533:     my $ansnumstr = join('","',@ansnums);
 7534:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 7535:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
 7536: function verify_bubble_radio(form) {
 7537:     var ansnumArray = new Array ("$ansnumstr");
 7538:     var need_bubble_count = 0;
 7539:     for (var i=0; i<ansnumArray.length; i++) {
 7540:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 7541:             var bubble_picked = 0; 
 7542:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 7543:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 7544:                     bubble_picked = 1;
 7545:                 }
 7546:             }
 7547:             if (bubble_picked == 0) {
 7548:                 need_bubble_count ++;
 7549:             }
 7550:         }
 7551:     }
 7552:     if (need_bubble_count) {
 7553:         alert("$warning");
 7554:         return;
 7555:     }
 7556:     form.submit(); 
 7557: }
 7558: ENDSCRIPT
 7559:     return $output;
 7560: }
 7561: 
 7562: =pod
 7563: 
 7564: =item  questions_to_line_list
 7565: 
 7566: Converts a list of questions into a string of comma separated
 7567: line numbers in the answer sheet used by the questions.  This is
 7568: used to fill in the scantron_questions form field.
 7569: 
 7570:   Arguments:
 7571:      questions    - Reference to an array of questions.
 7572:      randomorder  - True if randomorder in use.
 7573:      randompick   - True if randompick in use.
 7574:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
 7575:                      for current line to question number used for same question
 7576:                      in "Master Seqence" (as seen by Course Coordinator).
 7577:      startline    - Reference to hash where key is question number (0 is first)
 7578:                     and key is number of first bubble line for current student
 7579:                     or code-based randompick and/or randomorder.
 7580: 
 7581: =cut
 7582: 
 7583: 
 7584: sub questions_to_line_list {
 7585:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
 7586:     my @lines;
 7587: 
 7588:     foreach my $item (@{$questions}) {
 7589:         my $question = $item;
 7590:         my ($first,$count,$last);
 7591:         if ($item =~ /^(\d+)\.(\d+)$/) {
 7592:             $question = $1;
 7593:             my $subquestion = $2;
 7594:             my $responsenum = $question-1;
 7595:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7596:                 $responsenum = $respnumlookup->{$question-1};
 7597:                 if (ref($startline) eq 'HASH') {
 7598:                     $first = $startline->{$question-1} + 1;
 7599:                 }
 7600:             } else {
 7601:                 $first = $first_bubble_line{$responsenum} + 1;
 7602:             }
 7603:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 7604:             my $subcount = 1;
 7605:             while ($subcount<$subquestion) {
 7606:                 $first += $subans[$subcount-1];
 7607:                 $subcount ++;
 7608:             }
 7609:             $count = $subans[$subquestion-1];
 7610:         } else {
 7611:             my $responsenum = $question-1;
 7612:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7613:                 $responsenum = $respnumlookup->{$question-1};
 7614:                 if (ref($startline) eq 'HASH') {
 7615:                     $first = $startline->{$question-1} + 1;
 7616:                 }
 7617:             } else {
 7618:                 $first = $first_bubble_line{$responsenum} + 1;
 7619:             }
 7620: 	    $count   = $bubble_lines_per_response{$responsenum};
 7621:         }
 7622:         $last = $first+$count-1;
 7623:         push(@lines, ($first..$last));
 7624:     }
 7625:     return join(',', @lines);
 7626: }
 7627: 
 7628: =pod 
 7629: 
 7630: =item prompt_for_corrections
 7631: 
 7632: Prompts for a potentially multiline correction to the
 7633: user's bubbling (factors out common code from scantron_get_correction
 7634: for multi and missing bubble cases).
 7635: 
 7636:  Arguments:
 7637:    $r           - Apache request object.
 7638:    $question    - The question number to prompt for.
 7639:    $scan_config - The scantron file configuration hash.
 7640:    $scan_record - Reference to the hash that has the the parsed scanlines.
 7641:    $error       - Type of error
 7642:    $randomorder - True if randomorder in use.
 7643:    $randompick  - True if randompick in use.
 7644:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
 7645:                     for current line to question number used for same question
 7646:                     in "Master Seqence" (as seen by Course Coordinator).
 7647:    $startline   - Reference to hash where key is question number (0 is first)
 7648:                   and value is number of first bubble line for current student
 7649:                   or code-based randompick and/or randomorder.
 7650: 
 7651: 
 7652:  Implicit inputs:
 7653:    %bubble_lines_per_response   - Starting line numbers for each question.
 7654:                                   Numbered from 0 (but question numbers are from
 7655:                                   1.
 7656:    %first_bubble_line           - Starting bubble line for each question.
 7657:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 7658:                                   type problems render as separate sub-questions, 
 7659:                                   in exam mode. This hash contains a 
 7660:                                   comma-separated list of the lines per 
 7661:                                   sub-question.
 7662:    %responsetype_per_response   - essayresponse, formularesponse,
 7663:                                   stringresponse, imageresponse, reactionresponse,
 7664:                                   and organicresponse type problem parts can have
 7665:                                   multiple lines per response if the weight
 7666:                                   assigned exceeds 10.  In this case, only
 7667:                                   one bubble per line is permitted, but more 
 7668:                                   than one line might contain bubbles, e.g.
 7669:                                   bubbling of: line 1 - J, line 2 - J, 
 7670:                                   line 3 - B would assign 22 points.  
 7671: 
 7672: =cut
 7673: 
 7674: sub prompt_for_corrections {
 7675:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
 7676:         $randompick, $respnumlookup, $startline) = @_;
 7677:     my ($current_line,$lines);
 7678:     my @linenums;
 7679:     my $questionnum = $question;
 7680:     my ($first,$responsenum);
 7681:     if ($question =~ /^(\d+)\.(\d+)$/) {
 7682:         $question = $1;
 7683:         my $subquestion = $2;
 7684:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7685:             $responsenum = $respnumlookup->{$question-1};
 7686:             if (ref($startline) eq 'HASH') {
 7687:                 $first = $startline->{$question-1};
 7688:             }
 7689:         } else {
 7690:             $responsenum = $question-1;
 7691:             $first = $first_bubble_line{$responsenum};
 7692:         }
 7693:         $current_line = $first + 1 ;
 7694:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 7695:         my $subcount = 1;
 7696:         while ($subcount<$subquestion) {
 7697:             $current_line += $subans[$subcount-1];
 7698:             $subcount ++;
 7699:         }
 7700:         $lines = $subans[$subquestion-1];
 7701:     } else {
 7702:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7703:             $responsenum = $respnumlookup->{$question-1};
 7704:             if (ref($startline) eq 'HASH') { 
 7705:                 $first = $startline->{$question-1};
 7706:             }
 7707:         } else {
 7708:             $responsenum = $question-1;
 7709:             $first = $first_bubble_line{$responsenum};
 7710:         }
 7711:         $current_line = $first + 1;
 7712:         $lines        = $bubble_lines_per_response{$responsenum};
 7713:     }
 7714:     if ($lines > 1) {
 7715:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7716:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 7717:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 7718:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 7719:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 7720:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 7721:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 7722:             $r->print(
 7723:                 &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)
 7724:                .'<br /><br />'
 7725:                .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
 7726:                .'<br />'
 7727:                .&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.')
 7728:                .'<br />'
 7729:                .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
 7730:                .'<br /><br />'
 7731:             );
 7732:         } else {
 7733:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7734:         }
 7735:     }
 7736:     for (my $i =0; $i < $lines; $i++) {
 7737:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7738: 	&scantron_bubble_selector($r,$scan_config,$current_line,
 7739: 	        		  $questionnum,$error,split('', $selected));
 7740:         push(@linenums,$current_line);
 7741: 	$current_line++;
 7742:     }
 7743:     if ($lines > 1) {
 7744: 	$r->print("<hr /><br />");
 7745:     }
 7746:     return @linenums;
 7747: }
 7748: 
 7749: =pod
 7750: 
 7751: =item scantron_bubble_selector
 7752:   
 7753:    Generates the html radiobuttons to correct a single bubble line
 7754:    possibly showing the existing the selected bubbles if known
 7755: 
 7756:  Arguments:
 7757:     $r           - Apache request object
 7758:     $scan_config - hash from &get_scantron_config()
 7759:     $line        - Number of the line being displayed.
 7760:     $questionnum - Question number (may include subquestion)
 7761:     $error       - Type of error.
 7762:     @selected    - Array of bubbles picked on this line.
 7763: 
 7764: =cut
 7765: 
 7766: sub scantron_bubble_selector {
 7767:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7768:     my $max=$$scan_config{'Qlength'};
 7769: 
 7770:     my $scmode=$$scan_config{'Qon'};
 7771:     if ($scmode eq 'number' || $scmode eq 'letter') { 
 7772:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
 7773:             ($$scan_config{'BubblesPerRow'} > 0)) {
 7774:             $max=$$scan_config{'BubblesPerRow'};
 7775:             if (($scmode eq 'number') && ($max > 10)) {
 7776:                 $max = 10;
 7777:             } elsif (($scmode eq 'letter') && $max > 26) {
 7778:                 $max = 26;
 7779:             }
 7780:         } else {
 7781:             $max = 10;
 7782:         }
 7783:     }
 7784: 
 7785:     my @alphabet=('A'..'Z');
 7786:     $r->print(&Apache::loncommon::start_data_table().
 7787:               &Apache::loncommon::start_data_table_row());
 7788:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7789:     for (my $i=0;$i<$max+1;$i++) {
 7790: 	$r->print("\n".'<td align="center">');
 7791: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7792: 	else { $r->print('&nbsp;'); }
 7793: 	$r->print('</td>');
 7794:     }
 7795:     $r->print(&Apache::loncommon::end_data_table_row().
 7796:               &Apache::loncommon::start_data_table_row());
 7797:     for (my $i=0;$i<$max;$i++) {
 7798: 	$r->print("\n".
 7799: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7800: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7801:     }
 7802:     my $nobub_checked = ' ';
 7803:     if ($error eq 'missingbubble') {
 7804:         $nobub_checked = ' checked = "checked" ';
 7805:     }
 7806:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7807: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7808:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7809:               $line.'" value="'.$questionnum.'" /></td>');
 7810:     $r->print(&Apache::loncommon::end_data_table_row().
 7811:               &Apache::loncommon::end_data_table());
 7812: }
 7813: 
 7814: =pod
 7815: 
 7816: =item num_matches
 7817: 
 7818:    Counts the number of characters that are the same between the two arguments.
 7819: 
 7820:  Arguments:
 7821:    $orig - CODE from the scanline
 7822:    $code - CODE to match against
 7823: 
 7824:  Returns:
 7825:    $count - integer count of the number of same characters between the
 7826:             two arguments
 7827: 
 7828: =cut
 7829: 
 7830: sub num_matches {
 7831:     my ($orig,$code) = @_;
 7832:     my @code=split(//,$code);
 7833:     my @orig=split(//,$orig);
 7834:     my $same=0;
 7835:     for (my $i=0;$i<scalar(@code);$i++) {
 7836: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7837:     }
 7838:     return $same;
 7839: }
 7840: 
 7841: =pod
 7842: 
 7843: =item scantron_get_closely_matching_CODEs
 7844: 
 7845:    Cycles through all CODEs and finds the set that has the greatest
 7846:    number of same characters as the provided CODE
 7847: 
 7848:  Arguments:
 7849:    $allcodes - hash ref returned by &get_codes()
 7850:    $CODE     - CODE from the current scanline
 7851: 
 7852:  Returns:
 7853:    2 element list
 7854:     - first elements is number of how closely matching the best fit is 
 7855:       (5 means best set has 5 matching characters)
 7856:     - second element is an arrary ref containing the set of valid CODEs
 7857:       that best fit the passed in CODE
 7858: 
 7859: =cut
 7860: 
 7861: sub scantron_get_closely_matching_CODEs {
 7862:     my ($allcodes,$CODE)=@_;
 7863:     my @CODEs;
 7864:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7865: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7866:     }
 7867: 
 7868:     return ($#CODEs,$CODEs[-1]);
 7869: }
 7870: 
 7871: =pod
 7872: 
 7873: =item get_codes
 7874: 
 7875:    Builds a hash which has keys of all of the valid CODEs from the selected
 7876:    set of remembered CODEs.
 7877: 
 7878:  Arguments:
 7879:   $old_name - name of the set of remembered CODEs
 7880:   $cdom     - domain of the course
 7881:   $cnum     - internal course name
 7882: 
 7883:  Returns:
 7884:   %allcodes - keys are the valid CODEs, values are all 1
 7885: 
 7886: =cut
 7887: 
 7888: sub get_codes {
 7889:     my ($old_name, $cdom, $cnum) = @_;
 7890:     if (!$old_name) {
 7891: 	$old_name=$env{'form.scantron_CODElist'};
 7892:     }
 7893:     if (!$cdom) {
 7894: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7895:     }
 7896:     if (!$cnum) {
 7897: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7898:     }
 7899:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7900: 				    $cdom,$cnum);
 7901:     my %allcodes;
 7902:     if ($result{"type\0$old_name"} eq 'number') {
 7903: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7904:     } else {
 7905: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7906:     }
 7907:     return %allcodes;
 7908: }
 7909: 
 7910: =pod
 7911: 
 7912: =item scantron_validate_CODE
 7913: 
 7914:    Validates all scanlines in the selected file to not have any
 7915:    invalid or underspecified CODEs and that none of the codes are
 7916:    duplicated if this was requested.
 7917: 
 7918: =cut
 7919: 
 7920: sub scantron_validate_CODE {
 7921:     my ($r,$currentphase) = @_;
 7922:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7923:     if ($scantron_config{'CODElocation'} &&
 7924: 	$scantron_config{'CODEstart'} &&
 7925: 	$scantron_config{'CODElength'}) {
 7926: 	if (!defined($env{'form.scantron_CODElist'})) {
 7927: 	    &FIXME_blow_up()
 7928: 	}
 7929:     } else {
 7930: 	return (0,$currentphase+1);
 7931:     }
 7932:     
 7933:     my %usedCODEs;
 7934: 
 7935:     my %allcodes=&get_codes();
 7936: 
 7937:     my $nav_error;
 7938:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
 7939:     if ($nav_error) {
 7940:         $r->print(&navmap_errormsg());
 7941:         return(1,$currentphase);
 7942:     }
 7943: 
 7944:     my ($scanlines,$scan_data)=&scantron_getfile();
 7945:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7946: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7947: 	if ($line=~/^[\s\cz]*$/) { next; }
 7948: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7949: 						 $scan_data);
 7950: 	my $CODE=$$scan_record{'scantron.CODE'};
 7951: 	my $error=0;
 7952: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7953: 	    &scantron_get_correction($r,$i,$scan_record,
 7954: 				     \%scantron_config,
 7955: 				     $line,'incorrectCODE',\%allcodes);
 7956: 	    return(1,$currentphase);
 7957: 	}
 7958: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7959: 	    && !$$scan_record{'scantron.useCODE'}) {
 7960: 	    &scantron_get_correction($r,$i,$scan_record,
 7961: 				     \%scantron_config,
 7962: 				     $line,'incorrectCODE',\%allcodes);
 7963: 	    return(1,$currentphase);
 7964: 	}
 7965: 	if (exists($usedCODEs{$CODE}) 
 7966: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 7967: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 7968: 	    &scantron_get_correction($r,$i,$scan_record,
 7969: 				     \%scantron_config,
 7970: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 7971: 	    return(1,$currentphase);
 7972: 	}
 7973: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 7974:     }
 7975:     return (0,$currentphase+1);
 7976: }
 7977: 
 7978: =pod
 7979: 
 7980: =item scantron_validate_doublebubble
 7981: 
 7982:    Validates all scanlines in the selected file to not have any
 7983:    bubble lines with multiple bubbles marked.
 7984: 
 7985: =cut
 7986: 
 7987: sub scantron_validate_doublebubble {
 7988:     my ($r,$currentphase) = @_;
 7989:     #get student info
 7990:     my $classlist=&Apache::loncoursedata::get_classlist();
 7991:     my %idmap=&username_to_idmap($classlist);
 7992:     my (undef,undef,$sequence)=
 7993:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 7994: 
 7995:     #get scantron line setup
 7996:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7997:     my ($scanlines,$scan_data)=&scantron_getfile();
 7998: 
 7999:     my $navmap = Apache::lonnavmaps::navmap->new();
 8000:     unless (ref($navmap)) {
 8001:         $r->print(&navmap_errormsg());
 8002:         return(1,$currentphase);
 8003:     }
 8004:     my $map=$navmap->getResourceByUrl($sequence);
 8005:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8006:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8007:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8008:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8009: 
 8010:     my $nav_error;
 8011:     if (ref($map)) {
 8012:         $randomorder = $map->randomorder();
 8013:         $randompick = $map->randompick();
 8014:         if ($randomorder || $randompick) {
 8015:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8016:             if ($nav_error) {
 8017:                 $r->print(&navmap_errormsg());
 8018:                 return(1,$currentphase);
 8019:             }
 8020:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8021:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8022:         }
 8023:     } else {
 8024:         $r->print(&navmap_errormsg());
 8025:         return(1,$currentphase);
 8026:     }
 8027: 
 8028:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
 8029:     if ($nav_error) {
 8030:         $r->print(&navmap_errormsg());
 8031:         return(1,$currentphase);
 8032:     }
 8033: 
 8034:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8035: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8036: 	if ($line=~/^[\s\cz]*$/) { next; }
 8037: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8038: 						 $scan_data,undef,\%idmap,$randomorder,
 8039:                                                  $randompick,$sequence,\@master_seq,
 8040:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8041:                                                  \%orderedforcode,\%respnumlookup,\%startline);
 8042: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 8043: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 8044: 				 'doublebubble',
 8045: 				 $$scan_record{'scantron.doubleerror'},
 8046:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
 8047:     	return (1,$currentphase);
 8048:     }
 8049:     return (0,$currentphase+1);
 8050: }
 8051: 
 8052: 
 8053: sub scantron_get_maxbubble {
 8054:     my ($nav_error,$scantron_config) = @_;
 8055:     if (defined($env{'form.scantron_maxbubble'}) &&
 8056: 	$env{'form.scantron_maxbubble'}) {
 8057: 	&restore_bubble_lines();
 8058: 	return $env{'form.scantron_maxbubble'};
 8059:     }
 8060: 
 8061:     my (undef, undef, $sequence) =
 8062: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8063: 
 8064:     my $navmap=Apache::lonnavmaps::navmap->new();
 8065:     unless (ref($navmap)) {
 8066:         if (ref($nav_error)) {
 8067:             $$nav_error = 1;
 8068:         }
 8069:         return;
 8070:     }
 8071:     my $map=$navmap->getResourceByUrl($sequence);
 8072:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8073:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
 8074: 
 8075:     &Apache::lonxml::clear_problem_counter();
 8076: 
 8077:     my $uname       = $env{'user.name'};
 8078:     my $udom        = $env{'user.domain'};
 8079:     my $cid         = $env{'request.course.id'};
 8080:     my $total_lines = 0;
 8081:     %bubble_lines_per_response = ();
 8082:     %first_bubble_line         = ();
 8083:     %subdivided_bubble_lines   = ();
 8084:     %responsetype_per_response = ();
 8085:     %masterseq_id_responsenum  = ();
 8086: 
 8087:     my $response_number = 0;
 8088:     my $bubble_line     = 0;
 8089:     foreach my $resource (@resources) {
 8090:         my $resid = $resource->id(); 
 8091:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
 8092:                                                           $udom,undef,$bubbles_per_row);
 8093:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 8094: 	    foreach my $part_id (@{$parts}) {
 8095:                 my $lines;
 8096: 
 8097: 	        # TODO - make this a persistent hash not an array.
 8098: 
 8099:                 # optionresponse, matchresponse and rankresponse type items 
 8100:                 # render as separate sub-questions in exam mode.
 8101:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 8102:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 8103:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 8104:                     my ($numbub,$numshown);
 8105:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 8106:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 8107:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 8108:                         }
 8109:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 8110:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 8111:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 8112:                         }
 8113:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 8114:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 8115:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 8116:                         }
 8117:                     }
 8118:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 8119:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 8120:                     }
 8121:                     my $bubbles_per_row =
 8122:                         &bubblesheet_bubbles_per_row($scantron_config);
 8123:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
 8124:                     if (($numbub % $bubbles_per_row) != 0) {
 8125:                         $inner_bubble_lines++;
 8126:                     }
 8127:                     for (my $i=0; $i<$numshown; $i++) {
 8128:                         $subdivided_bubble_lines{$response_number} .= 
 8129:                             $inner_bubble_lines.',';
 8130:                     }
 8131:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 8132:                     $lines = $numshown * $inner_bubble_lines;
 8133:                 } else {
 8134:                     $lines = $analysis->{"$part_id.bubble_lines"};
 8135:                 }
 8136: 
 8137:                 $first_bubble_line{$response_number} = $bubble_line;
 8138: 	        $bubble_lines_per_response{$response_number} = $lines;
 8139:                 $responsetype_per_response{$response_number} = 
 8140:                     $analysis->{$part_id.'.type'};
 8141:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;  
 8142: 	        $response_number++;
 8143: 
 8144: 	        $bubble_line +=  $lines;
 8145: 	        $total_lines +=  $lines;
 8146: 	    }
 8147:         }
 8148:     }
 8149:     &Apache::lonnet::delenv('scantron.');
 8150: 
 8151:     &save_bubble_lines();
 8152:     $env{'form.scantron_maxbubble'} =
 8153: 	$total_lines;
 8154:     return $env{'form.scantron_maxbubble'};
 8155: }
 8156: 
 8157: sub bubblesheet_bubbles_per_row {
 8158:     my ($scantron_config) = @_;
 8159:     my $bubbles_per_row;
 8160:     if (ref($scantron_config) eq 'HASH') {
 8161:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
 8162:     }
 8163:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
 8164:         $bubbles_per_row = 10;
 8165:     }
 8166:     return $bubbles_per_row;
 8167: }
 8168: 
 8169: sub scantron_validate_missingbubbles {
 8170:     my ($r,$currentphase) = @_;
 8171:     #get student info
 8172:     my $classlist=&Apache::loncoursedata::get_classlist();
 8173:     my %idmap=&username_to_idmap($classlist);
 8174:     my (undef,undef,$sequence)=
 8175:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8176: 
 8177:     #get scantron line setup
 8178:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8179:     my ($scanlines,$scan_data)=&scantron_getfile();
 8180: 
 8181:     my $navmap = Apache::lonnavmaps::navmap->new();
 8182:     unless (ref($navmap)) {
 8183:         $r->print(&navmap_errormsg());
 8184:         return(1,$currentphase);
 8185:     }
 8186: 
 8187:     my $map=$navmap->getResourceByUrl($sequence);
 8188:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8189:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8190:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8191:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8192: 
 8193:     my $nav_error;
 8194:     if (ref($map)) {
 8195:         $randomorder = $map->randomorder();
 8196:         $randompick = $map->randompick();
 8197:         if ($randomorder || $randompick) {
 8198:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8199:             if ($nav_error) {
 8200:                 $r->print(&navmap_errormsg());
 8201:                 return(1,$currentphase);
 8202:             }
 8203:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8204:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8205:         }
 8206:     } else {
 8207:         $r->print(&navmap_errormsg());
 8208:         return(1,$currentphase);
 8209:     }
 8210: 
 8211: 
 8212:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 8213:     if ($nav_error) {
 8214:         $r->print(&navmap_errormsg());
 8215:         return(1,$currentphase);
 8216:     }
 8217: 
 8218:     if (!$max_bubble) { $max_bubble=2**31; }
 8219:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8220: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8221: 	if ($line=~/^[\s\cz]*$/) { next; }
 8222: 	my $scan_record =
 8223:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
 8224: 				     $randomorder,$randompick,$sequence,\@master_seq,
 8225:                                      \%symb_to_resource,\%grader_partids_by_symb,
 8226:                                      \%orderedforcode,\%respnumlookup,\%startline);
 8227: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 8228: 	my @to_correct;
 8229: 	
 8230: 	# Probably here's where the error is...
 8231: 
 8232: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 8233:             my $lastbubble;
 8234:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 8235:                my $question = $1;
 8236:                my $subquestion = $2;
 8237:                my ($first,$responsenum);
 8238:                if ($randomorder || $randompick) {
 8239:                    $responsenum = $respnumlookup{$question-1};
 8240:                    $first = $startline{$question-1};
 8241:                } else {
 8242:                    $responsenum = $question-1; 
 8243:                    $first = $first_bubble_line{$responsenum};
 8244:                }
 8245:                if (!defined($first)) { next; }
 8246:                my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8247:                my $subcount = 1;
 8248:                while ($subcount<$subquestion) {
 8249:                    $first += $subans[$subcount-1];
 8250:                    $subcount ++;
 8251:                }
 8252:                my $count = $subans[$subquestion-1];
 8253:                $lastbubble = $first + $count;
 8254:             } else {
 8255:                my ($first,$responsenum);
 8256:                if ($randomorder || $randompick) {
 8257:                    $responsenum = $respnumlookup{$missing-1};
 8258:                    $first = $startline{$missing-1};
 8259:                } else {
 8260:                    $responsenum = $missing-1;
 8261:                    $first = $first_bubble_line{$responsenum};
 8262:                }
 8263:                if (!defined($first)) { next; }
 8264:                $lastbubble = $first + $bubble_lines_per_response{$responsenum};
 8265:             }
 8266:             if ($lastbubble > $max_bubble) { next; }
 8267: 	    push(@to_correct,$missing);
 8268: 	}
 8269: 	if (@to_correct) {
 8270: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 8271: 				     $line,'missingbubble',\@to_correct,
 8272:                                      $randomorder,$randompick,\%respnumlookup,
 8273:                                      \%startline);
 8274: 	    return (1,$currentphase);
 8275: 	}
 8276: 
 8277:     }
 8278:     return (0,$currentphase+1);
 8279: }
 8280: 
 8281: sub hand_bubble_option {
 8282:     my (undef, undef, $sequence) =
 8283:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8284:     return if ($sequence eq '');
 8285:     my $navmap = Apache::lonnavmaps::navmap->new();
 8286:     unless (ref($navmap)) {
 8287:         return;
 8288:     }
 8289:     my $needs_hand_bubbles;
 8290:     my $map=$navmap->getResourceByUrl($sequence);
 8291:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8292:     foreach my $res (@resources) {
 8293:         if (ref($res)) {
 8294:             if ($res->is_problem()) {
 8295:                 my $partlist = $res->parts();
 8296:                 foreach my $part (@{ $partlist }) {
 8297:                     my @types = $res->responseType($part);
 8298:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
 8299:                         $needs_hand_bubbles = 1;
 8300:                         last;
 8301:                     }
 8302:                 }
 8303:             }
 8304:         }
 8305:     }
 8306:     if ($needs_hand_bubbles) {
 8307:         my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8308:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8309:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
 8310:                &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 />').
 8311:                '<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;'.
 8312:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
 8313:     }
 8314:     return;
 8315: }
 8316: 
 8317: sub scantron_process_students {
 8318:     my ($r,$symb) = @_;
 8319: 
 8320:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8321:     if (!$symb) {
 8322: 	return '';
 8323:     }
 8324:     my $default_form_data=&defaultFormData($symb);
 8325: 
 8326:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8327:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config); 
 8328:     my ($scanlines,$scan_data)=&scantron_getfile();
 8329:     my $classlist=&Apache::loncoursedata::get_classlist();
 8330:     my %idmap=&username_to_idmap($classlist);
 8331:     my $navmap=Apache::lonnavmaps::navmap->new();
 8332:     unless (ref($navmap)) {
 8333:         $r->print(&navmap_errormsg());
 8334:         return '';
 8335:     }
 8336:     my $map=$navmap->getResourceByUrl($sequence);
 8337:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8338:         %grader_randomlists_by_symb);
 8339:     if (ref($map)) {
 8340:         $randomorder = $map->randomorder();
 8341:         $randompick = $map->randompick();
 8342:     } else {
 8343:         $r->print(&navmap_errormsg());
 8344:         return '';
 8345:     }
 8346:     my $nav_error;
 8347:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8348:     if ($randomorder || $randompick) {
 8349:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8350:         if ($nav_error) {
 8351:             $r->print(&navmap_errormsg());
 8352:             return '';
 8353:         }
 8354:     }
 8355:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8356:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 8357: 
 8358:     my ($uname,$udom);
 8359:     my $result= <<SCANTRONFORM;
 8360: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 8361:   <input type="hidden" name="command" value="scantron_configphase" />
 8362:   $default_form_data
 8363: SCANTRONFORM
 8364:     $r->print($result);
 8365: 
 8366:     my @delayqueue;
 8367:     my (%completedstudents,%scandata);
 8368:     
 8369:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 8370:     my $count=&get_todo_count($scanlines,$scan_data);
 8371:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 8372:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
 8373:     $r->print('<br />');
 8374:     my $start=&Time::HiRes::time();
 8375:     my $i=-1;
 8376:     my $started;
 8377: 
 8378:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 8379:     if ($nav_error) {
 8380:         $r->print(&navmap_errormsg());
 8381:         return '';
 8382:     }
 8383: 
 8384:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 8385:     # the user and return.
 8386: 
 8387:     if ($ssi_error) {
 8388: 	$r->print("</form>");
 8389: 	&ssi_print_error($r);
 8390:         &Apache::lonnet::remove_lock($lock);
 8391: 	return '';		# Dunno why the other returns return '' rather than just returning.
 8392:     }
 8393: 
 8394:     my %lettdig = &letter_to_digits();
 8395:     my $numletts = scalar(keys(%lettdig));
 8396:     my %orderedforcode;
 8397: 
 8398:     while ($i<$scanlines->{'count'}) {
 8399:  	($uname,$udom)=('','');
 8400:  	$i++;
 8401:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8402:  	if ($line=~/^[\s\cz]*$/) { next; }
 8403: 	if ($started) {
 8404: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 8405: 	}
 8406: 	$started=1;
 8407:         my %respnumlookup = ();
 8408:         my %startline = ();
 8409:         my $total;
 8410:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8411:                                                  $scan_data,undef,\%idmap,$randomorder,
 8412:                                                  $randompick,$sequence,\@master_seq,
 8413:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8414:                                                  \%orderedforcode,\%respnumlookup,\%startline,
 8415:                                                  \$total);
 8416:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 8417:  					      \%idmap,$i)) {
 8418:   	    &scantron_add_delay(\@delayqueue,$line,
 8419:  				'Unable to find a student that matches',1);
 8420:  	    next;
 8421:   	}
 8422:  	if (exists $completedstudents{$uname}) {
 8423:  	    &scantron_add_delay(\@delayqueue,$line,
 8424:  				'Student '.$uname.' has multiple sheets',2);
 8425:  	    next;
 8426:  	}
 8427:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 8428:         my $user = $uname.':'.$usec;
 8429:   	($uname,$udom)=split(/:/,$uname);
 8430: 
 8431:         my $scancode;
 8432:         if ((exists($scan_record->{'scantron.CODE'})) &&
 8433:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 8434:             $scancode = $scan_record->{'scantron.CODE'};
 8435:         } else {
 8436:             $scancode = '';
 8437:         }
 8438: 
 8439:         my @mapresources = @resources;
 8440:         if ($randomorder || $randompick) {
 8441:             @mapresources = 
 8442:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 8443:                              \%orderedforcode);
 8444:         }
 8445:         my (%partids_by_symb,$res_error);
 8446:         foreach my $resource (@mapresources) {
 8447:             my $ressymb;
 8448:             if (ref($resource)) {
 8449:                 $ressymb = $resource->symb();
 8450:             } else {
 8451:                 $res_error = 1;
 8452:                 last;
 8453:             }
 8454:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8455:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8456:                 my ($analysis,$parts) =
 8457:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 8458:                                               $uname,$udom,undef,$bubbles_per_row);
 8459:                 $partids_by_symb{$ressymb} = $parts;
 8460:             } else {
 8461:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 8462:             }
 8463:         }
 8464: 
 8465:         if ($res_error) {
 8466:             &scantron_add_delay(\@delayqueue,$line,
 8467:                                 'An error occurred while grading student '.$uname,2);
 8468:             next;
 8469:         }
 8470: 
 8471: 	&Apache::lonxml::clear_problem_counter();
 8472:   	&Apache::lonnet::appenv($scan_record);
 8473: 
 8474: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 8475: 	    &scantron_putfile($scanlines,$scan_data);
 8476: 	}
 8477: 	
 8478:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8479:                                    \@mapresources,\%partids_by_symb,
 8480:                                    $bubbles_per_row,$randomorder,$randompick,
 8481:                                    \%respnumlookup,\%startline) 
 8482:             eq 'ssi_error') {
 8483:             $ssi_error = 0; # So end of handler error message does not trigger.
 8484:             $r->print("</form>");
 8485:             &ssi_print_error($r);
 8486:             &Apache::lonnet::remove_lock($lock);
 8487:             return '';      # Why return ''?  Beats me.
 8488:         }
 8489: 
 8490:         if (($scancode) && ($randomorder || $randompick)) {
 8491:             my $parmresult =
 8492:                 &Apache::lonparmset::storeparm_by_symb($symb,
 8493:                                                        '0_examcode',2,$scancode,
 8494:                                                        'string_examcode',$uname,
 8495:                                                        $udom);
 8496:         }
 8497: 	$completedstudents{$uname}={'line'=>$line};
 8498:         if ($env{'form.verifyrecord'}) {
 8499:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8500:             if ($randompick) {
 8501:                 if ($total) {
 8502:                     $lastpos = $total*$scantron_config{'Qlength'};
 8503:                 }
 8504:             }
 8505: 
 8506:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8507:             chomp($studentdata);
 8508:             $studentdata =~ s/\r$//;
 8509:             my $studentrecord = '';
 8510:             my $counter = -1;
 8511:             foreach my $resource (@mapresources) {
 8512:                 my $ressymb = $resource->symb();
 8513:                 ($counter,my $recording) =
 8514:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8515:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 8516:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
 8517:                                              $randompick,\%respnumlookup,\%startline);
 8518:                 $studentrecord .= $recording;
 8519:             }
 8520:             if ($studentrecord ne $studentdata) {
 8521:                 &Apache::lonxml::clear_problem_counter();
 8522:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8523:                                            \@mapresources,\%partids_by_symb,
 8524:                                            $bubbles_per_row,$randomorder,$randompick,
 8525:                                            \%respnumlookup,\%startline) 
 8526:                     eq 'ssi_error') {
 8527:                     $ssi_error = 0; # So end of handler error message does not trigger.
 8528:                     $r->print("</form>");
 8529:                     &ssi_print_error($r);
 8530:                     &Apache::lonnet::remove_lock($lock);
 8531:                     delete($completedstudents{$uname});
 8532:                     return '';
 8533:                 }
 8534:                 $counter = -1;
 8535:                 $studentrecord = '';
 8536:                 foreach my $resource (@mapresources) {
 8537:                     my $ressymb = $resource->symb();
 8538:                     ($counter,my $recording) =
 8539:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8540:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 8541:                                                  \%scantron_config,\%lettdig,$numletts,
 8542:                                                  $randomorder,$randompick,\%respnumlookup,
 8543:                                                  \%startline);
 8544:                     $studentrecord .= $recording;
 8545:                 }
 8546:                 if ($studentrecord ne $studentdata) {
 8547:                     $r->print('<p><span class="LC_warning">');
 8548:                     if ($scancode eq '') {
 8549:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
 8550:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 8551:                     } else {
 8552:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
 8553:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 8554:                     }
 8555:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 8556:                               &Apache::loncommon::start_data_table_header_row()."\n".
 8557:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 8558:                               &Apache::loncommon::end_data_table_header_row()."\n".
 8559:                               &Apache::loncommon::start_data_table_row().
 8560:                               '<td>'.&mt('Bubblesheet').'</td>'.
 8561:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
 8562:                               &Apache::loncommon::end_data_table_row().
 8563:                               &Apache::loncommon::start_data_table_row().
 8564:                               '<td>'.&mt('Stored submissions').'</td>'.
 8565:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
 8566:                               &Apache::loncommon::end_data_table_row().
 8567:                               &Apache::loncommon::end_data_table().'</p>');
 8568:                 } else {
 8569:                     $r->print('<br /><span class="LC_warning">'.
 8570:                              &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 />'.
 8571:                              &mt("As a consequence, this user's submission history records two tries.").
 8572:                                  '</span><br />');
 8573:                 }
 8574:             }
 8575:         }
 8576:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 8577:     } continue {
 8578: 	&Apache::lonxml::clear_problem_counter();
 8579: 	&Apache::lonnet::delenv('scantron.');
 8580:     }
 8581:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8582:     &Apache::lonnet::remove_lock($lock);
 8583: #    my $lasttime = &Time::HiRes::time()-$start;
 8584: #    $r->print("<p>took $lasttime</p>");
 8585: 
 8586:     $r->print("</form>");
 8587:     return '';
 8588: }
 8589: 
 8590: sub graders_resources_pass {
 8591:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
 8592:         $bubbles_per_row) = @_;
 8593:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 8594:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 8595:         foreach my $resource (@{$resources}) {
 8596:             my $ressymb = $resource->symb();
 8597:             my ($analysis,$parts) =
 8598:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 8599:                                           $env{'user.name'},$env{'user.domain'},
 8600:                                           1,$bubbles_per_row);
 8601:             $grader_partids_by_symb->{$ressymb} = $parts;
 8602:             if (ref($analysis) eq 'HASH') {
 8603:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 8604:                     $grader_randomlists_by_symb->{$ressymb} =
 8605:                         $analysis->{'parts_withrandomlist'};
 8606:                 }
 8607:             }
 8608:         }
 8609:     }
 8610:     return;
 8611: }
 8612: 
 8613: =pod
 8614: 
 8615: =item users_order
 8616: 
 8617:   Returns array of resources in current map, ordered based on either CODE,
 8618:   if this is a CODEd exam, or based on student's identity if this is a 
 8619:   "NAMEd" exam.
 8620: 
 8621:   Should be used when randomorder and/or randompick applied when the 
 8622:   corresponding exam was printed, prior to students completing bubblesheets 
 8623:   for the version of the exam the student received.
 8624: 
 8625: =cut
 8626: 
 8627: sub users_order  {
 8628:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
 8629:     my @mapresources;
 8630:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
 8631:         return @mapresources;
 8632:     }
 8633:     if ($scancode) {
 8634:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
 8635:             @mapresources = @{$orderedforcode->{$scancode}};
 8636:         } else {
 8637:             $env{'form.CODE'} = $scancode;
 8638:             my $actual_seq =
 8639:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 8640:                                                                $master_seq,
 8641:                                                                $user,$scancode,1);
 8642:             if (ref($actual_seq) eq 'ARRAY') {
 8643:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
 8644:                 if (ref($orderedforcode) eq 'HASH') {
 8645:                     if (@mapresources > 0) { 
 8646:                         $orderedforcode->{$scancode} = \@mapresources;
 8647:                     }
 8648:                 }
 8649:             }
 8650:             delete($env{'form.CODE'});
 8651:         }
 8652:     } else {
 8653:         my $actual_seq =
 8654:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 8655:                                                            $master_seq,
 8656:                                                            $user,undef,1);
 8657:         if (ref($actual_seq) eq 'ARRAY') {
 8658:             @mapresources = 
 8659:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
 8660:         }
 8661:     }
 8662:     return @mapresources;
 8663: }
 8664: 
 8665: sub grade_student_bubbles {
 8666:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
 8667:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
 8668:     my $uselookup = 0;
 8669:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
 8670:         (ref($startline) eq 'HASH')) {
 8671:         $uselookup = 1;
 8672:     }
 8673: 
 8674:     if (ref($resources) eq 'ARRAY') {
 8675:         my $count = 0;
 8676:         foreach my $resource (@{$resources}) {
 8677:             my $ressymb = $resource->symb();
 8678:             my %form = ('submitted'      => 'scantron',
 8679:                         'grade_target'   => 'grade',
 8680:                         'grade_username' => $uname,
 8681:                         'grade_domain'   => $udom,
 8682:                         'grade_courseid' => $env{'request.course.id'},
 8683:                         'grade_symb'     => $ressymb,
 8684:                         'CODE'           => $scancode
 8685:                        );
 8686:             if ($bubbles_per_row ne '') {
 8687:                 $form{'bubbles_per_row'} = $bubbles_per_row;
 8688:             }
 8689:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
 8690:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
 8691:             }
 8692:             if (ref($parts) eq 'HASH') {
 8693:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 8694:                     foreach my $part (@{$parts->{$ressymb}}) {
 8695:                         if ($uselookup) {
 8696:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
 8697:                         } else {
 8698:                             $form{'scantron_questnum_start.'.$part} =
 8699:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
 8700:                         }
 8701:                         $count++;
 8702:                     }
 8703:                 }
 8704:             }
 8705:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 8706:             return 'ssi_error' if ($ssi_error);
 8707:             last if (&Apache::loncommon::connection_aborted($r));
 8708:         }
 8709:     }
 8710:     return;
 8711: }
 8712: 
 8713: sub scantron_upload_scantron_data {
 8714:     my ($r,$symb)=@_;
 8715:     my $dom = $env{'request.role.domain'};
 8716:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 8717:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 8718:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 8719: 							  'domainid',
 8720: 							  'coursename',$dom);
 8721:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 8722:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
 8723:     my $default_form_data=&defaultFormData($symb);
 8724:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 8725:     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.");
 8726:     $r->print(&Apache::lonhtmlcommon::scripttag('
 8727:     function checkUpload(formname) {
 8728: 	if (formname.upfile.value == "") {
 8729: 	    alert("'.$nofile_alert.'");
 8730: 	    return false;
 8731: 	}
 8732:         if (formname.courseid.value == "") {
 8733:             alert("'.$nocourseid_alert.'");
 8734:             return false;
 8735:         }
 8736: 	formname.submit();
 8737:     }
 8738: 
 8739:     function ToSyllabus() {
 8740:         var cdom = '."'$dom'".';
 8741:         var cnum = document.rules.courseid.value;
 8742:         if (cdom == "" || cdom == null) {
 8743:             return;
 8744:         }
 8745:         if (cnum == "" || cnum == null) {
 8746:            return;
 8747:         }
 8748:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 8749:                             "height=350,width=350,scrollbars=yes,menubar=no");
 8750:         return;
 8751:     }
 8752: 
 8753: '));
 8754:     $r->print('
 8755: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
 8756: 
 8757: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 8758: '.$default_form_data.
 8759:   &Apache::lonhtmlcommon::start_pick_box().
 8760:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 8761:   '<input name="courseid" type="text" size="30" />'.$select_link.
 8762:   &Apache::lonhtmlcommon::row_closure().
 8763:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 8764:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 8765:   &Apache::lonhtmlcommon::row_closure().
 8766:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 8767:   '<input name="domainid" type="hidden" />'.$domdesc.
 8768:   &Apache::lonhtmlcommon::row_closure().
 8769:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 8770:   '<input type="file" name="upfile" size="50" />'.
 8771:   &Apache::lonhtmlcommon::row_closure(1).
 8772:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 8773: 
 8774: <input name="command" value="scantronupload_save" type="hidden" />
 8775: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 8776: </form>
 8777: ');
 8778:     return '';
 8779: }
 8780: 
 8781: 
 8782: sub scantron_upload_scantron_data_save {
 8783:     my($r,$symb)=@_;
 8784:     my $doanotherupload=
 8785: 	'<br /><form action="/adm/grades" method="post">'."\n".
 8786: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 8787: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 8788: 	'</form>'."\n";
 8789:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 8790: 	!&Apache::lonnet::allowed('usc',
 8791: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 8792: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 8793: 	unless ($symb) {
 8794: 	    $r->print($doanotherupload);
 8795: 	}
 8796: 	return '';
 8797:     }
 8798:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 8799:     my $uploadedfile;
 8800:     $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
 8801:     if (length($env{'form.upfile'}) < 2) {
 8802:         $r->print(
 8803:             &Apache::lonhtmlcommon::confirm_success(
 8804:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
 8805:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
 8806:     } else {
 8807:         my $result = 
 8808:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
 8809:                                             $env{'form.courseid'},$env{'form.domainid'});
 8810:         if ($result =~ m{^/uploaded/}) {
 8811:             $r->print(
 8812:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
 8813:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
 8814:                         (length($env{'form.upfile'})-1),
 8815:                         '<span class="LC_filename">'.$result.'</span>'));
 8816:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 8817:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 8818:                                                        $env{'form.courseid'},$uploadedfile));
 8819:         } else {
 8820:             $r->print(
 8821:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
 8822:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
 8823:                           $result,
 8824: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 8825: 	}
 8826:     }
 8827:     if ($symb) {
 8828: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
 8829:     } else {
 8830: 	$r->print($doanotherupload);
 8831:     }
 8832:     return '';
 8833: }
 8834: 
 8835: sub validate_uploaded_scantron_file {
 8836:     my ($cdom,$cname,$fname) = @_;
 8837:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 8838:     my @lines;
 8839:     if ($scanlines ne '-1') {
 8840:         @lines=split("\n",$scanlines,-1);
 8841:     }
 8842:     my $output;
 8843:     if (@lines) {
 8844:         my (%counts,$max_match_format);
 8845:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
 8846:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 8847:         my %idmap = &username_to_idmap($classlist);
 8848:         foreach my $key (keys(%idmap)) {
 8849:             my $lckey = lc($key);
 8850:             $idmap{$lckey} = $idmap{$key};
 8851:         }
 8852:         my %unique_formats;
 8853:         my @formatlines = &get_scantronformat_file();
 8854:         foreach my $line (@formatlines) {
 8855:             chomp($line);
 8856:             my @config = split(/:/,$line);
 8857:             my $idstart = $config[5];
 8858:             my $idlength = $config[6];
 8859:             if (($idstart ne '') && ($idlength > 0)) {
 8860:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 8861:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 8862:                 } else {
 8863:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 8864:                 }
 8865:             }
 8866:         }
 8867:         foreach my $key (keys(%unique_formats)) {
 8868:             my ($idstart,$idlength) = split(':',$key);
 8869:             %{$counts{$key}} = (
 8870:                                'found'   => 0,
 8871:                                'total'   => 0,
 8872:                               );
 8873:             foreach my $line (@lines) {
 8874:                 next if ($line =~ /^#/);
 8875:                 next if ($line =~ /^[\s\cz]*$/);
 8876:                 my $id = substr($line,$idstart-1,$idlength);
 8877:                 $id = lc($id);
 8878:                 if (exists($idmap{$id})) {
 8879:                     $counts{$key}{'found'} ++;
 8880:                 }
 8881:                 $counts{$key}{'total'} ++;
 8882:             }
 8883:             if ($counts{$key}{'total'}) {
 8884:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 8885:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 8886:                     $max_match_pct = $percent_match;
 8887:                     $max_match_format = $key;
 8888:                     $found_match_count = $counts{$key}{'found'};
 8889:                     $max_match_count = $counts{$key}{'total'};
 8890:                 }
 8891:             }
 8892:         }
 8893:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 8894:             my $format_descs;
 8895:             my $numwithformat = @{$unique_formats{$max_match_format}};
 8896:             for (my $i=0; $i<$numwithformat; $i++) {
 8897:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 8898:                 if ($i<$numwithformat-2) {
 8899:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 8900:                 } elsif ($i==$numwithformat-2) {
 8901:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 8902:                 } elsif ($i==$numwithformat-1) {
 8903:                     $format_descs .= '"<i>'.$desc.'</i>"';
 8904:                 }
 8905:             }
 8906:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 8907:             $output .= '<br />';
 8908:             if ($found_match_count == $max_match_count) {
 8909:                 # 100% matching entries
 8910:                 $output .= &Apache::lonhtmlcommon::confirm_success(
 8911:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
 8912:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
 8913:                 &mt('Comparison of student IDs in the uploaded file with'.
 8914:                     ' the course roster found matches for [_1] of the [_2] entries'.
 8915:                     ' in the file (for the format defined for [_3]).',
 8916:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
 8917:             } else {
 8918:                 # Not all entries matching? -> Show warning and additional info
 8919:                 $output .=
 8920:                     &Apache::lonhtmlcommon::confirm_success(
 8921:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
 8922:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
 8923:                         &mt('Not all entries could be matched!'),1).'<br />'.
 8924:                     &mt('Comparison of student IDs in the uploaded file with'.
 8925:                         ' the course roster found matches for [_1] of the [_2] entries'.
 8926:                         ' in the file (for the format defined for [_3]).',
 8927:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
 8928:                     '<p class="LC_info">'.
 8929:                     &mt('A low percentage of matches results from one of the following:').
 8930:                     '</p><ul>'.
 8931:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
 8932:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
 8933:                                '<i>'.$cdom.'</i>').'</li>'.
 8934:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 8935:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
 8936:                     '</ul>';
 8937:             }
 8938:         }
 8939:     } else {
 8940:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
 8941:     }
 8942:     return $output;
 8943: }
 8944: 
 8945: sub valid_file {
 8946:     my ($requested_file)=@_;
 8947:     foreach my $filename (sort(&scantron_filenames())) {
 8948: 	if ($requested_file eq $filename) { return 1; }
 8949:     }
 8950:     return 0;
 8951: }
 8952: 
 8953: sub scantron_download_scantron_data {
 8954:     my ($r,$symb)=@_;
 8955:     my $default_form_data=&defaultFormData($symb);
 8956:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8957:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8958:     my $file=$env{'form.scantron_selectfile'};
 8959:     if (! &valid_file($file)) {
 8960: 	$r->print('
 8961: 	<p>
 8962: 	    '.&mt('The requested filename was invalid.').'
 8963:         </p>
 8964: ');
 8965: 	return;
 8966:     }
 8967:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 8968:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 8969:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 8970:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 8971:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 8972:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 8973:     $r->print('
 8974:     <p>
 8975: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
 8976: 	      '<a href="'.$orig.'">','</a>').'
 8977:     </p>
 8978:     <p>
 8979: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 8980: 	      '<a href="'.$corrected.'">','</a>').'
 8981:     </p>
 8982:     <p>
 8983: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 8984: 	      '<a href="'.$skipped.'">','</a>').'
 8985:     </p>
 8986: ');
 8987:     return '';
 8988: }
 8989: 
 8990: sub checkscantron_results {
 8991:     my ($r,$symb) = @_;
 8992:     if (!$symb) {return '';}
 8993:     my $cid = $env{'request.course.id'};
 8994:     my %lettdig = &letter_to_digits();
 8995:     my $numletts = scalar(keys(%lettdig));
 8996:     my $cnum = $env{'course.'.$cid.'.num'};
 8997:     my $cdom = $env{'course.'.$cid.'.domain'};
 8998:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8999:     my %record;
 9000:     my %scantron_config =
 9001:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 9002:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 9003:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 9004:     my $classlist=&Apache::loncoursedata::get_classlist();
 9005:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 9006:     my $navmap=Apache::lonnavmaps::navmap->new();
 9007:     unless (ref($navmap)) {
 9008:         $r->print(&navmap_errormsg());
 9009:         return '';
 9010:     }
 9011:     my $map=$navmap->getResourceByUrl($sequence);
 9012:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 9013:         %grader_randomlists_by_symb,%orderedforcode);
 9014:     if (ref($map)) { 
 9015:         $randomorder=$map->randomorder();
 9016:         $randompick=$map->randompick();
 9017:     }
 9018:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 9019:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 9020:     if ($nav_error) {
 9021:         $r->print(&navmap_errormsg());
 9022:         return '';
 9023:     }
 9024:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 9025:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 9026:     my ($uname,$udom);
 9027:     my (%scandata,%lastname,%bylast);
 9028:     $r->print('
 9029: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 9030: 
 9031:     my @delayqueue;
 9032:     my %completedstudents;
 9033: 
 9034:     my $count=&get_todo_count($scanlines,$scan_data);
 9035:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 9036:     my ($username,$domain,$started);
 9037:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 9038:     if ($nav_error) {
 9039:         $r->print(&navmap_errormsg());
 9040:         return '';
 9041:     }
 9042: 
 9043:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
 9044:     my $start=&Time::HiRes::time();
 9045:     my $i=-1;
 9046: 
 9047:     while ($i<$scanlines->{'count'}) {
 9048:         ($username,$domain,$uname)=('','','');
 9049:         $i++;
 9050:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 9051:         if ($line=~/^[\s\cz]*$/) { next; }
 9052:         if ($started) {
 9053:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 9054:         }
 9055:         $started=1;
 9056:         my $scan_record=
 9057:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 9058:                                                      $scan_data);
 9059:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
 9060:                                               \%idmap,$i)) {
 9061:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9062:                                 'Unable to find a student that matches',1);
 9063:             next;
 9064:         }
 9065:         if (exists $completedstudents{$uname}) {
 9066:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9067:                                 'Student '.$uname.' has multiple sheets',2);
 9068:             next;
 9069:         }
 9070:         my $pid = $scan_record->{'scantron.ID'};
 9071:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 9072:         push(@{$bylast{$lastname{$pid}}},$pid);
 9073:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 9074:         my $user = $uname.':'.$usec;
 9075:         ($username,$domain)=split(/:/,$uname);
 9076: 
 9077:         my $scancode;
 9078:         if ((exists($scan_record->{'scantron.CODE'})) &&
 9079:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 9080:             $scancode = $scan_record->{'scantron.CODE'};
 9081:         } else {
 9082:             $scancode = '';
 9083:         }
 9084: 
 9085:         my @mapresources = @resources;
 9086:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 9087:         my %respnumlookup=();
 9088:         my %startline=();
 9089:         if ($randomorder || $randompick) {
 9090:             @mapresources =
 9091:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 9092:                              \%orderedforcode);
 9093:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
 9094:                                              $scan_record,\@master_seq,\%symb_to_resource,
 9095:                                              \%grader_partids_by_symb,\%orderedforcode,
 9096:                                              \%respnumlookup,\%startline);
 9097:             if ($randompick && $total) {
 9098:                 $lastpos = $total*$scantron_config{'Qlength'};
 9099:             }
 9100:         }
 9101:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 9102:         chomp($scandata{$pid});
 9103:         $scandata{$pid} =~ s/\r$//;
 9104: 
 9105:         my $counter = -1;
 9106:         foreach my $resource (@mapresources) {
 9107:             my $parts;
 9108:             my $ressymb = $resource->symb();
 9109:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 9110:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 9111:                 (my $analysis,$parts) =
 9112:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 9113:                                               $username,$domain,undef,
 9114:                                               $bubbles_per_row);
 9115:             } else {
 9116:                 $parts = $grader_partids_by_symb{$ressymb};
 9117:             }
 9118:             ($counter,my $recording) =
 9119:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 9120:                                          $scandata{$pid},$parts,
 9121:                                          \%scantron_config,\%lettdig,$numletts,
 9122:                                          $randomorder,$randompick,
 9123:                                          \%respnumlookup,\%startline);
 9124:             $record{$pid} .= $recording;
 9125:         }
 9126:     }
 9127:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 9128:     $r->print('<br />');
 9129:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 9130:     $passed = 0;
 9131:     $failed = 0;
 9132:     $numstudents = 0;
 9133:     foreach my $last (sort(keys(%bylast))) {
 9134:         if (ref($bylast{$last}) eq 'ARRAY') {
 9135:             foreach my $pid (sort(@{$bylast{$last}})) {
 9136:                 my $showscandata = $scandata{$pid};
 9137:                 my $showrecord = $record{$pid};
 9138:                 $showscandata =~ s/\s/&nbsp;/g;
 9139:                 $showrecord =~ s/\s/&nbsp;/g;
 9140:                 if ($scandata{$pid} eq $record{$pid}) {
 9141:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 9142:                     $okstudents .= '<tr class="'.$css_class.'">'.
 9143: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 9144: '</tr>'."\n".
 9145: '<tr class="'.$css_class.'">'."\n".
 9146: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
 9147:                     $passed ++;
 9148:                 } else {
 9149:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 9150:                     $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".
 9151: '</tr>'."\n".
 9152: '<tr class="'.$css_class.'">'."\n".
 9153: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 9154: '</tr>'."\n";
 9155:                     $failed ++;
 9156:                 }
 9157:                 $numstudents ++;
 9158:             }
 9159:         }
 9160:     }
 9161:     $r->print(
 9162:         '<p>'
 9163:        .&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).',
 9164:             '<b>',
 9165:             $numstudents,
 9166:             '</b>',
 9167:             $env{'form.scantron_maxbubble'})
 9168:        .'</p>'
 9169:     );
 9170:     $r->print('<p>'
 9171:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
 9172:              .'<br />'
 9173:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
 9174:              .'</p>'
 9175:     );
 9176:     if ($passed) {
 9177:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 9178:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9179:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9180:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9181:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9182:                  $okstudents."\n".
 9183:                  &Apache::loncommon::end_data_table().'<br />');
 9184:     }
 9185:     if ($failed) {
 9186:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 9187:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9188:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9189:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9190:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9191:                  $badstudents."\n".
 9192:                  &Apache::loncommon::end_data_table()).'<br />'.
 9193:                  &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.');  
 9194:     }
 9195:     $r->print('</form><br />');
 9196:     return;
 9197: }
 9198: 
 9199: sub verify_scantron_grading {
 9200:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 9201:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
 9202:         $respnumlookup,$startline) = @_;
 9203:     my ($record,%expected,%startpos);
 9204:     return ($counter,$record) if (!ref($resource));
 9205:     return ($counter,$record) if (!$resource->is_problem());
 9206:     my $symb = $resource->symb();
 9207:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 9208:     foreach my $part_id (@{$partids}) {
 9209:         $counter ++;
 9210:         $expected{$part_id} = 0;
 9211:         my $respnum = $counter;
 9212:         if ($randomorder || $randompick) {
 9213:             $respnum = $respnumlookup->{$counter};
 9214:             $startpos{$part_id} = $startline->{$counter} + 1;
 9215:         } else {
 9216:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 9217:         }
 9218:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
 9219:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
 9220:             foreach my $item (@sub_lines) {
 9221:                 $expected{$part_id} += $item;
 9222:             }
 9223:         } else {
 9224:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
 9225:         }
 9226:     }
 9227:     if ($symb) {
 9228:         my %recorded;
 9229:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 9230:         if ($returnhash{'version'}) {
 9231:             my %lasthash=();
 9232:             my $version;
 9233:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 9234:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 9235:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 9236:                 }
 9237:             }
 9238:             foreach my $key (keys(%lasthash)) {
 9239:                 if ($key =~ /\.scantron$/) {
 9240:                     my $value = &unescape($lasthash{$key});
 9241:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 9242:                     if ($value eq '') {
 9243:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 9244:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 9245:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9246:                             }
 9247:                         }
 9248:                     } else {
 9249:                         my @tocheck;
 9250:                         my @items = split(//,$value);
 9251:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 9252:                             ($scantron_config->{'Qon'} eq 'number')) {
 9253:                             if (@items < $expected{$part_id}) {
 9254:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 9255:                                 my @singles = split(//,$fragment);
 9256:                                 foreach my $pos (@singles) {
 9257:                                     if ($pos eq ' ') {
 9258:                                         push(@tocheck,$pos);
 9259:                                     } else {
 9260:                                         my $next = shift(@items);
 9261:                                         push(@tocheck,$next);
 9262:                                     }
 9263:                                 }
 9264:                             } else {
 9265:                                 @tocheck = @items;
 9266:                             }
 9267:                             foreach my $letter (@tocheck) {
 9268:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 9269:                                     if ($letter !~ /^[A-J]$/) {
 9270:                                         $letter = $scantron_config->{'Qoff'};
 9271:                                     }
 9272:                                     $recorded{$part_id} .= $letter;
 9273:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 9274:                                     my $digit;
 9275:                                     if ($letter !~ /^[A-J]$/) {
 9276:                                         $digit = $scantron_config->{'Qoff'};
 9277:                                     } else {
 9278:                                         $digit = $lettdig->{$letter};
 9279:                                     }
 9280:                                     $recorded{$part_id} .= $digit;
 9281:                                 }
 9282:                             }
 9283:                         } else {
 9284:                             @tocheck = @items;
 9285:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 9286:                                 my $curr_sub = shift(@tocheck);
 9287:                                 my $digit;
 9288:                                 if ($curr_sub =~ /^[A-J]$/) {
 9289:                                     $digit = $lettdig->{$curr_sub}-1;
 9290:                                 }
 9291:                                 if ($curr_sub eq 'J') {
 9292:                                     $digit += scalar($numletts);
 9293:                                 }
 9294:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9295:                                     if ($j == $digit) {
 9296:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 9297:                                     } else {
 9298:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9299:                                     }
 9300:                                 }
 9301:                             }
 9302:                         }
 9303:                     }
 9304:                 }
 9305:             }
 9306:         }
 9307:         foreach my $part_id (@{$partids}) {
 9308:             if ($recorded{$part_id} eq '') {
 9309:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 9310:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9311:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9312:                     }
 9313:                 }
 9314:             }
 9315:             $record .= $recorded{$part_id};
 9316:         }
 9317:     }
 9318:     return ($counter,$record);
 9319: }
 9320: 
 9321: sub letter_to_digits {
 9322:     my %lettdig = (
 9323:                     A => 1,
 9324:                     B => 2,
 9325:                     C => 3,
 9326:                     D => 4,
 9327:                     E => 5,
 9328:                     F => 6,
 9329:                     G => 7,
 9330:                     H => 8,
 9331:                     I => 9,
 9332:                     J => 0,
 9333:                   );
 9334:     return %lettdig;
 9335: }
 9336: 
 9337: 
 9338: #-------- end of section for handling grading scantron forms -------
 9339: #
 9340: #-------------------------------------------------------------------
 9341: 
 9342: #-------------------------- Menu interface -------------------------
 9343: #
 9344: #--- Href with symb and command ---
 9345: 
 9346: sub href_symb_cmd {
 9347:     my ($symb,$cmd)=@_;
 9348:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
 9349: }
 9350: 
 9351: sub grading_menu {
 9352:     my ($request,$symb) = @_;
 9353:     if (!$symb) {return '';}
 9354: 
 9355:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 9356:                   'command'=>'individual');
 9357:     
 9358:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9359: 
 9360:     $fields{'command'}='ungraded';
 9361:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9362: 
 9363:     $fields{'command'}='table';
 9364:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9365: 
 9366:     $fields{'command'}='all_for_one';
 9367:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9368: 
 9369:     $fields{'command'}='downloadfilesselect';
 9370:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9371: 
 9372:     $fields{'command'} = 'csvform';
 9373:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9374:     
 9375:     $fields{'command'} = 'processclicker';
 9376:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9377:     
 9378:     $fields{'command'} = 'scantron_selectphase';
 9379:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9380: 
 9381:     $fields{'command'} = 'initialverifyreceipt';
 9382:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9383:     
 9384:     my @menu = ({	categorytitle=>'Hand Grading',
 9385:             items =>[
 9386:                         {	linktext => 'Select individual students to grade',
 9387:                     		url => $url1a,
 9388:                     		permission => 'F',
 9389:                     		icon => 'grade_students.png',
 9390:                     		linktitle => 'Grade current resource for a selection of students.'
 9391:                         }, 
 9392:                         {       linktext => 'Grade ungraded submissions.',
 9393:                                 url => $url1b,
 9394:                                 permission => 'F',
 9395:                                 icon => 'ungrade_sub.png',
 9396:                                 linktitle => 'Grade all submissions that have not been graded yet.'
 9397:                         },
 9398: 
 9399:                         {       linktext => 'Grading table',
 9400:                                 url => $url1c,
 9401:                                 permission => 'F',
 9402:                                 icon => 'grading_table.png',
 9403:                                 linktitle => 'Grade current resource for all students.'
 9404:                         },
 9405:                         {       linktext => 'Grade page/folder for one student',
 9406:                                 url => $url1d,
 9407:                                 permission => 'F',
 9408:                                 icon => 'grade_PageFolder.png',
 9409:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
 9410:                         },
 9411:                         {       linktext => 'Download submissions',
 9412:                                 url => $url1e,
 9413:                                 permission => 'F',
 9414:                                 icon => 'download_sub.png',
 9415:                                 linktitle => 'Download all students submissions.'
 9416:                         }]},
 9417:                          { categorytitle=>'Automated Grading',
 9418:                items =>[
 9419: 
 9420:                 	    {	linktext => 'Upload Scores',
 9421:                     		url => $url2,
 9422:                     		permission => 'F',
 9423:                     		icon => 'uploadscores.png',
 9424:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 9425:                 	    },
 9426:                 	    {	linktext => 'Process Clicker',
 9427:                     		url => $url3,
 9428:                     		permission => 'F',
 9429:                     		icon => 'addClickerInfoFile.png',
 9430:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 9431:                 	    },
 9432:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
 9433:                     		url => $url4,
 9434:                     		permission => 'F',
 9435:                     		icon => 'bubblesheet.png',
 9436:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
 9437:                 	    },
 9438:                             {   linktext => 'Verify Receipt Number',
 9439:                                 url => $url5,
 9440:                                 permission => 'F',
 9441:                                 icon => 'receipt_number.png',
 9442:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
 9443:                             }
 9444: 
 9445:                     ]
 9446:             });
 9447: 
 9448:     # Create the menu
 9449:     my $Str;
 9450:     $Str .= '<form method="post" action="" name="gradingMenu">';
 9451:     $Str .= '<input type="hidden" name="command" value="" />'.
 9452:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9453: 
 9454:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
 9455:     return $Str;    
 9456: }
 9457: 
 9458: 
 9459: sub ungraded {
 9460:     my ($request)=@_;
 9461:     &submit_options($request);
 9462: }
 9463: 
 9464: sub submit_options_sequence {
 9465:     my ($request,$symb) = @_;
 9466:     if (!$symb) {return '';}
 9467:     &commonJSfunctions($request);
 9468:     my $result;
 9469: 
 9470:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9471:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9472:     $result.=&selectfield(0).
 9473:             '<input type="hidden" name="command" value="pickStudentPage" />
 9474:             <div>
 9475:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 9476:             </div>
 9477:         </div>
 9478:   </form>';
 9479:     return $result;
 9480: }
 9481: 
 9482: sub submit_options_table {
 9483:     my ($request,$symb) = @_;
 9484:     if (!$symb) {return '';}
 9485:     &commonJSfunctions($request);
 9486:     my $result;
 9487: 
 9488:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9489:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9490: 
 9491:     $result.=&selectfield(0).
 9492:             '<input type="hidden" name="command" value="viewgrades" />
 9493:             <div>
 9494:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 9495:             </div>
 9496:         </div>
 9497:   </form>';
 9498:     return $result;
 9499: }
 9500: 
 9501: sub submit_options_download {
 9502:     my ($request,$symb) = @_;
 9503:     if (!$symb) {return '';}
 9504: 
 9505:     &commonJSfunctions($request);
 9506: 
 9507:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9508:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9509:     $result.='
 9510: <h2>
 9511:   '.&mt('Select Students for Which to Download Submissions').'
 9512: </h2>'.&selectfield(1).'
 9513:                 <input type="hidden" name="command" value="downloadfileslink" /> 
 9514:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 9515:             </div>
 9516:           </div>
 9517: 
 9518: 
 9519:   </form>';
 9520:     return $result;
 9521: }
 9522: 
 9523: #--- Displays the submissions first page -------
 9524: sub submit_options {
 9525:     my ($request,$symb) = @_;
 9526:     if (!$symb) {return '';}
 9527: 
 9528:     &commonJSfunctions($request);
 9529:     my $result;
 9530: 
 9531:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9532: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9533:     $result.=&selectfield(1).'
 9534:                 <input type="hidden" name="command" value="submission" /> 
 9535: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
 9536:             </div>
 9537:           </div>
 9538: 
 9539: 
 9540:   </form>';
 9541:     return $result;
 9542: }
 9543: 
 9544: sub selectfield {
 9545:    my ($full)=@_;
 9546:    my %options = 
 9547:           (&Apache::lonlocal::texthash(
 9548:              'yes'       => 'with submissions',
 9549:              'queued'    => 'in grading queue',
 9550:              'graded'    => 'with ungraded submissions',
 9551:              'incorrect' => 'with incorrect submissions',
 9552:              'all'       => 'with any status'),
 9553:              'select_form_order' => ['yes','queued','graded','incorrect','all']);
 9554:    my $result='<div class="LC_columnSection">
 9555:   
 9556:     <fieldset>
 9557:       <legend>
 9558:        '.&mt('Sections').'
 9559:       </legend>
 9560:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
 9561:     </fieldset>
 9562:   
 9563:     <fieldset>
 9564:       <legend>
 9565:         '.&mt('Groups').'
 9566:       </legend>
 9567:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 9568:     </fieldset>
 9569:   
 9570:     <fieldset>
 9571:       <legend>
 9572:         '.&mt('Access Status').'
 9573:       </legend>
 9574:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
 9575:     </fieldset>';
 9576:     if ($full) {
 9577:        $result.='
 9578:     <fieldset>
 9579:       <legend>
 9580:         '.&mt('Submission Status').'
 9581:       </legend>'.
 9582:        &Apache::loncommon::select_form('all','submitonly',\%options).
 9583:    '</fieldset>';
 9584:     }
 9585:     $result.='</div><br />';
 9586:     return $result;
 9587: }
 9588: 
 9589: sub reset_perm {
 9590:     undef(%perm);
 9591: }
 9592: 
 9593: sub init_perm {
 9594:     &reset_perm();
 9595:     foreach my $test_perm ('vgr','mgr','opa') {
 9596: 
 9597: 	my $scope = $env{'request.course.id'};
 9598: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 9599: 
 9600: 	    $scope .= '/'.$env{'request.course.sec'};
 9601: 	    if ( $perm{$test_perm}=
 9602: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 9603: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 9604: 	    } else {
 9605: 		delete($perm{$test_perm});
 9606: 	    }
 9607: 	}
 9608:     }
 9609: }
 9610: 
 9611: sub init_old_essays {
 9612:     my ($symb,$apath,$adom,$aname) = @_;
 9613:     if ($symb ne '') {
 9614:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 9615:         if (keys(%essays) > 0) {
 9616:             $old_essays{$symb} = \%essays;
 9617:         }
 9618:     }
 9619:     return;
 9620: }
 9621: 
 9622: sub reset_old_essays {
 9623:     undef(%old_essays);
 9624: }
 9625: 
 9626: sub gather_clicker_ids {
 9627:     my %clicker_ids;
 9628: 
 9629:     my $classlist = &Apache::loncoursedata::get_classlist();
 9630: 
 9631:     # Set up a couple variables.
 9632:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 9633:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 9634:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 9635: 
 9636:     foreach my $student (keys(%$classlist)) {
 9637:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 9638:         my $username = $classlist->{$student}->[$username_idx];
 9639:         my $domain   = $classlist->{$student}->[$domain_idx];
 9640:         my $clickers =
 9641: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 9642:         foreach my $id (split(/\,/,$clickers)) {
 9643:             $id=~s/^[\#0]+//;
 9644:             $id=~s/[\-\:]//g;
 9645:             if (exists($clicker_ids{$id})) {
 9646: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 9647:             } else {
 9648: 		$clicker_ids{$id}=$username.':'.$domain;
 9649:             }
 9650:         }
 9651:     }
 9652:     return %clicker_ids;
 9653: }
 9654: 
 9655: sub gather_adv_clicker_ids {
 9656:     my %clicker_ids;
 9657:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 9658:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9659:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 9660:     foreach my $element (sort(keys(%coursepersonnel))) {
 9661:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 9662:             my ($puname,$pudom)=split(/\:/,$person);
 9663:             my $clickers =
 9664: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 9665:             foreach my $id (split(/\,/,$clickers)) {
 9666: 		$id=~s/^[\#0]+//;
 9667:                 $id=~s/[\-\:]//g;
 9668: 		if (exists($clicker_ids{$id})) {
 9669: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 9670: 		} else {
 9671: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 9672: 		}
 9673:             }
 9674:         }
 9675:     }
 9676:     return %clicker_ids;
 9677: }
 9678: 
 9679: sub clicker_grading_parameters {
 9680:     return ('gradingmechanism' => 'scalar',
 9681:             'upfiletype' => 'scalar',
 9682:             'specificid' => 'scalar',
 9683:             'pcorrect' => 'scalar',
 9684:             'pincorrect' => 'scalar');
 9685: }
 9686: 
 9687: sub process_clicker {
 9688:     my ($r,$symb)=@_;
 9689:     if (!$symb) {return '';}
 9690:     my $result=&checkforfile_js();
 9691:     $result.=&Apache::loncommon::start_data_table().
 9692:              &Apache::loncommon::start_data_table_header_row().
 9693:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
 9694:              &Apache::loncommon::end_data_table_header_row().
 9695:              &Apache::loncommon::start_data_table_row()."<td>\n";
 9696: # Attempt to restore parameters from last session, set defaults if not present
 9697:     my %Saveable_Parameters=&clicker_grading_parameters();
 9698:     &Apache::loncommon::restore_course_settings('grades_clicker',
 9699:                                                  \%Saveable_Parameters);
 9700:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 9701:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 9702:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 9703:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 9704: 
 9705:     my %checked;
 9706:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 9707:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 9708:           $checked{$gradingmechanism}=' checked="checked"';
 9709:        }
 9710:     }
 9711: 
 9712:     my $upload=&mt("Evaluate File");
 9713:     my $type=&mt("Type");
 9714:     my $attendance=&mt("Award points just for participation");
 9715:     my $personnel=&mt("Correctness determined from response by course personnel");
 9716:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 9717:     my $given=&mt("Correctness determined from given list of answers").' '.
 9718:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 9719:     my $pcorrect=&mt("Percentage points for correct solution");
 9720:     my $pincorrect=&mt("Percentage points for incorrect solution");
 9721:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 9722: 						   {'iclicker' => 'i>clicker',
 9723:                                                     'interwrite' => 'interwrite PRS',
 9724:                                                     'turning' => 'Turning Technologies'});
 9725:     $symb = &Apache::lonenc::check_encrypt($symb);
 9726:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
 9727: function sanitycheck() {
 9728: // Accept only integer percentages
 9729:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 9730:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 9731: // Find out grading choice
 9732:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 9733:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 9734:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 9735:       }
 9736:    }
 9737: // By default, new choice equals user selection
 9738:    newgradingchoice=gradingchoice;
 9739: // Not good to give more points for false answers than correct ones
 9740:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 9741:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 9742:    }
 9743: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 9744:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 9745:       document.forms.gradesupload.pcorrect.value=100;
 9746:       document.forms.gradesupload.pincorrect.value=100;
 9747:    }
 9748: // If the values are different, cannot be attendance only
 9749:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 9750:        (gradingchoice=='attendance')) {
 9751:        newgradingchoice='personnel';
 9752:    }
 9753: // Change grading choice to new one
 9754:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 9755:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 9756:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 9757:       } else {
 9758:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 9759:       }
 9760:    }
 9761: // Remember the old state
 9762:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 9763: }
 9764: ENDUPFORM
 9765:     $result.= <<ENDUPFORM;
 9766: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 9767: <input type="hidden" name="symb" value="$symb" />
 9768: <input type="hidden" name="command" value="processclickerfile" />
 9769: <input type="file" name="upfile" size="50" />
 9770: <br /><label>$type: $selectform</label>
 9771: ENDUPFORM
 9772:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
 9773:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
 9774:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
 9775: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
 9776: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
 9777: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 9778: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
 9779: <br />&nbsp;&nbsp;&nbsp;
 9780: <input type="text" name="givenanswer" size="50" />
 9781: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 9782: ENDGRADINGFORM
 9783:          $result.='</td>'.&Apache::loncommon::end_data_table_row().
 9784:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
 9785:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
 9786: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
 9787: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 9788: </form>'
 9789: ENDPERCFORM
 9790:     $result.='</td>'.
 9791:              &Apache::loncommon::end_data_table_row().
 9792:              &Apache::loncommon::end_data_table();
 9793:     return $result;
 9794: }
 9795: 
 9796: sub process_clicker_file {
 9797:     my ($r,$symb)=@_;
 9798:     if (!$symb) {return '';}
 9799: 
 9800:     my %Saveable_Parameters=&clicker_grading_parameters();
 9801:     &Apache::loncommon::store_course_settings('grades_clicker',
 9802:                                               \%Saveable_Parameters);
 9803:     my $result='';
 9804:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 9805: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 9806: 	return $result;
 9807:     }
 9808:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 9809:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 9810:         return $result;
 9811:     }
 9812:     my $foundgiven=0;
 9813:     if ($env{'form.gradingmechanism'} eq 'given') {
 9814:         $env{'form.givenanswer'}=~s/^\s*//gs;
 9815:         $env{'form.givenanswer'}=~s/\s*$//gs;
 9816:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
 9817:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 9818:         my @answers=split(/\,/,$env{'form.givenanswer'});
 9819:         $foundgiven=$#answers+1;
 9820:     }
 9821:     my %clicker_ids=&gather_clicker_ids();
 9822:     my %correct_ids;
 9823:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 9824: 	%correct_ids=&gather_adv_clicker_ids();
 9825:     }
 9826:     if ($env{'form.gradingmechanism'} eq 'specific') {
 9827: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 9828: 	   $correct_id=~tr/a-z/A-Z/;
 9829: 	   $correct_id=~s/\s//gs;
 9830: 	   $correct_id=~s/^[\#0]+//;
 9831:            $correct_id=~s/[\-\:]//g;
 9832:            if ($correct_id) {
 9833: 	      $correct_ids{$correct_id}='specified';
 9834:            }
 9835:         }
 9836:     }
 9837:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 9838: 	$result.=&mt('Score based on attendance only');
 9839:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
 9840:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
 9841:     } else {
 9842: 	my $number=0;
 9843: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 9844: 	foreach my $id (sort(keys(%correct_ids))) {
 9845: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 9846: 	    if ($correct_ids{$id} eq 'specified') {
 9847: 		$result.=&mt('specified');
 9848: 	    } else {
 9849: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 9850: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 9851: 	    }
 9852: 	    $number++;
 9853: 	}
 9854:         $result.="</p>\n";
 9855:         if ($number==0) {
 9856:             $result .=
 9857:                  &Apache::lonhtmlcommon::confirm_success(
 9858:                      &mt('No IDs found to determine correct answer'),1);
 9859:             return $result;
 9860:         }
 9861:     }
 9862:     if (length($env{'form.upfile'}) < 2) {
 9863:         $result .=
 9864:             &Apache::lonhtmlcommon::confirm_success(
 9865:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
 9866:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
 9867:         return $result;
 9868:     }
 9869: 
 9870: # Were able to get all the info needed, now analyze the file
 9871: 
 9872:     $result.=&Apache::loncommon::studentbrowser_javascript();
 9873:     $symb = &Apache::lonenc::check_encrypt($symb);
 9874:     $result.=&Apache::loncommon::start_data_table().
 9875:              &Apache::loncommon::start_data_table_header_row().
 9876:              '<th>'.&mt('Evaluate clicker file').'</th>'.
 9877:              &Apache::loncommon::end_data_table_header_row().
 9878:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
 9879: <td>
 9880: <form method="post" action="/adm/grades" name="clickeranalysis">
 9881: <input type="hidden" name="symb" value="$symb" />
 9882: <input type="hidden" name="command" value="assignclickergrades" />
 9883: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 9884: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 9885: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 9886: ENDHEADER
 9887:     if ($env{'form.gradingmechanism'} eq 'given') {
 9888:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
 9889:     } 
 9890:     my %responses;
 9891:     my @questiontitles;
 9892:     my $errormsg='';
 9893:     my $number=0;
 9894:     if ($env{'form.upfiletype'} eq 'iclicker') {
 9895: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 9896:     }
 9897:     if ($env{'form.upfiletype'} eq 'interwrite') {
 9898:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 9899:     }
 9900:     if ($env{'form.upfiletype'} eq 'turning') {
 9901:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
 9902:     }
 9903:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 9904:              '<input type="hidden" name="number" value="'.$number.'" />'.
 9905:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 9906:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 9907:              '<br />';
 9908:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
 9909:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
 9910:        return $result;
 9911:     } 
 9912: # Remember Question Titles
 9913: # FIXME: Possibly need delimiter other than ":"
 9914:     for (my $i=0;$i<$number;$i++) {
 9915:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 9916:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 9917:     }
 9918:     my $correct_count=0;
 9919:     my $student_count=0;
 9920:     my $unknown_count=0;
 9921: # Match answers with usernames
 9922: # FIXME: Possibly need delimiter other than ":"
 9923:     foreach my $id (keys(%responses)) {
 9924:        if ($correct_ids{$id}) {
 9925:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 9926:           $correct_count++;
 9927:        } elsif ($clicker_ids{$id}) {
 9928:           if ($clicker_ids{$id}=~/\,/) {
 9929: # More than one user with the same clicker!
 9930:              $result.="</td>".&Apache::loncommon::end_data_table_row().
 9931:                            &Apache::loncommon::start_data_table_row()."<td>".
 9932:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 9933:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9934:                            "<select name='multi".$id."'>";
 9935:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 9936:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 9937:              }
 9938:              $result.='</select>';
 9939:              $unknown_count++;
 9940:           } else {
 9941: # Good: found one and only one user with the right clicker
 9942:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 9943:              $student_count++;
 9944:           }
 9945:        } else {
 9946:           $result.="</td>".&Apache::loncommon::end_data_table_row().
 9947:                            &Apache::loncommon::start_data_table_row()."<td>".
 9948:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 9949:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9950:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 9951:                    "\n".&mt("Domain").": ".
 9952:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 9953:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
 9954:           $unknown_count++;
 9955:        }
 9956:     }
 9957:     $result.='<hr />'.
 9958:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 9959:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
 9960:        if ($correct_count==0) {
 9961:           $errormsg.="Found no correct answers for grading!";
 9962:        } elsif ($correct_count>1) {
 9963:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 9964:        }
 9965:     }
 9966:     if ($number<1) {
 9967:        $errormsg.="Found no questions.";
 9968:     }
 9969:     if ($errormsg) {
 9970:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 9971:     } else {
 9972:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 9973:     }
 9974:     $result.='</form></td>'.
 9975:              &Apache::loncommon::end_data_table_row().
 9976:              &Apache::loncommon::end_data_table();
 9977:     return $result;
 9978: }
 9979: 
 9980: sub iclicker_eval {
 9981:     my ($questiontitles,$responses)=@_;
 9982:     my $number=0;
 9983:     my $errormsg='';
 9984:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9985:         my %components=&Apache::loncommon::record_sep($line);
 9986:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9987: 	if ($entries[0] eq 'Question') {
 9988: 	    for (my $i=3;$i<$#entries;$i+=6) {
 9989: 		$$questiontitles[$number]=$entries[$i];
 9990: 		$number++;
 9991: 	    }
 9992: 	}
 9993: 	if ($entries[0]=~/^\#/) {
 9994: 	    my $id=$entries[0];
 9995: 	    my @idresponses;
 9996: 	    $id=~s/^[\#0]+//;
 9997: 	    for (my $i=0;$i<$number;$i++) {
 9998: 		my $idx=3+$i*6;
 9999:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
10000: 		push(@idresponses,$entries[$idx]);
10001: 	    }
10002: 	    $$responses{$id}=join(',',@idresponses);
10003: 	}
10004:     }
10005:     return ($errormsg,$number);
10006: }
10007: 
10008: sub interwrite_eval {
10009:     my ($questiontitles,$responses)=@_;
10010:     my $number=0;
10011:     my $errormsg='';
10012:     my $skipline=1;
10013:     my $questionnumber=0;
10014:     my %idresponses=();
10015:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10016:         my %components=&Apache::loncommon::record_sep($line);
10017:         my @entries=map {$components{$_}} (sort(keys(%components)));
10018:         if ($entries[1] eq 'Time') { $skipline=0; next; }
10019:         if ($entries[1] eq 'Response') { $skipline=1; }
10020:         next if $skipline;
10021:         if ($entries[0]!=$questionnumber) {
10022:            $questionnumber=$entries[0];
10023:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
10024:            $number++;
10025:         }
10026:         my $id=$entries[4];
10027:         $id=~s/^[\#0]+//;
10028:         $id=~s/^v\d*\://i;
10029:         $id=~s/[\-\:]//g;
10030:         $idresponses{$id}[$number]=$entries[6];
10031:     }
10032:     foreach my $id (keys(%idresponses)) {
10033:        $$responses{$id}=join(',',@{$idresponses{$id}});
10034:        $$responses{$id}=~s/^\s*\,//;
10035:     }
10036:     return ($errormsg,$number);
10037: }
10038: 
10039: sub turning_eval {
10040:     my ($questiontitles,$responses)=@_;
10041:     my $number=0;
10042:     my $errormsg='';
10043:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10044:         my %components=&Apache::loncommon::record_sep($line);
10045:         my @entries=map {$components{$_}} (sort(keys(%components)));
10046:         if ($#entries>$number) { $number=$#entries; }
10047:         my $id=$entries[0];
10048:         my @idresponses;
10049:         $id=~s/^[\#0]+//;
10050:         unless ($id) { next; }
10051:         for (my $idx=1;$idx<=$#entries;$idx++) {
10052:             $entries[$idx]=~s/\,/\;/g;
10053:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
10054:             push(@idresponses,$entries[$idx]);
10055:         }
10056:         $$responses{$id}=join(',',@idresponses);
10057:     }
10058:     for (my $i=1; $i<=$number; $i++) {
10059:         $$questiontitles[$i]=&mt('Question [_1]',$i);
10060:     }
10061:     return ($errormsg,$number);
10062: }
10063: 
10064: 
10065: sub assign_clicker_grades {
10066:     my ($r,$symb)=@_;
10067:     if (!$symb) {return '';}
10068: # See which part we are saving to
10069:     my $res_error;
10070:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
10071:     if ($res_error) {
10072:         return &navmap_errormsg();
10073:     }
10074: # FIXME: This should probably look for the first handgradeable part
10075:     my $part=$$partlist[0];
10076: # Start screen output
10077:     my $result=&Apache::loncommon::start_data_table().
10078:              &Apache::loncommon::start_data_table_header_row().
10079:              '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
10080:              &Apache::loncommon::end_data_table_header_row().
10081:              &Apache::loncommon::start_data_table_row().'<td>';
10082: # Get correct result
10083: # FIXME: Possibly need delimiter other than ":"
10084:     my @correct=();
10085:     my $gradingmechanism=$env{'form.gradingmechanism'};
10086:     my $number=$env{'form.number'};
10087:     if ($gradingmechanism ne 'attendance') {
10088:        foreach my $key (keys(%env)) {
10089:           if ($key=~/^form\.correct\:/) {
10090:              my @input=split(/\,/,$env{$key});
10091:              for (my $i=0;$i<=$#input;$i++) {
10092:                  if (($correct[$i]) && ($input[$i]) &&
10093:                      ($correct[$i] ne $input[$i])) {
10094:                     $result.='<br /><span class="LC_warning">'.
10095:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
10096:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
10097:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
10098:                     $correct[$i]=$input[$i];
10099:                  }
10100:              }
10101:           }
10102:        }
10103:        for (my $i=0;$i<$number;$i++) {
10104:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
10105:              $result.='<br /><span class="LC_error">'.
10106:                       &mt('No correct result given for question "[_1]"!',
10107:                           $env{'form.question:'.$i}).'</span>';
10108:           }
10109:        }
10110:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
10111:     }
10112: # Start grading
10113:     my $pcorrect=$env{'form.pcorrect'};
10114:     my $pincorrect=$env{'form.pincorrect'};
10115:     my $storecount=0;
10116:     my %users=();
10117:     foreach my $key (keys(%env)) {
10118:        my $user='';
10119:        if ($key=~/^form\.student\:(.*)$/) {
10120:           $user=$1;
10121:        }
10122:        if ($key=~/^form\.unknown\:(.*)$/) {
10123:           my $id=$1;
10124:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
10125:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
10126:           } elsif ($env{'form.multi'.$id}) {
10127:              $user=$env{'form.multi'.$id};
10128:           }
10129:        }
10130:        if ($user) {
10131:           if ($users{$user}) {
10132:              $result.='<br /><span class="LC_warning">'.
10133:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
10134:                       '</span><br />';
10135:           }
10136:           $users{$user}=1; 
10137:           my @answer=split(/\,/,$env{$key});
10138:           my $sum=0;
10139:           my $realnumber=$number;
10140:           for (my $i=0;$i<$number;$i++) {
10141:              if  ($correct[$i] eq '-') {
10142:                 $realnumber--;
10143:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/))  {
10144:                 if ($gradingmechanism eq 'attendance') {
10145:                    $sum+=$pcorrect;
10146:                 } elsif ($correct[$i] eq '*') {
10147:                    $sum+=$pcorrect;
10148:                 } else {
10149: # We actually grade if correct or not
10150:                    my $increment=$pincorrect;
10151: # Special case: numerical answer "0"
10152:                    if ($correct[$i] eq '0') {
10153:                       if ($answer[$i]=~/^[0\.]+$/) {
10154:                          $increment=$pcorrect;
10155:                       }
10156: # General numerical answer, both evaluate to something non-zero
10157:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
10158:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
10159:                          $increment=$pcorrect;
10160:                       }
10161: # Must be just alphanumeric
10162:                    } elsif ($answer[$i] eq $correct[$i]) {
10163:                       $increment=$pcorrect;
10164:                    }
10165:                    $sum+=$increment;
10166:                 }
10167:              }
10168:           }
10169:           my $ave=$sum/(100*$realnumber);
10170: # Store
10171:           my ($username,$domain)=split(/\:/,$user);
10172:           my %grades=();
10173:           $grades{"resource.$part.solved"}='correct_by_override';
10174:           $grades{"resource.$part.awarded"}=$ave;
10175:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
10176:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
10177:                                                  $env{'request.course.id'},
10178:                                                  $domain,$username);
10179:           if ($returncode ne 'ok') {
10180:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
10181:           } else {
10182:              $storecount++;
10183:           }
10184:        }
10185:     }
10186: # We are done
10187:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
10188:              '</td>'.
10189:              &Apache::loncommon::end_data_table_row().
10190:              &Apache::loncommon::end_data_table();
10191:     return $result;
10192: }
10193: 
10194: sub navmap_errormsg {
10195:     return '<div class="LC_error">'.
10196:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
10197:            &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>').
10198:            '</div>';
10199: }
10200: 
10201: sub startpage {
10202:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js) = @_;
10203:     if ($nomenu) {
10204:         $r->print(&Apache::loncommon::start_page("Student's Version",$js,{'only_body' => '1'}));
10205:     } else {
10206:         unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
10207:         $r->print(&Apache::loncommon::start_page('Grading',$js,
10208:                                                  {'bread_crumbs' => $crumbs}));
10209:         &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
10210:     }
10211:     unless ($nodisplayflag) {
10212:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
10213:     }
10214: }
10215: 
10216: sub select_problem {
10217:     my ($r)=@_;
10218:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
10219:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1));
10220:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
10221:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
10222: }
10223: 
10224: sub handler {
10225:     my $request=$_[0];
10226:     &reset_caches();
10227:     if ($request->header_only) {
10228:         &Apache::loncommon::content_type($request,'text/html');
10229:         $request->send_http_header;
10230:         return OK;
10231:     }
10232:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
10233: 
10234: # see what command we need to execute
10235: 
10236:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
10237:     my $command=$commands[0];
10238: 
10239:     &init_perm();
10240:     if (!$env{'request.course.id'}) {
10241:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
10242:                 ($command =~ /^scantronupload/)) {
10243:             # Not in a course.
10244:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
10245:             return HTTP_NOT_ACCEPTABLE;
10246:         }
10247:     } elsif (!%perm) {
10248:         $request->internal_redirect('/adm/quickgrades');
10249:         return OK;
10250:     }
10251:     &Apache::loncommon::content_type($request,'text/html');
10252:     $request->send_http_header;
10253: 
10254:     if ($#commands > 0) {
10255: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
10256:     }
10257: 
10258: # see what the symb is
10259: 
10260:     my $symb=$env{'form.symb'};
10261:     unless ($symb) {
10262:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
10263:        $symb=&Apache::lonnet::symbread($url);
10264:     }
10265:     &Apache::lonenc::check_decrypt(\$symb);
10266: 
10267:     $ssi_error = 0;
10268:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
10269: #
10270: # Not called from a resource, but inside a course
10271: #    
10272:         &startpage($request,undef,[],1,1);
10273:         &select_problem($request);
10274:     } else {
10275: 	if ($command eq 'submission' && $perm{'vgr'}) {
10276:             my ($stuvcurrent,$stuvdisp,$versionform,$js);
10277:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
10278:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
10279:                     &choose_task_version_form($symb,$env{'form.student'},
10280:                                               $env{'form.userdom'});
10281:             }
10282:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
10283:             if ($versionform) {
10284:                 $request->print($versionform);
10285:             }
10286:             $request->print('<br clear="all" />');
10287: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
10288:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
10289:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
10290:                 &choose_task_version_form($symb,$env{'form.student'},
10291:                                           $env{'form.userdom'},
10292:                                           $env{'form.inhibitmenu'});
10293:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
10294:             if ($versionform) {
10295:                 $request->print($versionform);
10296:             }
10297:             $request->print('<br clear="all" />');
10298:             $request->print(&show_previous_task_version($request,$symb));
10299: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
10300:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10301:                                        {href=>'',text=>'Select student'}],1,1);
10302: 	    &pickStudentPage($request,$symb);
10303: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
10304:             &startpage($request,$symb,
10305:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10306:                                        {href=>'',text=>'Select student'},
10307:                                        {href=>'',text=>'Grade student'}],1,1);
10308: 	    &displayPage($request,$symb);
10309: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
10310:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10311:                                        {href=>'',text=>'Select student'},
10312:                                        {href=>'',text=>'Grade student'},
10313:                                        {href=>'',text=>'Store grades'}],1,1);
10314: 	    &updateGradeByPage($request,$symb);
10315: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
10316:             &startpage($request,$symb,[{href=>'',text=>'...'},
10317:                                        {href=>'',text=>'Modify grades'}]);
10318: 	    &processGroup($request,$symb);
10319: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
10320:             &startpage($request,$symb);
10321: 	    $request->print(&grading_menu($request,$symb));
10322: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
10323:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
10324: 	    $request->print(&submit_options($request,$symb));
10325:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
10326:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
10327:             $request->print(&listStudents($request,$symb,'graded'));
10328:         } elsif ($command eq 'table' && $perm{'vgr'}) {
10329:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
10330:             $request->print(&submit_options_table($request,$symb));
10331:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
10332:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
10333:             $request->print(&submit_options_sequence($request,$symb));
10334: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
10335:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
10336: 	    $request->print(&viewgrades($request,$symb));
10337: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
10338:             &startpage($request,$symb,[{href=>'',text=>'...'},
10339:                                        {href=>'',text=>'Store grades'}]);
10340: 	    $request->print(&processHandGrade($request,$symb));
10341: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
10342:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
10343:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
10344:                                                                              text=>"Modify grades"},
10345:                                        {href=>'', text=>"Store grades"}]);
10346: 	    $request->print(&editgrades($request,$symb));
10347:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
10348:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
10349:             $request->print(&initialverifyreceipt($request,$symb));
10350: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
10351:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
10352:                                        {href=>'',text=>'Verification Result'}]);
10353: 	    $request->print(&verifyreceipt($request,$symb));
10354:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
10355:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
10356:             $request->print(&process_clicker($request,$symb));
10357:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
10358:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
10359:                                        {href=>'', text=>'Process clicker file'}]);
10360:             $request->print(&process_clicker_file($request,$symb));
10361:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
10362:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
10363:                                        {href=>'', text=>'Process clicker file'},
10364:                                        {href=>'', text=>'Store grades'}]);
10365:             $request->print(&assign_clicker_grades($request,$symb));
10366: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
10367:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10368: 	    $request->print(&upcsvScores_form($request,$symb));
10369: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
10370:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10371: 	    $request->print(&csvupload($request,$symb));
10372: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
10373:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10374: 	    $request->print(&csvuploadmap($request,$symb));
10375: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
10376: 	    if ($env{'form.associate'} ne 'Reverse Association') {
10377:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10378: 		$request->print(&csvuploadoptions($request,$symb));
10379: 	    } else {
10380: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
10381: 		    $env{'form.upfile_associate'} = 'reverse';
10382: 		} else {
10383: 		    $env{'form.upfile_associate'} = 'forward';
10384: 		}
10385:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10386: 		$request->print(&csvuploadmap($request,$symb));
10387: 	    }
10388: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
10389:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10390: 	    $request->print(&csvuploadassign($request,$symb));
10391: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
10392:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10393: 	    $request->print(&scantron_selectphase($request,undef,$symb));
10394:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
10395:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10396:  	    $request->print(&scantron_do_warning($request,$symb));
10397: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
10398:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10399: 	    $request->print(&scantron_validate_file($request,$symb));
10400: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
10401:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10402: 	    $request->print(&scantron_process_students($request,$symb));
10403:  	} elsif ($command eq 'scantronupload' && 
10404:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10405: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10406:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10407:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
10408:  	} elsif ($command eq 'scantronupload_save' &&
10409:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10410: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10411:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10412:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
10413:  	} elsif ($command eq 'scantron_download' &&
10414: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
10415:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10416:  	    $request->print(&scantron_download_scantron_data($request,$symb));
10417:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
10418:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10419:             $request->print(&checkscantron_results($request,$symb));
10420:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
10421:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
10422:             $request->print(&submit_options_download($request,$symb));
10423:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
10424:             &startpage($request,$symb,
10425:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
10426:     {href=>'', text=>'Download submissions'}]);
10427:             &submit_download_link($request,$symb);
10428: 	} elsif ($command) {
10429:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
10430: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
10431: 	}
10432:     }
10433:     if ($ssi_error) {
10434: 	&ssi_print_error($request);
10435:     }
10436:     if ($env{'form.inhibitmenu'}) {
10437:         $request->print(&Apache::loncommon::end_page());
10438:     } else {
10439:         &Apache::lonquickgrades::endGradeScreen($request);
10440:     }
10441:     &reset_caches();
10442:     return OK;
10443: }
10444: 
10445: 1;
10446: 
10447: __END__;
10448: 
10449: 
10450: =head1 NAME
10451: 
10452: Apache::grades
10453: 
10454: =head1 SYNOPSIS
10455: 
10456: Handles the viewing of grades.
10457: 
10458: This is part of the LearningOnline Network with CAPA project
10459: described at http://www.lon-capa.org.
10460: 
10461: =head1 OVERVIEW
10462: 
10463: Do an ssi with retries:
10464: While I'd love to factor out this with the version in lonprintout,
10465: 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
10466: I'm not quite ready to invent (e.g. an ssi_with_retry object).
10467: 
10468: At least the logic that drives this has been pulled out into loncommon.
10469: 
10470: 
10471: 
10472: ssi_with_retries - Does the server side include of a resource.
10473:                      if the ssi call returns an error we'll retry it up to
10474:                      the number of times requested by the caller.
10475:                      If we still have a problem, no text is appended to the
10476:                      output and we set some global variables.
10477:                      to indicate to the caller an SSI error occurred.  
10478:                      All of this is supposed to deal with the issues described
10479:                      in LON-CAPA BZ 5631 see:
10480:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
10481:                      by informing the user that this happened.
10482: 
10483: Parameters:
10484:   resource   - The resource to include.  This is passed directly, without
10485:                interpretation to lonnet::ssi.
10486:   form       - The form hash parameters that guide the interpretation of the resource
10487:                
10488:   retries    - Number of retries allowed before giving up completely.
10489: Returns:
10490:   On success, returns the rendered resource identified by the resource parameter.
10491: Side Effects:
10492:   The following global variables can be set:
10493:    ssi_error                - If an unrecoverable error occurred this becomes true.
10494:                               It is up to the caller to initialize this to false
10495:                               if desired.
10496:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
10497:                               of the resource that could not be rendered by the ssi
10498:                               call.
10499:    ssi_error_message   - The error string fetched from the ssi response
10500:                               in the event of an error.
10501: 
10502: 
10503: =head1 HANDLER SUBROUTINE
10504: 
10505: ssi_with_retries()
10506: 
10507: =head1 SUBROUTINES
10508: 
10509: =over
10510: 
10511: =head1 Routines to display previous version of a Task for a specific student
10512: 
10513: Tasks are graded pass/fail. Students who have yet to pass a particular Task
10514: can receive another opportunity. Access to tasks is slot-based. If a slot
10515: requires a proctor to check-in the student, a new version of the Task will
10516: be created when the student is checked in to the new opportunity.
10517: 
10518: If a particular student has tried two or more versions of a particular task,
10519: the submission screen provides a user with vgr privileges (e.g., a Course
10520: Coordinator) the ability to display a previous version worked on by the
10521: student.  By default, the current version is displayed. If a previous version
10522: has been selected for display, submission data are only shown that pertain
10523: to that particular version, and the interface to submit grades is not shown.
10524: 
10525: =over 4
10526: 
10527: =item show_previous_task_version()
10528: 
10529: Displays a specified version of a student's Task, as the student sees it.
10530: 
10531: Inputs: 2
10532:         request - request object
10533:         symb    - unique symb for current instance of resource
10534: 
10535: Output: None.
10536: 
10537: Side Effects: calls &show_problem() to print version of Task, with
10538:               version contained in form item: $env{'form.previousversion'}
10539: 
10540: =item choose_task_version_form()
10541: 
10542: Displays a web form used to select which version of a student's view of a
10543: Task should be displayed.  Either launches a pop-up window, or replaces
10544: content in existing pop-up, or replaces page in main window.
10545: 
10546: Inputs: 4
10547:         symb    - unique symb for current instance of resource
10548:         uname   - username of student
10549:         udom    - domain of student
10550:         nomenu  - 1 if display is in a pop-up window, and hence no menu
10551:                   breadcrumbs etc., are displayed
10552: 
10553: Output: 4
10554:         current   - student's current version
10555:         displayed - student's version being displayed
10556:         result    - scalar containing HTML for web form used to switch to
10557:                     a different version (or a link to close window, if pop-up).
10558:         js        - javascript for processing selection in versions web form
10559: 
10560: Side Effects: None.
10561: 
10562: =item previous_display_javascript()
10563: 
10564: Inputs: 2
10565:         nomenu  - 1 if display is in a pop-up window, and hence no menu
10566:                   breadcrumbs etc., are displayed.
10567:         current - student's current version number.
10568: 
10569: Output: 1
10570:         js      - javascript for processing selection in versions web form.
10571: 
10572: Side Effects: None.
10573: 
10574: =back
10575: 
10576: =head1 Routines to process bubblesheet data.
10577: 
10578: =over 4
10579: 
10580: =item scantron_get_correction() : 
10581: 
10582:    Builds the interface screen to interact with the operator to fix a
10583:    specific error condition in a specific scanline
10584: 
10585:  Arguments:
10586:     $r           - Apache request object
10587:     $i           - number of the current scanline
10588:     $scan_record - hash ref as returned from &scantron_parse_scanline()
10589:     $scan_config - hash ref as returned from &get_scantron_config()
10590:     $line        - full contents of the current scanline
10591:     $error       - error condition, valid values are
10592:                    'incorrectCODE', 'duplicateCODE',
10593:                    'doublebubble', 'missingbubble',
10594:                    'duplicateID', 'incorrectID'
10595:     $arg         - extra information needed
10596:        For errors:
10597:          - duplicateID   - paper number that this studentID was seen before on
10598:          - duplicateCODE - array ref of the paper numbers this CODE was
10599:                            seen on before
10600:          - incorrectCODE - current incorrect CODE 
10601:          - doublebubble  - array ref of the bubble lines that have double
10602:                            bubble errors
10603:          - missingbubble - array ref of the bubble lines that have missing
10604:                            bubble errors
10605: 
10606:    $randomorder - True if exam folder has randomorder set
10607:    $randompick  - True if exam folder has randompick set
10608:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
10609:                      for current line to question number used for same question
10610:                      in "Master Seqence" (as seen by Course Coordinator).
10611:    $startline   - Reference to hash where key is question number (0 is first)
10612:                   and value is number of first bubble line for current student
10613:                   or code-based randompick and/or randomorder.
10614: 
10615: 
10616: 
10617: =item  scantron_get_maxbubble() : 
10618: 
10619:    Arguments:
10620:        $nav_error  - Reference to scalar which is a flag to indicate a
10621:                       failure to retrieve a navmap object.
10622:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
10623:        calling routine should trap the error condition and display the warning
10624:        found in &navmap_errormsg().
10625: 
10626:        $scantron_config - Reference to bubblesheet format configuration hash.
10627: 
10628:    Returns the maximum number of bubble lines that are expected to
10629:    occur. Does this by walking the selected sequence rendering the
10630:    resource and then checking &Apache::lonxml::get_problem_counter()
10631:    for what the current value of the problem counter is.
10632: 
10633:    Caches the results to $env{'form.scantron_maxbubble'},
10634:    $env{'form.scantron.bubble_lines.n'}, 
10635:    $env{'form.scantron.first_bubble_line.n'} and
10636:    $env{"form.scantron.sub_bubblelines.n"}
10637:    which are the total number of bubble lines, the number of bubble
10638:    lines for response n and number of the first bubble line for response n,
10639:    and a comma separated list of numbers of bubble lines for sub-questions
10640:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
10641: 
10642: 
10643: =item  scantron_validate_missingbubbles() : 
10644: 
10645:    Validates all scanlines in the selected file to not have any
10646:     answers that don't have bubbles that have not been verified
10647:     to be bubble free.
10648: 
10649: =item  scantron_process_students() : 
10650: 
10651:    Routine that does the actual grading of the bubblesheet information.
10652: 
10653:    The parsed scanline hash is added to %env 
10654: 
10655:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
10656:    foreach resource , with the form data of
10657: 
10658: 	'submitted'     =>'scantron' 
10659: 	'grade_target'  =>'grade',
10660: 	'grade_username'=> username of student
10661: 	'grade_domain'  => domain of student
10662: 	'grade_courseid'=> of course
10663: 	'grade_symb'    => symb of resource to grade
10664: 
10665:     This triggers a grading pass. The problem grading code takes care
10666:     of converting the bubbled letter information (now in %env) into a
10667:     valid submission.
10668: 
10669: =item  scantron_upload_scantron_data() :
10670: 
10671:     Creates the screen for adding a new bubblesheet data file to a course.
10672: 
10673: =item  scantron_upload_scantron_data_save() : 
10674: 
10675:    Adds a provided bubble information data file to the course if user
10676:    has the correct privileges to do so. 
10677: 
10678: =item  valid_file() :
10679: 
10680:    Validates that the requested bubble data file exists in the course.
10681: 
10682: =item  scantron_download_scantron_data() : 
10683: 
10684:    Shows a list of the three internal files (original, corrected,
10685:    skipped) for a specific bubblesheet data file that exists in the
10686:    course.
10687: 
10688: =item  scantron_validate_ID() : 
10689: 
10690:    Validates all scanlines in the selected file to not have any
10691:    invalid or underspecified student/employee IDs
10692: 
10693: =item navmap_errormsg() :
10694: 
10695:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
10696:    Should be called whenever the request to instantiate a navmap object fails.
10697: 
10698: =back
10699: 
10700: =back
10701: 
10702: =cut

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